From 37a62fb3e3e8516de8bc55cdc2e88ba0e12bb239 Mon Sep 17 00:00:00 2001 From: lgv Date: Tue, 13 Oct 2026 09:18:06 +0800 Subject: [PATCH] feat(arm): add collision-aware planning and refactor motion control Integrate OMPL RRTConnect and quintic B-spline smoothing into moveP, reuse the B-spline trajectory generator for moveJ, and remove the TOPPRA paths and dependencies. Separate joint and Cartesian planners, smoothers, and the standalone curve math library. Move speedL execution into SpeedLExecutor, tighten velocity QP feasibility, and add adaptive speed reduction, braking recovery, feedback-derived TCP velocity, and grouped cyclic velocity submission. Improve MuJoCo control cycle synchronization and camera streaming. Centralize kinematics and collision geometry in RobotModel, expose box obstacles through CollisionChecker, and extract SelfCollisionMonitor for protective stops and recovery. Add cancellable moveP pre-approach and configurable failure recovery to the touch workflow, with updated configs, documentation, and regression coverage. Validation: recorded -j8 build and 133 passing tests on 2026-10-08, including headless MuJoCo checks for eight target poses and seven moveJ returns. Static scene configuration removal passed 27 follow-up tests and six arm configuration parses. Staged diff and shell syntax checks pass; no new hardware tests were run for this commit. --- README.md | 10 + cmvr-es/CMakeLists.txt | 4 + cmvr-es/algorithms/CMakeLists.txt | 3 +- .../collision_detection/CMakeLists.txt | 39 +- .../collision_benchmark.cpp} | 4 +- .../include/collision_checker.h | 131 ++ .../include/distance_sampling_policy.h | 11 +- .../include/self_collision_checker.h | 82 - .../src/self_collision_checker.cpp | 403 ----- .../test/self_collision_checker_test.cpp | 236 --- .../src/collision_checker.cpp | 468 ++++++ .../src/distance_sampling_policy.cpp | 18 +- .../test/collision_checker_test.cpp | 840 +++++++++++ cmvr-es/algorithms/controllers/CMakeLists.txt | 3 - .../controllers/arm_control/CMakeLists.txt | 17 - .../include/cartesian_velocity_controller.h | 92 -- .../src/cartesian_velocity_controller.cpp | 379 ----- .../cartesian_velocity_controller_test.cpp | 131 -- .../pbvs/include/pbvs_controller.h | 201 +-- .../controllers/pbvs/src/pbvs_controller.cpp | 1228 +++++++-------- .../kinematics/ik_solver/CMakeLists.txt | 1 + .../ik_solver/common/include/ik_solver.h | 29 +- .../ik_solver/common/include/urdf_parser.h | 32 +- .../ik_solver/common/src/ik_solver.cpp | 65 +- .../ik_solver/common/src/urdf_parser.cpp | 26 +- .../pinocchio/include/pinocchio_ik_base.h | 38 +- .../include/pinocchio_qp_ik_solver.h | 20 + .../pinocchio/src/pinocchio_dls_ik_solver.cpp | 48 +- .../pinocchio/src/pinocchio_ik_base.cpp | 95 +- .../pinocchio/src/pinocchio_qp_ik_solver.cpp | 172 ++- .../src/pinocchio_qp_ik_solver_test.cpp | 368 ++++- .../algorithms/motion_planner/CMakeLists.txt | 2 - .../motion_planner/arm_motion/CMakeLists.txt | 35 - .../cartesian_motion_planner.h | 58 - .../cartesian_motion_planner_factory.h | 63 - .../pinocchio_cartesian_motion_planner.h | 117 -- .../pinocchio_cartesian_motion_planner.cpp | 1321 ----------------- .../test/pinocchio_speedl_limits_test.cpp | 213 --- .../common/include/twist_limiter_config.h | 55 - .../joint_motion_planner_factory.h | 55 - .../include/toppra_joint_motion_planner.h | 46 - .../src/toppra_joint_motion_planner.cpp | 258 ---- .../test/toppra_joint_motion_planner_test.cpp | 139 -- .../motion_planner/base_motion/CMakeLists.txt | 49 - .../include/cartesian_twist_limiter.h | 249 ---- .../src/cartesian_twist_limiter.cpp | 573 ------- .../cartesian_twist_limiter_reversal_test.cpp | 118 -- .../joint_trajectory_planner.h | 90 -- .../include/toppra_joint_trajectory_planner.h | 209 --- .../src/toppra_joint_trajectory_planner.cpp | 527 ------- .../test/toppra_multi_waypoint_test.cpp | 228 --- .../include/s_curve_position_planner.h | 100 -- .../include/s_curve_velocity_planner.h | 240 --- .../s_curve/src/s_curve_position_planner.cpp | 191 --- .../s_curve/src/s_curve_velocity_planner.cpp | 578 -------- .../s_curve_velocity_planner_stop_test.cpp | 77 - cmvr-es/algorithms/planner/CMakeLists.txt | 49 + .../cartesian_motion_planner_factory.h | 64 + .../cartesian/cartesian_trajectory_planner.h | 41 + .../cartesian/cartesian_velocity_planner.h | 62 + .../pinocchio_cartesian_trajectory_planner.h | 63 + .../pinocchio_cartesian_velocity_planner.h | 100 ++ ...pinocchio_cartesian_trajectory_planner.cpp | 679 +++++++++ .../pinocchio_cartesian_velocity_planner.cpp | 1017 +++++++++++++ .../test/pinocchio_speedl_limits_test.cpp | 1161 +++++++++++++++ .../s_curve/include/s_curve_planner.h | 136 ++ .../s_curve/include/s_curve_planner_config.h | 47 + .../cartesian/s_curve/src/s_curve_planner.cpp | 420 ++++++ .../test/s_curve_planner_reversal_test.cpp | 320 ++++ .../planner/joint/joint_path_planner.h | 62 + .../joint/joint_path_planner_factory.h | 48 + .../planner/joint/ompl/include/rrt_connect.h | 28 + .../planner/joint/ompl/src/rrt_connect.cpp | 262 ++++ .../test/rrt_connect_self_collision_test.cpp | 222 +++ .../joint/ompl/test/rrt_connect_test.cpp | 304 ++++ cmvr-es/algorithms/smoother/CMakeLists.txt | 11 + .../bspline/include/bspline_smoother.h | 23 + .../smoother/bspline/src/bspline_smoother.cpp | 128 ++ .../bspline/test/bspline_smoother_test.cpp | 519 +++++++ .../smoother/joint_trajectory_smoother.h | 24 + .../joint_trajectory_smoother_factory.h | 28 + .../joint_trajectory_validation.h} | 58 +- cmvr-es/common/math/qp_solver.h | 21 +- cmvr-es/common/math/transform_math.h | 7 - cmvr-es/common/types/arm/arm_types.h | 46 +- cmvr-es/config/devices/arm/arm.pb.txt | 72 +- .../config/devices/arm/arm_gen2_mujoco.pb.txt | 38 +- cmvr-es/config/devices/arm/arm_mujoco.pb.txt | 39 +- .../config/devices/arm/arm_mujoco_qp.pb.txt | 39 +- cmvr-es/config/devices/arm/arm_qp.pb.txt | 39 +- .../devices/arm/ethercat_dual_arm.pb.txt | 72 +- cmvr-es/config/manager/device_manager.pb.txt | 14 +- cmvr-es/config/manager/task_manager.pb.txt | 4 +- .../touch_screen_task.pb.txt | 17 +- .../touch_screen_task_mujoco.pb.txt | 34 +- cmvr-es/curves/CMakeLists.txt | 10 + .../curves/bspline/include/quintic_bspline.h | 56 + .../curves/bspline/src/quintic_bspline.cpp | 264 ++++ .../s_curve/include/s_curve.h | 111 +- .../s_curve/src/s_curve.cpp | 342 ++++- .../arm/motor_robot_arm/CMakeLists.txt | 18 +- .../arm/motor_robot_arm/SPEEDL_REVERSAL.md | 41 +- .../motor_robot_arm/include/motor_robot_arm.h | 65 +- .../include/speed_l_executor.h | 119 ++ .../motor_robot_arm/src/motor_robot_arm.cpp | 993 +++++++++++-- .../src/motor_robot_arm_gen2_mujoco_test.cpp | 58 +- .../src/motor_robot_arm_mujoco_test.cpp | 795 +++++++++- .../src/motor_robot_arm_speedl_stop_test.cpp | 3 + .../src/rrt_connect_mujoco_test.cpp | 357 +++++ .../motor_robot_arm/src/speed_l_executor.cpp | 636 ++++++++ .../src/speed_l_executor_test.cpp | 1031 +++++++++++++ .../src/speedl_reversal_mujoco_test.cpp | 54 +- cmvr-es/devices/arm/robot_arm.h | 23 + .../mujoco_camera/include/mujoco_camera.h | 25 +- .../mujoco_camera/src/mujoco_camera.cpp | 259 +++- .../mujoco_camera/src/mujoco_camera_test.cpp | 146 ++ .../include/cia402/cia402_protocol.h | 11 +- .../include/vendor/eyou/eyou_motor.h | 3 + .../src/cia402/cia402_protocol.cpp | 73 +- .../src/vendor/eyou/eyou_motor.cpp | 36 + .../drivers/mujoco/include/mujoco_motor.h | 7 + .../motor/drivers/mujoco/src/mujoco_motor.cpp | 78 + cmvr-es/devices/motor/manager/CMakeLists.txt | 2 +- .../motor/manager/include/motor_manager.h | 3 + .../motor/manager/src/motor_manager.cpp | 115 +- cmvr-es/environment/CMakeLists.txt | 13 + cmvr-es/environment/include/robot_model.h | 104 ++ cmvr-es/environment/src/robot_model.cpp | 310 ++++ cmvr-es/safety/CMakeLists.txt | 18 + .../include/self_collision_monitor.h | 92 ++ .../src/self_collision_monitor.cpp | 557 +++++++ .../grpc/action/tests/action_queue_test.cpp | 4 +- .../mujoco_world/include/mujoco_world.h | 21 + .../mujoco/mujoco_world/src/mujoco_world.cpp | 123 +- cmvr-es/task/CMakeLists.txt | 4 +- .../include/self_collision_task.h | 74 +- .../src/self_collision_task.cpp | 599 +------- .../include/touch_screen_task.h | 41 +- .../src/touch_screen_task.cpp | 657 ++++---- .../src/touch_screen_task_test.cpp | 801 +++++++++- data/ik/plot_joint_traj.py | 59 - .../v0.6.2/include/toppra/algorithm.hpp | 168 --- .../include/toppra/algorithm/toppra.hpp | 21 - .../v0.6.2/include/toppra/constraint.hpp | 174 --- .../constraint/cartesian_velocity_norm.hpp | 94 -- .../cartesian_velocity_norm/pinocchio.hpp | 86 -- .../toppra/constraint/joint_torque.hpp | 113 -- .../constraint/joint_torque/pinocchio.hpp | 87 -- .../constraint/linear_joint_acceleration.hpp | 36 - .../constraint/linear_joint_velocity.hpp | 86 -- .../toppra/v0.6.2/include/toppra/export.hpp | 43 - .../v0.6.2/include/toppra/geometric_path.hpp | 116 -- .../geometric_path/piecewise_poly_path.hpp | 161 -- .../v0.6.2/include/toppra/parametrizer.hpp | 75 - .../toppra/parametrizer/const_accel.hpp | 52 - .../include/toppra/parametrizer/spline.hpp | 47 - .../toppra/v0.6.2/include/toppra/solver.hpp | 138 -- .../include/toppra/solver/glpk-wrapper.hpp | 54 - .../include/toppra/solver/qpOASES-wrapper.hpp | 66 - .../v0.6.2/include/toppra/solver/seidel.hpp | 43 - .../toppra/v0.6.2/include/toppra/toppra.hpp | 86 -- .../lib/cmake/toppra/toppraConfig.cmake | 13 - .../cmake/toppra/toppraTargets-noconfig.cmake | 19 - .../lib/cmake/toppra/toppraTargets.cmake | 107 -- .../toppra/v0.6.2/lib/libtoppra.so | Bin 6628800 -> 0 bytes .../share/eigen3/cmake/Eigen3Config.cmake | 17 + .../eigen3/cmake/Eigen3ConfigVersion.cmake | 9 + .../ompl/base/ConstrainedSpaceInformation.h | 233 +++ .../v2.0.2/include/ompl/base/Constraint.h | 325 ++++ .../ompl/v2.0.2/include/ompl/base/Cost.h | 70 + .../ompl/base/DiscreteMotionValidator.h | 78 + .../v2.0.2/include/ompl/base/GenericParam.h | 316 ++++ .../ompl/v2.0.2/include/ompl/base/Goal.h | 154 ++ .../ompl/v2.0.2/include/ompl/base/GoalTypes.h | 70 + .../include/ompl/base/MotionValidator.h | 144 ++ .../include/ompl/base/OptimizationObjective.h | 306 ++++ .../ompl/v2.0.2/include/ompl/base/Path.h | 128 ++ .../ompl/v2.0.2/include/ompl/base/Planner.h | 432 ++++++ .../v2.0.2/include/ompl/base/PlannerData.h | 437 ++++++ .../include/ompl/base/PlannerDataGraph.h | 94 ++ .../include/ompl/base/PlannerDataStorage.h | 294 ++++ .../v2.0.2/include/ompl/base/PlannerStatus.h | 115 ++ .../ompl/base/PlannerTerminationCondition.h | 136 ++ .../ompl/base/PrecomputedStateSampler.h | 72 + .../include/ompl/base/ProblemDefinition.h | 439 ++++++ .../include/ompl/base/ProjectionEvaluator.h | 334 +++++ .../v2.0.2/include/ompl/base/ScopedState.h | 553 +++++++ .../ompl/base/SolutionNonExistenceProof.h | 73 + .../include/ompl/base/SpaceInformation.h | 459 ++++++ .../ompl/v2.0.2/include/ompl/base/State.h | 133 ++ .../v2.0.2/include/ompl/base/StateSampler.h | 195 +++ .../include/ompl/base/StateSamplerArray.h | 148 ++ .../v2.0.2/include/ompl/base/StateSpace.h | 841 +++++++++++ .../include/ompl/base/StateSpaceTypes.h | 109 ++ .../v2.0.2/include/ompl/base/StateStorage.h | 286 ++++ .../include/ompl/base/StateValidityChecker.h | 198 +++ .../include/ompl/base/TypedSpaceInformation.h | 140 ++ .../ompl/base/TypedStateValidityChecker.h | 85 ++ .../include/ompl/base/ValidStateSampler.h | 138 ++ .../include/ompl/base/goals/GoalLazySamples.h | 190 +++ .../include/ompl/base/goals/GoalRegion.h | 96 ++ .../ompl/base/goals/GoalSampleableRegion.h | 83 ++ .../include/ompl/base/goals/GoalSpace.h | 88 ++ .../include/ompl/base/goals/GoalState.h | 91 ++ .../include/ompl/base/goals/GoalStates.h | 100 ++ .../objectives/ControlDurationObjective.h | 72 + .../MaximizeMinClearanceObjective.h | 70 + .../MechanicalWorkOptimizationObjective.h | 72 + .../ompl/base/objectives/MinimaxObjective.h | 70 + .../base/objectives/MinimizeArrivalTime.h | 70 + .../PathLengthOptimizationObjective.h | 79 + .../objectives/StateCostIntegralObjective.h | 130 ++ .../VFMechanicalWorkOptimizationObjective.h | 97 ++ ...VFUpstreamCriterionOptimizationObjective.h | 112 ++ .../samplers/BridgeTestValidStateSampler.h | 95 ++ .../base/samplers/ConditionalStateSampler.h | 112 ++ .../base/samplers/DeterministicStateSampler.h | 186 +++ .../base/samplers/GaussianValidStateSampler.h | 81 + .../ompl/base/samplers/InformedStateSampler.h | 171 +++ .../MaximizeClearanceValidStateSampler.h | 86 ++ .../MinimumClearanceValidStateSampler.h | 90 ++ .../samplers/ObstacleBasedValidStateSampler.h | 75 + .../base/samplers/UniformValidStateSampler.h | 66 + .../deterministic/DeterministicSequence.h | 64 + .../samplers/deterministic/HaltonSequence.h | 104 ++ .../deterministic/PrecomputedSequence.h | 79 + .../samplers/informed/OrderedInfSampler.h | 106 ++ .../informed/PathLengthDirectInfSampler.h | 194 +++ .../samplers/informed/RejectionInfSampler.h | 96 ++ .../ompl/base/spaces/DiscreteStateSpace.h | 164 ++ .../base/spaces/Dubins3DMotionValidator.h | 179 +++ .../ompl/base/spaces/DubinsMotionValidator.h | 180 +++ .../ompl/base/spaces/DubinsStateSpace.h | 170 +++ .../ompl/base/spaces/EmptyStateSpace.h | 82 + .../ompl/base/spaces/HybridStateSpace.h | 111 ++ .../ompl/base/spaces/HybridTimeStateSpace.h | 207 +++ .../include/ompl/base/spaces/OwenStateSpace.h | 226 +++ .../ompl/base/spaces/RealVectorBounds.h | 91 ++ .../base/spaces/RealVectorStateProjections.h | 202 +++ .../ompl/base/spaces/RealVectorStateSpace.h | 206 +++ .../ompl/base/spaces/ReedsSheppStateSpace.h | 133 ++ .../include/ompl/base/spaces/SE2StateSpace.h | 137 ++ .../include/ompl/base/spaces/SE3StateSpace.h | 146 ++ .../include/ompl/base/spaces/SO2StateSpace.h | 131 ++ .../include/ompl/base/spaces/SO3StateSpace.h | 164 ++ .../ompl/base/spaces/SpaceTimeStateSpace.h | 112 ++ .../include/ompl/base/spaces/TimeStateSpace.h | 167 +++ .../ompl/base/spaces/TrochoidStateSpace.h | 176 +++ .../ompl/base/spaces/VanaOwenStateSpace.h | 254 ++++ .../include/ompl/base/spaces/VanaStateSpace.h | 248 ++++ .../ompl/base/spaces/WrapperStateSpace.h | 425 ++++++ .../ompl/base/spaces/constraint/AtlasChart.h | 269 ++++ .../base/spaces/constraint/AtlasStateSpace.h | 437 ++++++ .../spaces/constraint/ConstrainedStateSpace.h | 346 +++++ .../spaces/constraint/ProjectedStateSpace.h | 142 ++ .../constraint/TangentBundleStateSpace.h | 118 ++ .../spaces/special/KleinBottleStateSpace.h | 134 ++ .../base/spaces/special/MobiusStateSpace.h | 109 ++ .../base/spaces/special/SphereStateSpace.h | 120 ++ .../base/spaces/special/TorusStateSpace.h | 120 ++ .../CostConvergenceTerminationCondition.h | 83 ++ .../IterationTerminationCondition.h | 79 + .../ompl/v2.0.2/include/ompl/config.h | 60 + .../v2.0.2/include/ompl/control/Control.h | 122 ++ .../include/ompl/control/ControlSampler.h | 163 ++ .../include/ompl/control/ControlSpace.h | 290 ++++ .../include/ompl/control/ControlSpaceTypes.h | 64 + .../ompl/control/DirectedControlSampler.h | 107 ++ .../v2.0.2/include/ompl/control/ODESolver.h | 328 ++++ .../v2.0.2/include/ompl/control/PathControl.h | 223 +++ .../v2.0.2/include/ompl/control/PlannerData.h | 174 +++ .../include/ompl/control/PlannerDataStorage.h | 191 +++ .../control/SimpleDirectedControlSampler.h | 120 ++ .../v2.0.2/include/ompl/control/SimpleSetup.h | 298 ++++ .../include/ompl/control/SpaceInformation.h | 321 ++++ .../include/ompl/control/StatePropagator.h | 129 ++ .../ompl/control/SteeredControlSampler.h | 80 + .../ompl/control/planners/PlannerIncludes.h | 46 + .../include/ompl/control/planners/est/EST.h | 264 ++++ .../ompl/control/planners/kpiece/KPIECE1.h | 432 ++++++ .../ompl/control/planners/ltl/Automaton.h | 191 +++ .../ompl/control/planners/ltl/LTLPlanner.h | 210 +++ .../planners/ltl/LTLProblemDefinition.h | 74 + .../planners/ltl/LTLSpaceInformation.h | 104 ++ .../ompl/control/planners/ltl/ProductGraph.h | 258 ++++ .../planners/ltl/PropositionalDecomposition.h | 107 ++ .../include/ompl/control/planners/ltl/World.h | 117 ++ .../include/ompl/control/planners/pdst/PDST.h | 331 +++++ .../include/ompl/control/planners/rrt/HyRRT.h | 421 ++++++ .../include/ompl/control/planners/rrt/RRT.h | 195 +++ .../include/ompl/control/planners/sst/HySST.h | 592 ++++++++ .../include/ompl/control/planners/sst/SST.h | 279 ++++ .../control/planners/syclop/Decomposition.h | 122 ++ .../planners/syclop/GridDecomposition.h | 112 ++ .../ompl/control/planners/syclop/Syclop.h | 596 ++++++++ .../ompl/control/planners/syclop/SyclopEST.h | 84 ++ .../ompl/control/planners/syclop/SyclopRRT.h | 120 ++ .../control/spaces/DiscreteControlSpace.h | 150 ++ .../control/spaces/RealVectorControlSpace.h | 150 ++ .../ompl/datastructures/AdjacencyList.h | 124 ++ .../include/ompl/datastructures/BinaryHeap.h | 338 +++++ .../include/ompl/datastructures/DynamicSSSP.h | 290 ++++ .../ompl/datastructures/GreedyKCenters.h | 131 ++ .../v2.0.2/include/ompl/datastructures/Grid.h | 392 +++++ .../include/ompl/datastructures/GridB.h | 366 +++++ .../include/ompl/datastructures/GridN.h | 253 ++++ .../ompl/datastructures/LPAstarOnGraph.h | 413 ++++++ .../ompl/datastructures/NearestNeighbors.h | 118 ++ .../datastructures/NearestNeighborsFLANN.h | 354 +++++ .../datastructures/NearestNeighborsGNAT.h | 806 ++++++++++ .../NearestNeighborsGNATNoThreadSafety.h | 809 ++++++++++ .../datastructures/NearestNeighborsLinear.h | 176 +++ .../NearestNeighborsSqrtApprox.h | 133 ++ .../v2.0.2/include/ompl/datastructures/PDF.h | 291 ++++ .../include/ompl/datastructures/Permutation.h | 73 + .../PropositionalTriangularDecomposition.h | 98 ++ .../triangle/TriangularDecomposition.h | 194 +++ .../include/ompl/geometric/GeneticSearch.h | 208 +++ .../include/ompl/geometric/HillClimbing.h | 114 ++ .../include/ompl/geometric/PathGeometric.h | 280 ++++ .../ompl/geometric/PathHybridization.h | 172 +++ .../include/ompl/geometric/PathSimplifier.h | 316 ++++ .../include/ompl/geometric/SimpleSetup.h | 310 ++++ .../planners/AnytimePathShortening.h | 249 ++++ .../ompl/geometric/planners/PlannerIncludes.h | 45 + .../ompl/geometric/planners/cforest/CForest.h | 213 +++ .../planners/cforest/CForestStateSampler.h | 105 ++ .../cforest/CForestStateSpaceWrapper.h | 224 +++ .../ompl/geometric/planners/est/BiEST.h | 172 +++ .../include/ompl/geometric/planners/est/EST.h | 185 +++ .../ompl/geometric/planners/est/ProjEST.h | 248 ++++ .../experience/LightningRetrieveRepair.h | 200 +++ .../experience/ThunderRetrieveRepair.h | 202 +++ .../ompl/geometric/planners/fmt/BFMT.h | 646 ++++++++ .../include/ompl/geometric/planners/fmt/FMT.h | 508 +++++++ .../planners/informedtrees/ABITstar.h | 124 ++ .../planners/informedtrees/AITstar.h | 344 +++++ .../planners/informedtrees/BITstar.h | 562 +++++++ .../planners/informedtrees/EIRMstar.h | 87 ++ .../planners/informedtrees/EITstar.h | 453 ++++++ .../planners/informedtrees/aitstar/Edge.h | 97 ++ .../informedtrees/aitstar/ImplicitGraph.h | 250 ++++ .../informedtrees/aitstar/Queuetypes.h | 72 + .../planners/informedtrees/aitstar/Vertex.h | 312 ++++ .../informedtrees/bitstar/CostHelper.h | 344 +++++ .../informedtrees/bitstar/HelperFunctions.h | 95 ++ .../informedtrees/bitstar/IdGenerator.h | 78 + .../informedtrees/bitstar/ImplicitGraph.h | 485 ++++++ .../informedtrees/bitstar/SearchQueue.h | 287 ++++ .../planners/informedtrees/bitstar/Vertex.h | 351 +++++ .../informedtrees/eitstar/Direction.h | 58 + .../planners/informedtrees/eitstar/Edge.h | 81 + .../informedtrees/eitstar/ForwardQueue.h | 215 +++ .../eitstar/RandomGeometricGraph.h | 326 ++++ .../informedtrees/eitstar/ReverseQueue.h | 152 ++ .../planners/informedtrees/eitstar/State.h | 252 ++++ .../planners/informedtrees/eitstar/Vertex.h | 180 +++ .../ompl/geometric/planners/kpiece/BKPIECE1.h | 239 +++ .../planners/kpiece/Discretization.h | 357 +++++ .../ompl/geometric/planners/kpiece/KPIECE1.h | 257 ++++ .../geometric/planners/kpiece/LBKPIECE1.h | 238 +++ .../planners/lazyinformedtrees/BLITstar.h | 366 +++++ .../blitstar/ImplicitGraph.h | 262 ++++ .../lazyinformedtrees/blitstar/Queuetypes.h | 83 ++ .../lazyinformedtrees/blitstar/Vertex.h | 374 +++++ .../ompl/geometric/planners/pdst/PDST.h | 312 ++++ .../planners/prm/ConnectionStrategy.h | 201 +++ .../ompl/geometric/planners/prm/LazyPRM.h | 375 +++++ .../ompl/geometric/planners/prm/LazyPRMstar.h | 78 + .../include/ompl/geometric/planners/prm/PRM.h | 440 ++++++ .../ompl/geometric/planners/prm/PRMstar.h | 76 + .../ompl/geometric/planners/prm/SPARS.h | 591 ++++++++ .../ompl/geometric/planners/prm/SPARStwo.h | 540 +++++++ .../ompl/geometric/planners/rlrt/BiRLRT.h | 190 +++ .../ompl/geometric/planners/rlrt/RLRT.h | 175 +++ .../ompl/geometric/planners/rrt/AORRTC.h | 154 ++ .../geometric/planners/rrt/AOXRRTConnect.h | 283 ++++ .../ompl/geometric/planners/rrt/ATRRT.h | 361 +++++ .../ompl/geometric/planners/rrt/BiTRRT.h | 315 ++++ .../geometric/planners/rrt/InformedRRTstar.h | 76 + .../ompl/geometric/planners/rrt/LBTRRT.h | 300 ++++ .../ompl/geometric/planners/rrt/LazyLBTRRT.h | 333 +++++ .../ompl/geometric/planners/rrt/LazyRRT.h | 205 +++ .../include/ompl/geometric/planners/rrt/RRT.h | 200 +++ .../ompl/geometric/planners/rrt/RRTConnect.h | 201 +++ .../ompl/geometric/planners/rrt/RRTXstatic.h | 487 ++++++ .../ompl/geometric/planners/rrt/RRTsharp.h | 83 ++ .../ompl/geometric/planners/rrt/RRTstar.h | 529 +++++++ .../ompl/geometric/planners/rrt/SORRTstar.h | 72 + .../ompl/geometric/planners/rrt/STRRTstar.h | 332 +++++ .../ompl/geometric/planners/rrt/TRRT.h | 330 ++++ .../ompl/geometric/planners/rrt/TRRTstar.h | 523 +++++++ .../ompl/geometric/planners/rrt/TSRRT.h | 211 +++ .../ompl/geometric/planners/rrt/VFRRT.h | 154 ++ .../ompl/geometric/planners/rrt/pRRT.h | 185 +++ .../include/ompl/geometric/planners/sbl/SBL.h | 274 ++++ .../ompl/geometric/planners/sbl/pSBL.h | 273 ++++ .../include/ompl/geometric/planners/sst/SST.h | 286 ++++ .../ompl/geometric/planners/stride/STRIDE.h | 327 ++++ .../include/ompl/geometric/planners/xxl/XXL.h | 496 +++++++ .../geometric/planners/xxl/XXLDecomposition.h | 130 ++ .../planners/xxl/XXLPlanarDecomposition.h | 162 ++ .../planners/xxl/XXLPositionDecomposition.h | 128 ++ .../multilevel/datastructures/BundleSpace.h | 279 ++++ .../datastructures/BundleSpaceGraph.h | 438 ++++++ .../datastructures/BundleSpaceSequence.h | 153 ++ .../datastructures/BundleSpaceSequenceImpl.h | 409 +++++ .../multilevel/datastructures/Parameter.h | 144 ++ .../ParameterExponentialDecay.h | 98 ++ .../datastructures/ParameterSmoothStep.h | 76 + .../PlannerDataVertexAnnotated.h | 146 ++ .../datastructures/PlannerMultiLevel.h | 98 ++ .../multilevel/datastructures/Projection.h | 164 ++ .../datastructures/ProjectionFactory.h | 157 ++ .../datastructures/ProjectionTypes.h | 118 ++ .../graphsampler/GraphSampler.h | 103 ++ .../graphsampler/RandomDegreeVertex.h | 62 + .../datastructures/graphsampler/RandomEdge.h | 62 + .../graphsampler/RandomVertex.h | 62 + .../importance/BundleSpaceImportance.h | 72 + .../datastructures/importance/Exponential.h | 62 + .../datastructures/importance/Greedy.h | 66 + .../datastructures/importance/Uniform.h | 62 + .../metrics/BundleSpaceMetric.h | 95 ++ .../datastructures/metrics/Geodesic.h | 71 + .../pathrestriction/FindSection.h | 121 ++ .../pathrestriction/FindSectionSideStep.h | 81 + .../pathrestriction/FindSectionTypes.h | 17 + .../datastructures/pathrestriction/Head.h | 140 ++ .../pathrestriction/HeadAnalyzer.h | 111 ++ .../pathrestriction/PathRestriction.h | 182 +++ .../pathrestriction/PathSection.h | 146 ++ .../datastructures/projections/EmptySet.h | 74 + .../projections/FiberedProjection.h | 107 ++ .../datastructures/projections/Identity.h | 69 + .../datastructures/projections/None.h | 69 + .../datastructures/projections/RNSO2_RN.h | 69 + .../datastructures/projections/RN_RM.h | 69 + .../datastructures/projections/Relaxation.h | 59 + .../datastructures/projections/SE2RN_R2.h | 69 + .../datastructures/projections/SE2_R2.h | 69 + .../datastructures/projections/SE3RN_R3.h | 69 + .../datastructures/projections/SE3_R3.h | 69 + .../datastructures/projections/SO2N_SO2M.h | 69 + .../datastructures/projections/XRN_X.h | 64 + .../datastructures/projections/XRN_XRM.h | 70 + .../datastructures/projections/XRN_XRM_SE2.h | 64 + .../datastructures/projections/XRN_XRM_SE3.h | 64 + .../datastructures/projections/XRN_XRM_SO2.h | 64 + .../datastructures/projections/XRN_XRM_SO3.h | 64 + .../datastructures/projections/XRN_X_SE2.h | 64 + .../datastructures/projections/XRN_X_SE3.h | 64 + .../datastructures/projections/XRN_X_SO2.h | 64 + .../datastructures/projections/XRN_X_SO3.h | 64 + .../propagators/BundleSpacePropagator.h | 31 + .../datastructures/propagators/Geometric.h | 24 + .../ompl/multilevel/planners/qmp/QMP.h | 69 + .../ompl/multilevel/planners/qmp/QMPImpl.h | 87 ++ .../ompl/multilevel/planners/qmp/QMPStar.h | 66 + .../multilevel/planners/qmp/QMPStarImpl.h | 67 + .../ompl/multilevel/planners/qrrt/QRRT.h | 74 + .../ompl/multilevel/planners/qrrt/QRRTImpl.h | 66 + .../ompl/multilevel/planners/qrrt/QRRTStar.h | 69 + .../multilevel/planners/qrrt/QRRTStarImpl.h | 108 ++ .../include/ompl/tools/benchmark/Benchmark.h | 298 ++++ .../ompl/tools/benchmark/MachineSpecs.h | 62 + .../ompl/tools/config/MagicConstants.h | 109 ++ .../include/ompl/tools/config/SelfConfig.h | 133 ++ .../include/ompl/tools/debug/PlannerMonitor.h | 95 ++ .../include/ompl/tools/debug/Profiler.h | 451 ++++++ .../ompl/tools/experience/ExperienceSetup.h | 212 +++ .../ompl/tools/lightning/DynamicTimeWarp.h | 98 ++ .../include/ompl/tools/lightning/Lightning.h | 220 +++ .../ompl/tools/lightning/LightningDB.h | 175 +++ .../ompl/tools/multiplan/OptimizePlan.h | 94 ++ .../ompl/tools/multiplan/ParallelPlan.h | 168 +++ .../include/ompl/tools/thunder/SPARSdb.h | 788 ++++++++++ .../include/ompl/tools/thunder/Thunder.h | 205 +++ .../include/ompl/tools/thunder/ThunderDB.h | 179 +++ .../v2.0.2/include/ompl/util/ClassForward.h | 49 + .../ompl/v2.0.2/include/ompl/util/Console.h | 169 +++ .../ompl/util/DisableCompilerWarning.h | 63 + .../ompl/v2.0.2/include/ompl/util/Exception.h | 64 + .../include/ompl/util/GeometricEquations.h | 55 + .../ompl/v2.0.2/include/ompl/util/Hash.h | 86 ++ .../ompl/v2.0.2/include/ompl/util/PPM.h | 133 ++ .../include/ompl/util/ProlateHyperspheroid.h | 115 ++ .../v2.0.2/include/ompl/util/RandomNumbers.h | 199 +++ .../ompl/v2.0.2/include/ompl/util/String.h | 59 + .../ompl/v2.0.2/include/ompl/util/Time.h | 104 ++ .../ompl/v2.0.2/include/ompl/vamp/Utils.h | 43 + .../include/ompl/vamp/VampMotionValidator.h | 58 + .../v2.0.2/include/ompl/vamp/VampStateSpace.h | 52 + .../ompl/vamp/VampStateValidityChecker.h | 47 + .../third_party/ompl/v2.0.2/lib/libompl.so | 1 + .../third_party/ompl/v2.0.2/lib/libompl.so.19 | 1 + .../ompl/v2.0.2/lib/libompl.so.2.0.2 | Bin 0 -> 9748440 bytes .../ompl/v2.0.2/share/licenses/ompl/LICENSE | 32 + .../share/ompl/cmake/FindTriangle.cmake | 20 + .../v2.0.2/share/ompl/cmake/Findspot.cmake | 22 + .../share/ompl/cmake/Findyaml-cpp.cmake | 12 + .../v2.0.2/share/ompl/cmake/omplConfig.cmake | 118 ++ .../share/ompl/cmake/omplConfigVersion.cmake} | 11 +- .../share/ompl/cmake/omplExport-release.cmake | 19 + .../v2.0.2/share/ompl/cmake/omplExport.cmake | 99 ++ .../v0.6.2/include/toppra/algorithm.hpp | 168 --- .../include/toppra/algorithm/toppra.hpp | 21 - .../v0.6.2/include/toppra/constraint.hpp | 174 --- .../constraint/cartesian_velocity_norm.hpp | 94 -- .../cartesian_velocity_norm/pinocchio.hpp | 86 -- .../toppra/constraint/joint_torque.hpp | 113 -- .../constraint/joint_torque/pinocchio.hpp | 87 -- .../constraint/linear_joint_acceleration.hpp | 36 - .../constraint/linear_joint_velocity.hpp | 86 -- .../toppra/v0.6.2/include/toppra/export.hpp | 43 - .../v0.6.2/include/toppra/geometric_path.hpp | 116 -- .../geometric_path/piecewise_poly_path.hpp | 161 -- .../v0.6.2/include/toppra/parametrizer.hpp | 75 - .../toppra/parametrizer/const_accel.hpp | 52 - .../include/toppra/parametrizer/spline.hpp | 47 - .../toppra/v0.6.2/include/toppra/solver.hpp | 138 -- .../include/toppra/solver/glpk-wrapper.hpp | 54 - .../include/toppra/solver/qpOASES-wrapper.hpp | 66 - .../v0.6.2/include/toppra/solver/seidel.hpp | 43 - .../toppra/v0.6.2/include/toppra/toppra.hpp | 86 -- .../lib/cmake/toppra/toppraConfig.cmake | 13 - .../cmake/toppra/toppraConfigVersion.cmake | 65 - .../cmake/toppra/toppraTargets-noconfig.cmake | 19 - .../lib/cmake/toppra/toppraTargets.cmake | 107 -- .../toppra/v0.6.2/lib/libtoppra.so | Bin 6562216 -> 0 bytes docs/ompl_rrt_connect.md | 440 ++++++ .../cmvr/config/arm_config/arm_config.proto | 43 +- protos/cmvr/config/collision_config.proto | 40 + protos/cmvr/config/joint_motion_config.proto | 41 + .../self_collision_task_config.proto | 31 +- .../touch_screen_task_config.proto | 23 +- request.txt | 4 +- script/build_ompl.sh | 62 + script/test_speedl_reversal_mujoco.sh | 2 +- 539 files changed, 79897 insertions(+), 13423 deletions(-) rename cmvr-es/algorithms/collision_detection/{self_collision/benchmark/self_collision_benchmark.cpp => benchmark/collision_benchmark.cpp} (93%) create mode 100644 cmvr-es/algorithms/collision_detection/include/collision_checker.h rename cmvr-es/algorithms/collision_detection/{self_collision => }/include/distance_sampling_policy.h (73%) delete mode 100644 cmvr-es/algorithms/collision_detection/self_collision/include/self_collision_checker.h delete mode 100644 cmvr-es/algorithms/collision_detection/self_collision/src/self_collision_checker.cpp delete mode 100644 cmvr-es/algorithms/collision_detection/self_collision/test/self_collision_checker_test.cpp create mode 100644 cmvr-es/algorithms/collision_detection/src/collision_checker.cpp rename cmvr-es/algorithms/collision_detection/{self_collision => }/src/distance_sampling_policy.cpp (80%) create mode 100644 cmvr-es/algorithms/collision_detection/test/collision_checker_test.cpp delete mode 100644 cmvr-es/algorithms/controllers/arm_control/CMakeLists.txt delete mode 100644 cmvr-es/algorithms/controllers/arm_control/include/cartesian_velocity_controller.h delete mode 100644 cmvr-es/algorithms/controllers/arm_control/src/cartesian_velocity_controller.cpp delete mode 100644 cmvr-es/algorithms/controllers/arm_control/src/cartesian_velocity_controller_test.cpp delete mode 100644 cmvr-es/algorithms/motion_planner/CMakeLists.txt delete mode 100644 cmvr-es/algorithms/motion_planner/arm_motion/CMakeLists.txt delete mode 100644 cmvr-es/algorithms/motion_planner/arm_motion/cartesian_motion/cartesian_motion_planner.h delete mode 100644 cmvr-es/algorithms/motion_planner/arm_motion/cartesian_motion/cartesian_motion_planner_factory.h delete mode 100644 cmvr-es/algorithms/motion_planner/arm_motion/cartesian_motion/pinocchio/include/pinocchio_cartesian_motion_planner.h delete mode 100644 cmvr-es/algorithms/motion_planner/arm_motion/cartesian_motion/pinocchio/src/pinocchio_cartesian_motion_planner.cpp delete mode 100644 cmvr-es/algorithms/motion_planner/arm_motion/cartesian_motion/pinocchio/test/pinocchio_speedl_limits_test.cpp delete mode 100644 cmvr-es/algorithms/motion_planner/arm_motion/common/include/twist_limiter_config.h delete mode 100644 cmvr-es/algorithms/motion_planner/arm_motion/joint_motion/joint_motion_planner_factory.h delete mode 100644 cmvr-es/algorithms/motion_planner/arm_motion/joint_motion/toppra/include/toppra_joint_motion_planner.h delete mode 100644 cmvr-es/algorithms/motion_planner/arm_motion/joint_motion/toppra/src/toppra_joint_motion_planner.cpp delete mode 100644 cmvr-es/algorithms/motion_planner/arm_motion/joint_motion/toppra/test/toppra_joint_motion_planner_test.cpp delete mode 100644 cmvr-es/algorithms/motion_planner/base_motion/CMakeLists.txt delete mode 100644 cmvr-es/algorithms/motion_planner/base_motion/cartesian_velocity/twist_limiter/include/cartesian_twist_limiter.h delete mode 100644 cmvr-es/algorithms/motion_planner/base_motion/cartesian_velocity/twist_limiter/src/cartesian_twist_limiter.cpp delete mode 100644 cmvr-es/algorithms/motion_planner/base_motion/cartesian_velocity/twist_limiter/test/cartesian_twist_limiter_reversal_test.cpp delete mode 100644 cmvr-es/algorithms/motion_planner/base_motion/joint_trajectory/joint_trajectory_planner.h delete mode 100644 cmvr-es/algorithms/motion_planner/base_motion/joint_trajectory/toppra/include/toppra_joint_trajectory_planner.h delete mode 100644 cmvr-es/algorithms/motion_planner/base_motion/joint_trajectory/toppra/src/toppra_joint_trajectory_planner.cpp delete mode 100644 cmvr-es/algorithms/motion_planner/base_motion/joint_trajectory/toppra/test/toppra_multi_waypoint_test.cpp delete mode 100644 cmvr-es/algorithms/motion_planner/base_motion/motion_profile/s_curve/include/s_curve_position_planner.h delete mode 100644 cmvr-es/algorithms/motion_planner/base_motion/motion_profile/s_curve/include/s_curve_velocity_planner.h delete mode 100644 cmvr-es/algorithms/motion_planner/base_motion/motion_profile/s_curve/src/s_curve_position_planner.cpp delete mode 100644 cmvr-es/algorithms/motion_planner/base_motion/motion_profile/s_curve/src/s_curve_velocity_planner.cpp delete mode 100644 cmvr-es/algorithms/motion_planner/base_motion/motion_profile/s_curve/test/s_curve_velocity_planner_stop_test.cpp create mode 100644 cmvr-es/algorithms/planner/CMakeLists.txt create mode 100644 cmvr-es/algorithms/planner/cartesian/cartesian_motion_planner_factory.h create mode 100644 cmvr-es/algorithms/planner/cartesian/cartesian_trajectory_planner.h create mode 100644 cmvr-es/algorithms/planner/cartesian/cartesian_velocity_planner.h create mode 100644 cmvr-es/algorithms/planner/cartesian/pinocchio/include/pinocchio_cartesian_trajectory_planner.h create mode 100644 cmvr-es/algorithms/planner/cartesian/pinocchio/include/pinocchio_cartesian_velocity_planner.h create mode 100644 cmvr-es/algorithms/planner/cartesian/pinocchio/src/pinocchio_cartesian_trajectory_planner.cpp create mode 100644 cmvr-es/algorithms/planner/cartesian/pinocchio/src/pinocchio_cartesian_velocity_planner.cpp create mode 100644 cmvr-es/algorithms/planner/cartesian/pinocchio/test/pinocchio_speedl_limits_test.cpp create mode 100644 cmvr-es/algorithms/planner/cartesian/s_curve/include/s_curve_planner.h create mode 100644 cmvr-es/algorithms/planner/cartesian/s_curve/include/s_curve_planner_config.h create mode 100644 cmvr-es/algorithms/planner/cartesian/s_curve/src/s_curve_planner.cpp create mode 100644 cmvr-es/algorithms/planner/cartesian/s_curve/test/s_curve_planner_reversal_test.cpp create mode 100644 cmvr-es/algorithms/planner/joint/joint_path_planner.h create mode 100644 cmvr-es/algorithms/planner/joint/joint_path_planner_factory.h create mode 100644 cmvr-es/algorithms/planner/joint/ompl/include/rrt_connect.h create mode 100644 cmvr-es/algorithms/planner/joint/ompl/src/rrt_connect.cpp create mode 100644 cmvr-es/algorithms/planner/joint/ompl/test/rrt_connect_self_collision_test.cpp create mode 100644 cmvr-es/algorithms/planner/joint/ompl/test/rrt_connect_test.cpp create mode 100644 cmvr-es/algorithms/smoother/CMakeLists.txt create mode 100644 cmvr-es/algorithms/smoother/bspline/include/bspline_smoother.h create mode 100644 cmvr-es/algorithms/smoother/bspline/src/bspline_smoother.cpp create mode 100644 cmvr-es/algorithms/smoother/bspline/test/bspline_smoother_test.cpp create mode 100644 cmvr-es/algorithms/smoother/joint_trajectory_smoother.h create mode 100644 cmvr-es/algorithms/smoother/joint_trajectory_smoother_factory.h rename cmvr-es/algorithms/{motion_planner/arm_motion/joint_motion/joint_motion_planner.h => smoother/joint_trajectory_validation.h} (70%) create mode 100644 cmvr-es/curves/CMakeLists.txt create mode 100644 cmvr-es/curves/bspline/include/quintic_bspline.h create mode 100644 cmvr-es/curves/bspline/src/quintic_bspline.cpp rename cmvr-es/{algorithms/motion_planner/base_motion/motion_profile => curves}/s_curve/include/s_curve.h (59%) rename cmvr-es/{algorithms/motion_planner/base_motion/motion_profile => curves}/s_curve/src/s_curve.cpp (62%) create mode 100644 cmvr-es/devices/arm/motor_robot_arm/include/speed_l_executor.h create mode 100644 cmvr-es/devices/arm/motor_robot_arm/src/rrt_connect_mujoco_test.cpp create mode 100644 cmvr-es/devices/arm/motor_robot_arm/src/speed_l_executor.cpp create mode 100644 cmvr-es/devices/arm/motor_robot_arm/src/speed_l_executor_test.cpp create mode 100644 cmvr-es/environment/CMakeLists.txt create mode 100644 cmvr-es/environment/include/robot_model.h create mode 100644 cmvr-es/environment/src/robot_model.cpp create mode 100644 cmvr-es/safety/CMakeLists.txt create mode 100644 cmvr-es/safety/self_collision/include/self_collision_monitor.h create mode 100644 cmvr-es/safety/self_collision/src/self_collision_monitor.cpp delete mode 100644 data/ik/plot_joint_traj.py delete mode 100644 dependency/arm/third_party/toppra/v0.6.2/include/toppra/algorithm.hpp delete mode 100644 dependency/arm/third_party/toppra/v0.6.2/include/toppra/algorithm/toppra.hpp delete mode 100644 dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint.hpp delete mode 100644 dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint/cartesian_velocity_norm.hpp delete mode 100644 dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint/cartesian_velocity_norm/pinocchio.hpp delete mode 100644 dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint/joint_torque.hpp delete mode 100644 dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint/joint_torque/pinocchio.hpp delete mode 100644 dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint/linear_joint_acceleration.hpp delete mode 100644 dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint/linear_joint_velocity.hpp delete mode 100644 dependency/arm/third_party/toppra/v0.6.2/include/toppra/export.hpp delete mode 100644 dependency/arm/third_party/toppra/v0.6.2/include/toppra/geometric_path.hpp delete mode 100644 dependency/arm/third_party/toppra/v0.6.2/include/toppra/geometric_path/piecewise_poly_path.hpp delete mode 100644 dependency/arm/third_party/toppra/v0.6.2/include/toppra/parametrizer.hpp delete mode 100644 dependency/arm/third_party/toppra/v0.6.2/include/toppra/parametrizer/const_accel.hpp delete mode 100644 dependency/arm/third_party/toppra/v0.6.2/include/toppra/parametrizer/spline.hpp delete mode 100644 dependency/arm/third_party/toppra/v0.6.2/include/toppra/solver.hpp delete mode 100644 dependency/arm/third_party/toppra/v0.6.2/include/toppra/solver/glpk-wrapper.hpp delete mode 100644 dependency/arm/third_party/toppra/v0.6.2/include/toppra/solver/qpOASES-wrapper.hpp delete mode 100644 dependency/arm/third_party/toppra/v0.6.2/include/toppra/solver/seidel.hpp delete mode 100644 dependency/arm/third_party/toppra/v0.6.2/include/toppra/toppra.hpp delete mode 100644 dependency/arm/third_party/toppra/v0.6.2/lib/cmake/toppra/toppraConfig.cmake delete mode 100644 dependency/arm/third_party/toppra/v0.6.2/lib/cmake/toppra/toppraTargets-noconfig.cmake delete mode 100644 dependency/arm/third_party/toppra/v0.6.2/lib/cmake/toppra/toppraTargets.cmake delete mode 100644 dependency/arm/third_party/toppra/v0.6.2/lib/libtoppra.so create mode 100644 dependency/x86/third_party/Eigen3/v3.4.0/share/eigen3/cmake/Eigen3Config.cmake create mode 100644 dependency/x86/third_party/Eigen3/v3.4.0/share/eigen3/cmake/Eigen3ConfigVersion.cmake create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/ConstrainedSpaceInformation.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/Constraint.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/Cost.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/DiscreteMotionValidator.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/GenericParam.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/Goal.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/GoalTypes.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/MotionValidator.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/OptimizationObjective.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/Path.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/Planner.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/PlannerData.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/PlannerDataGraph.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/PlannerDataStorage.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/PlannerStatus.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/PlannerTerminationCondition.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/PrecomputedStateSampler.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/ProblemDefinition.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/ProjectionEvaluator.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/ScopedState.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/SolutionNonExistenceProof.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/SpaceInformation.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/State.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/StateSampler.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/StateSamplerArray.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/StateSpace.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/StateSpaceTypes.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/StateStorage.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/StateValidityChecker.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/TypedSpaceInformation.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/TypedStateValidityChecker.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/ValidStateSampler.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/goals/GoalLazySamples.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/goals/GoalRegion.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/goals/GoalSampleableRegion.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/goals/GoalSpace.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/goals/GoalState.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/goals/GoalStates.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/objectives/ControlDurationObjective.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/objectives/MaximizeMinClearanceObjective.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/objectives/MechanicalWorkOptimizationObjective.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/objectives/MinimaxObjective.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/objectives/MinimizeArrivalTime.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/objectives/PathLengthOptimizationObjective.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/objectives/StateCostIntegralObjective.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/objectives/VFMechanicalWorkOptimizationObjective.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/objectives/VFUpstreamCriterionOptimizationObjective.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/BridgeTestValidStateSampler.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/ConditionalStateSampler.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/DeterministicStateSampler.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/GaussianValidStateSampler.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/InformedStateSampler.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/MaximizeClearanceValidStateSampler.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/MinimumClearanceValidStateSampler.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/ObstacleBasedValidStateSampler.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/UniformValidStateSampler.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/deterministic/DeterministicSequence.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/deterministic/HaltonSequence.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/deterministic/PrecomputedSequence.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/informed/OrderedInfSampler.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/informed/PathLengthDirectInfSampler.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/samplers/informed/RejectionInfSampler.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/DiscreteStateSpace.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/Dubins3DMotionValidator.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/DubinsMotionValidator.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/DubinsStateSpace.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/EmptyStateSpace.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/HybridStateSpace.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/HybridTimeStateSpace.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/OwenStateSpace.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/RealVectorBounds.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/RealVectorStateProjections.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/RealVectorStateSpace.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/ReedsSheppStateSpace.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/SE2StateSpace.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/SE3StateSpace.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/SO2StateSpace.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/SO3StateSpace.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/SpaceTimeStateSpace.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/TimeStateSpace.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/TrochoidStateSpace.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/VanaOwenStateSpace.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/VanaStateSpace.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/WrapperStateSpace.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/constraint/AtlasChart.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/constraint/AtlasStateSpace.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/constraint/ConstrainedStateSpace.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/constraint/ProjectedStateSpace.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/constraint/TangentBundleStateSpace.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/special/KleinBottleStateSpace.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/special/MobiusStateSpace.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/special/SphereStateSpace.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/spaces/special/TorusStateSpace.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/terminationconditions/CostConvergenceTerminationCondition.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/base/terminationconditions/IterationTerminationCondition.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/config.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/Control.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/ControlSampler.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/ControlSpace.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/ControlSpaceTypes.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/DirectedControlSampler.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/ODESolver.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/PathControl.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/PlannerData.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/PlannerDataStorage.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/SimpleDirectedControlSampler.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/SimpleSetup.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/SpaceInformation.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/StatePropagator.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/SteeredControlSampler.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/PlannerIncludes.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/est/EST.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/kpiece/KPIECE1.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/ltl/Automaton.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/ltl/LTLPlanner.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/ltl/LTLProblemDefinition.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/ltl/LTLSpaceInformation.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/ltl/ProductGraph.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/ltl/PropositionalDecomposition.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/ltl/World.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/pdst/PDST.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/rrt/HyRRT.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/rrt/RRT.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/sst/HySST.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/sst/SST.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/syclop/Decomposition.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/syclop/GridDecomposition.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/syclop/Syclop.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/syclop/SyclopEST.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/planners/syclop/SyclopRRT.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/spaces/DiscreteControlSpace.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/control/spaces/RealVectorControlSpace.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/datastructures/AdjacencyList.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/datastructures/BinaryHeap.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/datastructures/DynamicSSSP.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/datastructures/GreedyKCenters.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/datastructures/Grid.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/datastructures/GridB.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/datastructures/GridN.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/datastructures/LPAstarOnGraph.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/datastructures/NearestNeighbors.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/datastructures/NearestNeighborsFLANN.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/datastructures/NearestNeighborsGNAT.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/datastructures/NearestNeighborsGNATNoThreadSafety.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/datastructures/NearestNeighborsLinear.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/datastructures/NearestNeighborsSqrtApprox.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/datastructures/PDF.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/datastructures/Permutation.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/extensions/triangle/PropositionalTriangularDecomposition.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/extensions/triangle/TriangularDecomposition.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/GeneticSearch.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/HillClimbing.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/PathGeometric.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/PathHybridization.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/PathSimplifier.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/SimpleSetup.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/AnytimePathShortening.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/PlannerIncludes.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/cforest/CForest.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/cforest/CForestStateSampler.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/cforest/CForestStateSpaceWrapper.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/est/BiEST.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/est/EST.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/est/ProjEST.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/experience/LightningRetrieveRepair.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/experience/ThunderRetrieveRepair.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/fmt/BFMT.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/fmt/FMT.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/informedtrees/ABITstar.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/informedtrees/AITstar.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/informedtrees/BITstar.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/informedtrees/EIRMstar.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/informedtrees/EITstar.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/informedtrees/aitstar/Edge.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/informedtrees/aitstar/ImplicitGraph.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/informedtrees/aitstar/Queuetypes.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/informedtrees/aitstar/Vertex.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/informedtrees/bitstar/CostHelper.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/informedtrees/bitstar/HelperFunctions.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/informedtrees/bitstar/IdGenerator.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/informedtrees/bitstar/ImplicitGraph.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/informedtrees/bitstar/SearchQueue.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/informedtrees/bitstar/Vertex.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/informedtrees/eitstar/Direction.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/informedtrees/eitstar/Edge.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/informedtrees/eitstar/ForwardQueue.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/informedtrees/eitstar/RandomGeometricGraph.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/informedtrees/eitstar/ReverseQueue.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/informedtrees/eitstar/State.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/informedtrees/eitstar/Vertex.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/kpiece/BKPIECE1.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/kpiece/Discretization.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/kpiece/KPIECE1.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/kpiece/LBKPIECE1.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/lazyinformedtrees/BLITstar.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/lazyinformedtrees/blitstar/ImplicitGraph.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/lazyinformedtrees/blitstar/Queuetypes.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/lazyinformedtrees/blitstar/Vertex.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/pdst/PDST.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/prm/ConnectionStrategy.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/prm/LazyPRM.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/prm/LazyPRMstar.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/prm/PRM.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/prm/PRMstar.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/prm/SPARS.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/prm/SPARStwo.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/rlrt/BiRLRT.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/rlrt/RLRT.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/rrt/AORRTC.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/rrt/AOXRRTConnect.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/rrt/ATRRT.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/rrt/BiTRRT.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/rrt/InformedRRTstar.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/rrt/LBTRRT.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/rrt/LazyLBTRRT.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/rrt/LazyRRT.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/rrt/RRT.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/rrt/RRTConnect.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/rrt/RRTXstatic.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/rrt/RRTsharp.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/rrt/RRTstar.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/rrt/SORRTstar.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/rrt/STRRTstar.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/rrt/TRRT.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/rrt/TRRTstar.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/rrt/TSRRT.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/rrt/VFRRT.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/rrt/pRRT.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/sbl/SBL.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/sbl/pSBL.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/sst/SST.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/stride/STRIDE.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/xxl/XXL.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/xxl/XXLDecomposition.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/xxl/XXLPlanarDecomposition.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/geometric/planners/xxl/XXLPositionDecomposition.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/BundleSpace.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/BundleSpaceGraph.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/BundleSpaceSequence.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/BundleSpaceSequenceImpl.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/Parameter.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/ParameterExponentialDecay.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/ParameterSmoothStep.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/PlannerDataVertexAnnotated.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/PlannerMultiLevel.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/Projection.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/ProjectionFactory.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/ProjectionTypes.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/graphsampler/GraphSampler.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/graphsampler/RandomDegreeVertex.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/graphsampler/RandomEdge.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/graphsampler/RandomVertex.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/importance/BundleSpaceImportance.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/importance/Exponential.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/importance/Greedy.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/importance/Uniform.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/metrics/BundleSpaceMetric.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/metrics/Geodesic.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/pathrestriction/FindSection.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/pathrestriction/FindSectionSideStep.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/pathrestriction/FindSectionTypes.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/pathrestriction/Head.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/pathrestriction/HeadAnalyzer.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/pathrestriction/PathRestriction.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/pathrestriction/PathSection.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/projections/EmptySet.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/projections/FiberedProjection.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/projections/Identity.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/projections/None.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/projections/RNSO2_RN.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/projections/RN_RM.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/projections/Relaxation.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/projections/SE2RN_R2.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/projections/SE2_R2.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/projections/SE3RN_R3.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/projections/SE3_R3.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/projections/SO2N_SO2M.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/projections/XRN_X.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/projections/XRN_XRM.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/projections/XRN_XRM_SE2.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/projections/XRN_XRM_SE3.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/projections/XRN_XRM_SO2.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/projections/XRN_XRM_SO3.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/projections/XRN_X_SE2.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/projections/XRN_X_SE3.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/projections/XRN_X_SO2.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/projections/XRN_X_SO3.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/propagators/BundleSpacePropagator.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/datastructures/propagators/Geometric.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/planners/qmp/QMP.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/planners/qmp/QMPImpl.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/planners/qmp/QMPStar.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/planners/qmp/QMPStarImpl.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/planners/qrrt/QRRT.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/planners/qrrt/QRRTImpl.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/planners/qrrt/QRRTStar.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/multilevel/planners/qrrt/QRRTStarImpl.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/tools/benchmark/Benchmark.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/tools/benchmark/MachineSpecs.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/tools/config/MagicConstants.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/tools/config/SelfConfig.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/tools/debug/PlannerMonitor.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/tools/debug/Profiler.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/tools/experience/ExperienceSetup.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/tools/lightning/DynamicTimeWarp.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/tools/lightning/Lightning.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/tools/lightning/LightningDB.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/tools/multiplan/OptimizePlan.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/tools/multiplan/ParallelPlan.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/tools/thunder/SPARSdb.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/tools/thunder/Thunder.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/tools/thunder/ThunderDB.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/util/ClassForward.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/util/Console.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/util/DisableCompilerWarning.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/util/Exception.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/util/GeometricEquations.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/util/Hash.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/util/PPM.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/util/ProlateHyperspheroid.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/util/RandomNumbers.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/util/String.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/util/Time.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/vamp/Utils.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/vamp/VampMotionValidator.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/vamp/VampStateSpace.h create mode 100644 dependency/x86/third_party/ompl/v2.0.2/include/ompl/vamp/VampStateValidityChecker.h create mode 120000 dependency/x86/third_party/ompl/v2.0.2/lib/libompl.so create mode 120000 dependency/x86/third_party/ompl/v2.0.2/lib/libompl.so.19 create mode 100644 dependency/x86/third_party/ompl/v2.0.2/lib/libompl.so.2.0.2 create mode 100644 dependency/x86/third_party/ompl/v2.0.2/share/licenses/ompl/LICENSE create mode 100644 dependency/x86/third_party/ompl/v2.0.2/share/ompl/cmake/FindTriangle.cmake create mode 100644 dependency/x86/third_party/ompl/v2.0.2/share/ompl/cmake/Findspot.cmake create mode 100644 dependency/x86/third_party/ompl/v2.0.2/share/ompl/cmake/Findyaml-cpp.cmake create mode 100644 dependency/x86/third_party/ompl/v2.0.2/share/ompl/cmake/omplConfig.cmake rename dependency/{arm/third_party/toppra/v0.6.2/lib/cmake/toppra/toppraConfigVersion.cmake => x86/third_party/ompl/v2.0.2/share/ompl/cmake/omplConfigVersion.cmake} (92%) create mode 100644 dependency/x86/third_party/ompl/v2.0.2/share/ompl/cmake/omplExport-release.cmake create mode 100644 dependency/x86/third_party/ompl/v2.0.2/share/ompl/cmake/omplExport.cmake delete mode 100644 dependency/x86/third_party/toppra/v0.6.2/include/toppra/algorithm.hpp delete mode 100644 dependency/x86/third_party/toppra/v0.6.2/include/toppra/algorithm/toppra.hpp delete mode 100644 dependency/x86/third_party/toppra/v0.6.2/include/toppra/constraint.hpp delete mode 100644 dependency/x86/third_party/toppra/v0.6.2/include/toppra/constraint/cartesian_velocity_norm.hpp delete mode 100644 dependency/x86/third_party/toppra/v0.6.2/include/toppra/constraint/cartesian_velocity_norm/pinocchio.hpp delete mode 100644 dependency/x86/third_party/toppra/v0.6.2/include/toppra/constraint/joint_torque.hpp delete mode 100644 dependency/x86/third_party/toppra/v0.6.2/include/toppra/constraint/joint_torque/pinocchio.hpp delete mode 100644 dependency/x86/third_party/toppra/v0.6.2/include/toppra/constraint/linear_joint_acceleration.hpp delete mode 100644 dependency/x86/third_party/toppra/v0.6.2/include/toppra/constraint/linear_joint_velocity.hpp delete mode 100644 dependency/x86/third_party/toppra/v0.6.2/include/toppra/export.hpp delete mode 100644 dependency/x86/third_party/toppra/v0.6.2/include/toppra/geometric_path.hpp delete mode 100644 dependency/x86/third_party/toppra/v0.6.2/include/toppra/geometric_path/piecewise_poly_path.hpp delete mode 100644 dependency/x86/third_party/toppra/v0.6.2/include/toppra/parametrizer.hpp delete mode 100644 dependency/x86/third_party/toppra/v0.6.2/include/toppra/parametrizer/const_accel.hpp delete mode 100644 dependency/x86/third_party/toppra/v0.6.2/include/toppra/parametrizer/spline.hpp delete mode 100644 dependency/x86/third_party/toppra/v0.6.2/include/toppra/solver.hpp delete mode 100644 dependency/x86/third_party/toppra/v0.6.2/include/toppra/solver/glpk-wrapper.hpp delete mode 100644 dependency/x86/third_party/toppra/v0.6.2/include/toppra/solver/qpOASES-wrapper.hpp delete mode 100644 dependency/x86/third_party/toppra/v0.6.2/include/toppra/solver/seidel.hpp delete mode 100644 dependency/x86/third_party/toppra/v0.6.2/include/toppra/toppra.hpp delete mode 100644 dependency/x86/third_party/toppra/v0.6.2/lib/cmake/toppra/toppraConfig.cmake delete mode 100644 dependency/x86/third_party/toppra/v0.6.2/lib/cmake/toppra/toppraConfigVersion.cmake delete mode 100644 dependency/x86/third_party/toppra/v0.6.2/lib/cmake/toppra/toppraTargets-noconfig.cmake delete mode 100644 dependency/x86/third_party/toppra/v0.6.2/lib/cmake/toppra/toppraTargets.cmake delete mode 100644 dependency/x86/third_party/toppra/v0.6.2/lib/libtoppra.so create mode 100644 docs/ompl_rrt_connect.md create mode 100644 protos/cmvr/config/collision_config.proto create mode 100644 protos/cmvr/config/joint_motion_config.proto create mode 100755 script/build_ompl.sh diff --git a/README.md b/README.md index 1bcb8565..3c0a1ea5 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,16 @@ CMVR-ES 工程。 +机械臂已提供独立的 OMPL RRTConnect 关节路径规划模块,构建与使用方式见 +[RRTConnect 接入说明](docs/ompl_rrt_connect.md)。`MotorRobotArm::moveP` 已接入路径规划、 +五次 B 样条平滑、运动限值校验与碰撞复检,并按控制周期下发电机指令。 + +运行时自碰撞监测位于 `cmvr-es/safety/self_collision`:`SelfCollisionMonitor` +通过 `RobotArm` 接口读取反馈、触发保护停止并协调恢复,碰撞计算仍由 +`algorithms/collision_detection` 中的 `CollisionChecker` 完成。 +`SelfCollisionTask` 仅绑定机械臂和转发周期调度;Monitor 不创建线程,恢复调用期间 +须继续周期检测。现有 `self_collision_task` 配置格式保持不变。 + ## 安装 ### 1. 拉取 Git 子模块 diff --git a/cmvr-es/CMakeLists.txt b/cmvr-es/CMakeLists.txt index 0ff7c443..a42d0c1f 100644 --- a/cmvr-es/CMakeLists.txt +++ b/cmvr-es/CMakeLists.txt @@ -1,11 +1,15 @@ +add_subdirectory(curves) + add_subdirectory(common/base/logging) link_libraries(cmvr_es::logging) +add_subdirectory(environment) add_subdirectory(common) add_subdirectory(hardware) add_subdirectory(algorithms) add_subdirectory(simulate) add_subdirectory(devices) +add_subdirectory(safety) add_subdirectory(manager/device_manager) add_subdirectory(manager/media_source_hub) add_subdirectory(service/quic_edge) diff --git a/cmvr-es/algorithms/CMakeLists.txt b/cmvr-es/algorithms/CMakeLists.txt index 471f0dfe..0654fef5 100644 --- a/cmvr-es/algorithms/CMakeLists.txt +++ b/cmvr-es/algorithms/CMakeLists.txt @@ -1,4 +1,5 @@ -add_subdirectory(motion_planner) +add_subdirectory(planner) +add_subdirectory(smoother) add_subdirectory(kinematics/ik_solver) add_subdirectory(perception) add_subdirectory(controllers) diff --git a/cmvr-es/algorithms/collision_detection/CMakeLists.txt b/cmvr-es/algorithms/collision_detection/CMakeLists.txt index f6401175..fd5a8547 100644 --- a/cmvr-es/algorithms/collision_detection/CMakeLists.txt +++ b/cmvr-es/algorithms/collision_detection/CMakeLists.txt @@ -1,48 +1,45 @@ -add_library(self_collision_checker SHARED - self_collision/src/self_collision_checker.cpp - self_collision/src/distance_sampling_policy.cpp +add_library(collision_checker SHARED + src/collision_checker.cpp + src/distance_sampling_policy.cpp ) -target_include_directories(self_collision_checker PUBLIC +target_include_directories(collision_checker PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} ) -target_compile_definitions(self_collision_checker PRIVATE - PINOCCHIO_ENABLE_TEMPLATE_INSTANTIATION - PINOCCHIO_WITH_HPP_FCL +target_compile_definitions(collision_checker PRIVATE COAL_DISABLE_HPP_FCL_WARNINGS ) -target_link_libraries(self_collision_checker PUBLIC - pinocchio_default - pinocchio_parsers - pinocchio_collision - coal +target_link_libraries(collision_checker PUBLIC + cmvr_es::environment + cmvr_es::proto ) +target_link_libraries(collision_checker PRIVATE coal) -add_library(cmvr_es::self_collision_checker ALIAS self_collision_checker) +add_library(cmvr_es::collision_checker ALIAS collision_checker) -add_executable(self_collision_checker_test - self_collision/test/self_collision_checker_test.cpp +add_executable(collision_checker_test + test/collision_checker_test.cpp ) -target_link_libraries(self_collision_checker_test PRIVATE - cmvr_es::self_collision_checker +target_link_libraries(collision_checker_test PRIVATE + cmvr_es::collision_checker gtest gtest_main pthread ) -target_compile_definitions(self_collision_checker_test PRIVATE +target_compile_definitions(collision_checker_test PRIVATE CMVR_ES_SOURCE_DIR="${PROJECT_SOURCE_DIR}" ) add_executable(self_collision_benchmark - self_collision/benchmark/self_collision_benchmark.cpp + benchmark/collision_benchmark.cpp ) target_link_libraries(self_collision_benchmark PRIVATE - cmvr_es::self_collision_checker + cmvr_es::collision_checker ) target_compile_definitions(self_collision_benchmark PRIVATE CMVR_ES_SOURCE_DIR="${PROJECT_SOURCE_DIR}" ) -install(TARGETS self_collision_checker LIBRARY DESTINATION lib) +install(TARGETS collision_checker LIBRARY DESTINATION lib) diff --git a/cmvr-es/algorithms/collision_detection/self_collision/benchmark/self_collision_benchmark.cpp b/cmvr-es/algorithms/collision_detection/benchmark/collision_benchmark.cpp similarity index 93% rename from cmvr-es/algorithms/collision_detection/self_collision/benchmark/self_collision_benchmark.cpp rename to cmvr-es/algorithms/collision_detection/benchmark/collision_benchmark.cpp index dae09d71..17c1b8e8 100644 --- a/cmvr-es/algorithms/collision_detection/self_collision/benchmark/self_collision_benchmark.cpp +++ b/cmvr-es/algorithms/collision_detection/benchmark/collision_benchmark.cpp @@ -4,7 +4,7 @@ #include #include -#include "algorithms/collision_detection/self_collision/include/self_collision_checker.h" +#include "algorithms/collision_detection/include/collision_checker.h" int main() { @@ -15,7 +15,7 @@ int main() "R_WRIST_P", "R_WRIST_Y", "R_WRIST_R", }; - cmvr::SelfCollisionChecker checker; + cmvr::CollisionChecker checker; std::string error; if (!checker.init(urdf_path, joint_names, {}, &error)) { std::cerr << "Initialization failed: " << error << '\n'; diff --git a/cmvr-es/algorithms/collision_detection/include/collision_checker.h b/cmvr-es/algorithms/collision_detection/include/collision_checker.h new file mode 100644 index 00000000..5d48e8c8 --- /dev/null +++ b/cmvr-es/algorithms/collision_detection/include/collision_checker.h @@ -0,0 +1,131 @@ +#ifndef CMVR_ES_COLLISION_CHECKER_H +#define CMVR_ES_COLLISION_CHECKER_H + +#include +#include +#include +#include +#include + +#include + +#include "common/types/arm/arm_types.h" +#include "environment/include/robot_model.h" + +namespace cmvr { + +namespace config { +class CollisionCheckerConfig; +} + +struct CollisionPair { + std::string first; + std::string second; +}; + +struct BoxObstacle { + EIGEN_MAKE_ALIGNED_OPERATOR_NEW + + std::string name; + // Existing URDF frame fixed to the model root. Pose describes the box center. + std::string frame_id; + Eigen::Vector3d size_m{Eigen::Vector3d::Zero()}; + Eigen::Vector3d position_m{Eigen::Vector3d::Zero()}; + Eigen::Quaterniond orientation{Eigen::Quaterniond::Identity()}; +}; + +struct CollisionOptions { + std::vector ignored_pairs; + // Copied at init; robot-world pairs are never excluded by ignored_pairs. + std::vector obstacles; +}; + +struct CollisionResult { + bool valid{false}; + bool in_collision{false}; + double minimum_distance_m{0.0}; + std::string first; + std::string second; + std::string error; +}; + +struct CollisionValidationOptions { + double minimum_distance_m{0.0}; + // Maximum accumulated joint-space step between discrete collision checks. + double joint_step_rad{0.02}; + std::function&)> additional_state_valid; + std::function is_cancelled; +}; + +struct CollisionTrajectoryResult { + bool valid{false}; + std::size_t validity_checks{0}; + std::string error; +}; + +// Instances own distance-query caches; not thread-safe. +class CollisionChecker { +public: + CollisionChecker(); + ~CollisionChecker(); + + CollisionChecker(CollisionChecker&&) noexcept; + CollisionChecker& operator=(CollisionChecker&&) noexcept; + + CollisionChecker(const CollisionChecker&) = delete; + CollisionChecker& operator=(const CollisionChecker&) = delete; + + // RobotModel computes body poses; this checker owns pair rules and distance + // queries. A model without collision geometry fails initialization. + bool init(const RobotModel& model, + const std::vector& active_joint_names, + const CollisionOptions& options, + std::string* error = nullptr); + + bool init(const std::string& urdf_path, + const std::vector& active_joint_names, + const CollisionOptions& options, + std::string* error = nullptr); + + // Resolves the configured URDF and self-collision pair rules. + // A failed init clears the previous checker state. + bool init(const config::CollisionCheckerConfig& config, + const std::vector& active_joint_names, + std::string* error = nullptr); + + // Reuses matching model geometry, or loads the configured collision URDF + // into a local model copy. The caller's model is never modified. + bool init(const config::CollisionCheckerConfig& config, + const RobotModel& model, + std::string* error = nullptr); + + // Returns the selected robot bodies at these joint positions; invalid input throws. + std::vector collisionBodies(const std::vector& joint_positions) const; + + CollisionResult check(const std::vector& bodies); + CollisionResult check(const std::vector& joint_positions); + + // Invalid queries throw; collisions and additional constraint failures + // return false. Additional constraints cannot bypass geometry checks. + bool isStateValid(const std::vector& joint_positions, + const CollisionValidationOptions& options = {}); + + // Checks the position polyline, including both endpoints. This is discrete + // checking; joint limits and motion derivative limits belong to the caller. + CollisionTrajectoryResult checkTrajectory( + const device::JointTrajectory& trajectory, + const CollisionValidationOptions& options = {}); + + bool initialized() const; + std::size_t dof() const; + std::size_t activePairCount() const; + const std::vector& jointNames() const; + +private: + class Impl; + std::unique_ptr impl_; +}; + +} // namespace cmvr + +#endif // CMVR_ES_COLLISION_CHECKER_H diff --git a/cmvr-es/algorithms/collision_detection/self_collision/include/distance_sampling_policy.h b/cmvr-es/algorithms/collision_detection/include/distance_sampling_policy.h similarity index 73% rename from cmvr-es/algorithms/collision_detection/self_collision/include/distance_sampling_policy.h rename to cmvr-es/algorithms/collision_detection/include/distance_sampling_policy.h index f2b022af..dbbbcd48 100644 --- a/cmvr-es/algorithms/collision_detection/self_collision/include/distance_sampling_policy.h +++ b/cmvr-es/algorithms/collision_detection/include/distance_sampling_policy.h @@ -3,8 +3,9 @@ #include #include +#include -#include "algorithms/collision_detection/self_collision/include/self_collision_checker.h" +#include "environment/include/robot_model.h" namespace cmvr { @@ -20,22 +21,22 @@ public: bool configure(const DistanceSamplingOptions& options, std::string* error = nullptr); - bool shouldCheck(const CollisionGeometrySnapshot& current, + bool shouldCheck(const std::vector& current, Clock::time_point now) const; - void markChecked(const CollisionGeometrySnapshot& current, + void markChecked(const std::vector& current, Clock::time_point now); void reset(); double displacementSinceLastCheck( - const CollisionGeometrySnapshot& current) const; + const std::vector& current) const; bool hasBaseline() const { return has_baseline_; } private: DistanceSamplingOptions options_{}; - CollisionGeometrySnapshot last_checked_{}; + std::vector last_checked_{}; Clock::time_point last_check_time_{}; bool configured_{false}; bool has_baseline_{false}; diff --git a/cmvr-es/algorithms/collision_detection/self_collision/include/self_collision_checker.h b/cmvr-es/algorithms/collision_detection/self_collision/include/self_collision_checker.h deleted file mode 100644 index 60fae78b..00000000 --- a/cmvr-es/algorithms/collision_detection/self_collision/include/self_collision_checker.h +++ /dev/null @@ -1,82 +0,0 @@ -#ifndef CMVR_ES_SELF_COLLISION_CHECKER_H -#define CMVR_ES_SELF_COLLISION_CHECKER_H - -#include -#include -#include -#include - -#include - -namespace cmvr { - -struct CollisionPair { - std::string first; - std::string second; -}; - -struct SelfCollisionOptions { - std::vector ignored_pairs; -}; - -struct CollisionObjectPose { - EIGEN_MAKE_ALIGNED_OPERATOR_NEW - - std::size_t geometry_index{0}; - Eigen::Vector3d position{Eigen::Vector3d::Zero()}; - Eigen::Quaterniond orientation{Eigen::Quaterniond::Identity()}; - double bounding_radius_m{0.0}; -}; - -struct CollisionGeometrySnapshot { - EIGEN_MAKE_ALIGNED_OPERATOR_NEW - - std::vector> objects; -}; - -struct SelfCollisionResult { - bool valid{false}; - bool in_collision{false}; - double minimum_distance_m{0.0}; - std::string first; - std::string second; - std::string error; -}; - -// Instances cache Pinocchio work data and are not thread-safe. -class SelfCollisionChecker { -public: - SelfCollisionChecker(); - ~SelfCollisionChecker(); - - SelfCollisionChecker(SelfCollisionChecker&&) noexcept; - SelfCollisionChecker& operator=(SelfCollisionChecker&&) noexcept; - - SelfCollisionChecker(const SelfCollisionChecker&) = delete; - SelfCollisionChecker& operator=(const SelfCollisionChecker&) = delete; - - bool init(const std::string& urdf_path, - const std::vector& active_joint_names, - const SelfCollisionOptions& options, - std::string* error = nullptr); - - bool makeSnapshot(const std::vector& joint_positions, - CollisionGeometrySnapshot* snapshot, - std::string* error = nullptr); - - SelfCollisionResult check(const CollisionGeometrySnapshot& snapshot); - SelfCollisionResult check(const std::vector& joint_positions); - - bool initialized() const; - std::size_t dof() const; - std::size_t activePairCount() const; - const std::vector& jointNames() const; - -private: - class Impl; - std::unique_ptr impl_; -}; - -} // namespace cmvr - -#endif // CMVR_ES_SELF_COLLISION_CHECKER_H diff --git a/cmvr-es/algorithms/collision_detection/self_collision/src/self_collision_checker.cpp b/cmvr-es/algorithms/collision_detection/self_collision/src/self_collision_checker.cpp deleted file mode 100644 index 8606bd22..00000000 --- a/cmvr-es/algorithms/collision_detection/self_collision/src/self_collision_checker.cpp +++ /dev/null @@ -1,403 +0,0 @@ -#include "algorithms/collision_detection/self_collision/include/self_collision_checker.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -namespace cmvr { -namespace { - -using LinkPairKey = std::pair; - -LinkPairKey canonicalPair(std::string first, std::string second) -{ - if (second < first) { - std::swap(first, second); - } - return {std::move(first), std::move(second)}; -} - -void setError(std::string* error, const std::string& message) -{ - if (error) { - *error = message; - } -} - -} // namespace - -class SelfCollisionChecker::Impl { -public: - bool init(const std::string& urdf_path, - const std::vector& active_joint_names, - const SelfCollisionOptions& options, - std::string* error) - { - reset(); - if (urdf_path.empty()) { - setError(error, "URDF path is empty"); - return false; - } - if (!std::filesystem::is_regular_file(urdf_path)) { - setError(error, "URDF file does not exist: " + urdf_path); - return false; - } - if (active_joint_names.empty()) { - setError(error, "Active joint list is empty"); - return false; - } - - try { - pinocchio::urdf::buildModel(urdf_path, model_); - pinocchio::urdf::buildGeom( - model_, urdf_path, pinocchio::COLLISION, geometry_model_); - } catch (const std::exception& exception) { - setError(error, "Failed to load collision URDF: " + std::string(exception.what())); - reset(); - return false; - } - - if (geometry_model_.ngeoms == 0) { - setError(error, "URDF contains no collision geometry: " + urdf_path); - reset(); - return false; - } - - std::unordered_set active_joint_ids; - std::unordered_set unique_joint_names; - joint_names_.reserve(active_joint_names.size()); - joint_q_indices_.reserve(active_joint_names.size()); - for (const auto& joint_name : active_joint_names) { - if (joint_name.empty() || !unique_joint_names.insert(joint_name).second) { - setError(error, "Active joint names must be non-empty and unique"); - reset(); - return false; - } - if (!model_.existJointName(joint_name)) { - setError(error, "Joint not found in URDF: " + joint_name); - reset(); - return false; - } - const pinocchio::JointIndex joint_id = model_.getJointId(joint_name); - const auto& joint = model_.joints[joint_id]; - if (joint.nq() != 1) { - setError(error, "Only one-DoF active joints are supported: " + joint_name); - reset(); - return false; - } - active_joint_ids.insert(joint_id); - joint_names_.push_back(joint_name); - joint_q_indices_.push_back(joint.idx_q()); - } - - geometry_link_names_.resize(geometry_model_.ngeoms); - std::unordered_set selected_link_names; - for (pinocchio::GeomIndex geometry_id = 0; - geometry_id < geometry_model_.ngeoms; - ++geometry_id) { - auto& geometry = geometry_model_.geometryObjects[geometry_id]; - const std::string link_name = geometry.parentFrame < model_.frames.size() - ? model_.frames[geometry.parentFrame].name - : geometry.name; - geometry_link_names_[geometry_id] = link_name; - - const bool is_static = geometry.parentJoint == 0; - const bool belongs_to_active_arm = active_joint_ids.count(geometry.parentJoint) != 0; - if (!is_static && !belongs_to_active_arm) { - continue; - } - - if (!geometry.geometry) { - setError(error, "Collision geometry is null for link: " + link_name); - reset(); - return false; - } - geometry.geometry->computeLocalAABB(); - selected_geometry_indices_.push_back(geometry_id); - selected_link_names.insert(link_name); - } - - if (selected_geometry_indices_.size() < 2) { - setError(error, "Fewer than two collision geometries remain after arm filtering"); - reset(); - return false; - } - - std::set ignored_pairs; - for (const auto& pair : options.ignored_pairs) { - if (pair.first.empty() || pair.second.empty() || pair.first == pair.second) { - setError(error, "Ignored collision pairs require two different non-empty links"); - reset(); - return false; - } - if (!selected_link_names.count(pair.first) || !selected_link_names.count(pair.second)) { - setError(error, - "Ignored collision pair references an inactive or unknown link: " + - pair.first + ", " + pair.second); - reset(); - return false; - } - ignored_pairs.insert(canonicalPair(pair.first, pair.second)); - } - - geometry_model_.removeAllCollisionPairs(); - for (std::size_t first_index = 0; - first_index < selected_geometry_indices_.size(); - ++first_index) { - const auto first_geometry_id = selected_geometry_indices_[first_index]; - const auto& first_geometry = geometry_model_.geometryObjects[first_geometry_id]; - for (std::size_t second_index = first_index + 1; - second_index < selected_geometry_indices_.size(); - ++second_index) { - const auto second_geometry_id = selected_geometry_indices_[second_index]; - const auto& second_geometry = geometry_model_.geometryObjects[second_geometry_id]; - - if (first_geometry.parentJoint == second_geometry.parentJoint) { - continue; - } - if (model_.parents[first_geometry.parentJoint] == second_geometry.parentJoint || - model_.parents[second_geometry.parentJoint] == first_geometry.parentJoint) { - continue; - } - - const auto link_pair = canonicalPair( - geometry_link_names_[first_geometry_id], - geometry_link_names_[second_geometry_id]); - if (ignored_pairs.count(link_pair)) { - continue; - } - geometry_model_.addCollisionPair( - pinocchio::CollisionPair(first_geometry_id, second_geometry_id)); - } - } - - if (geometry_model_.collisionPairs.empty()) { - setError(error, "No active collision pairs remain after filtering"); - reset(); - return false; - } - - data_ = std::make_unique(model_); - geometry_data_ = std::make_unique(geometry_model_); - for (auto& request : geometry_data_->distanceRequests) { - request.enable_signed_distance = true; - } - neutral_q_ = pinocchio::neutral(model_); - initialized_ = true; - if (error) { - error->clear(); - } - return true; - } - - bool makeSnapshot(const std::vector& joint_positions, - CollisionGeometrySnapshot* snapshot, - std::string* error) - { - if (!initialized_) { - setError(error, "SelfCollisionChecker is not initialized"); - return false; - } - if (!snapshot) { - setError(error, "Collision snapshot output is null"); - return false; - } - if (joint_positions.size() != joint_names_.size()) { - std::ostringstream stream; - stream << "Joint position size mismatch: expected " << joint_names_.size() - << ", got " << joint_positions.size(); - setError(error, stream.str()); - return false; - } - - Eigen::VectorXd q = neutral_q_; - for (std::size_t index = 0; index < joint_positions.size(); ++index) { - if (!std::isfinite(joint_positions[index])) { - setError(error, "Joint position contains a non-finite value: " + joint_names_[index]); - return false; - } - q[joint_q_indices_[index]] = joint_positions[index]; - } - - try { - pinocchio::updateGeometryPlacements( - model_, *data_, geometry_model_, *geometry_data_, q); - } catch (const std::exception& exception) { - setError(error, "Failed to update collision geometry: " + std::string(exception.what())); - return false; - } - - snapshot->objects.clear(); - snapshot->objects.reserve(selected_geometry_indices_.size()); - for (const auto geometry_id : selected_geometry_indices_) { - const auto& placement = geometry_data_->oMg[geometry_id]; - const auto& geometry = geometry_model_.geometryObjects[geometry_id]; - CollisionObjectPose pose; - pose.geometry_index = geometry_id; - pose.position = placement.translation(); - pose.orientation = Eigen::Quaterniond(placement.rotation()).normalized(); - pose.bounding_radius_m = std::max(0.0, geometry.geometry->aabb_radius); - snapshot->objects.push_back(std::move(pose)); - } - if (error) { - error->clear(); - } - return true; - } - - SelfCollisionResult check(const CollisionGeometrySnapshot& snapshot) - { - SelfCollisionResult result; - if (!initialized_) { - result.error = "SelfCollisionChecker is not initialized"; - return result; - } - if (snapshot.objects.size() != selected_geometry_indices_.size()) { - result.error = "Collision snapshot size does not match initialized geometry"; - return result; - } - - for (std::size_t index = 0; index < snapshot.objects.size(); ++index) { - const auto& pose = snapshot.objects[index]; - if (pose.geometry_index != selected_geometry_indices_[index] || - pose.geometry_index >= geometry_data_->oMg.size()) { - result.error = "Collision snapshot geometry order is invalid"; - return result; - } - if (!pose.position.allFinite() || !pose.orientation.coeffs().allFinite() || - pose.orientation.norm() <= std::numeric_limits::epsilon()) { - result.error = "Collision snapshot contains an invalid pose"; - return result; - } - geometry_data_->oMg[pose.geometry_index] = pinocchio::SE3( - pose.orientation.normalized().toRotationMatrix(), pose.position); - } - - try { - const std::size_t pair_index = - pinocchio::computeDistances(geometry_model_, *geometry_data_); - if (pair_index >= geometry_model_.collisionPairs.size()) { - result.error = "Collision distance computation returned no active pair"; - return result; - } - const auto& pair = geometry_model_.collisionPairs[pair_index]; - result.minimum_distance_m = geometry_data_->distanceResults[pair_index].min_distance; - result.first = geometry_link_names_[pair.first]; - result.second = geometry_link_names_[pair.second]; - result.in_collision = result.minimum_distance_m <= 0.0; - result.valid = std::isfinite(result.minimum_distance_m); - if (!result.valid) { - result.error = "Collision distance is not finite"; - } - } catch (const std::exception& exception) { - result.error = "Collision distance computation failed: " + std::string(exception.what()); - } - return result; - } - - SelfCollisionResult check(const std::vector& joint_positions) - { - CollisionGeometrySnapshot snapshot; - std::string error; - if (!makeSnapshot(joint_positions, &snapshot, &error)) { - SelfCollisionResult result; - result.error = std::move(error); - return result; - } - return check(snapshot); - } - - void reset() - { - initialized_ = false; - joint_names_.clear(); - joint_q_indices_.clear(); - selected_geometry_indices_.clear(); - geometry_link_names_.clear(); - geometry_data_.reset(); - data_.reset(); - model_ = pinocchio::Model{}; - geometry_model_ = pinocchio::GeometryModel{}; - neutral_q_.resize(0); - } - - bool initialized_{false}; - std::vector joint_names_; - std::vector joint_q_indices_; - std::vector selected_geometry_indices_; - std::vector geometry_link_names_; - pinocchio::Model model_; - pinocchio::GeometryModel geometry_model_; - std::unique_ptr data_; - std::unique_ptr geometry_data_; - Eigen::VectorXd neutral_q_; -}; - -SelfCollisionChecker::SelfCollisionChecker() - : impl_(std::make_unique()) -{ -} - -SelfCollisionChecker::~SelfCollisionChecker() = default; -SelfCollisionChecker::SelfCollisionChecker(SelfCollisionChecker&&) noexcept = default; -SelfCollisionChecker& SelfCollisionChecker::operator=(SelfCollisionChecker&&) noexcept = default; - -bool SelfCollisionChecker::init(const std::string& urdf_path, - const std::vector& active_joint_names, - const SelfCollisionOptions& options, - std::string* error) -{ - return impl_->init(urdf_path, active_joint_names, options, error); -} - -bool SelfCollisionChecker::makeSnapshot(const std::vector& joint_positions, - CollisionGeometrySnapshot* snapshot, - std::string* error) -{ - return impl_->makeSnapshot(joint_positions, snapshot, error); -} - -SelfCollisionResult SelfCollisionChecker::check(const CollisionGeometrySnapshot& snapshot) -{ - return impl_->check(snapshot); -} - -SelfCollisionResult SelfCollisionChecker::check(const std::vector& joint_positions) -{ - return impl_->check(joint_positions); -} - -bool SelfCollisionChecker::initialized() const -{ - return impl_->initialized_; -} - -std::size_t SelfCollisionChecker::dof() const -{ - return impl_->joint_names_.size(); -} - -std::size_t SelfCollisionChecker::activePairCount() const -{ - return impl_->geometry_model_.collisionPairs.size(); -} - -const std::vector& SelfCollisionChecker::jointNames() const -{ - return impl_->joint_names_; -} - -} // namespace cmvr diff --git a/cmvr-es/algorithms/collision_detection/self_collision/test/self_collision_checker_test.cpp b/cmvr-es/algorithms/collision_detection/self_collision/test/self_collision_checker_test.cpp deleted file mode 100644 index 5c5d75b4..00000000 --- a/cmvr-es/algorithms/collision_detection/self_collision/test/self_collision_checker_test.cpp +++ /dev/null @@ -1,236 +0,0 @@ -#include -#include -#include - -#include - -#include "algorithms/collision_detection/self_collision/include/distance_sampling_policy.h" -#include "algorithms/collision_detection/self_collision/include/self_collision_checker.h" - -namespace cmvr { -namespace { - -const std::vector kRightArmJoints{ - "R_SHOULDER_P", - "R_SHOULDER_R", - "R_SHOULDER_Y", - "R_ELBOW_R", - "R_WRIST_P", - "R_WRIST_Y", - "R_WRIST_R", -}; - -const std::vector kGen2RightArmJoints{ - "right_arm_J1", - "right_arm_J2", - "right_arm_J3", - "right_arm_J4", - "right_arm_J5", - "right_arm_J6", - "right_arm_J7", -}; - -const std::vector kGen2SetupPose{ - 0.0, -0.50, 1.5708, 1.5708, -0.041, 0.0, 0.0, -}; - -const std::vector kGen2WarningPose{ - 2.45028525340088, - 0.413065394330014, - -1.78610031118294, - 2.3232081721811, - -2.96828882895788, - -1.59350098130002, - 0.582912411114367, -}; - -const std::vector kGen2StopPose{ - 2.13758633436379, - 1.61835160165575, - -2.3836142221041, - 0.964538527544213, - -0.00382525077004825, - 1.74586899135531, - -0.336868659266887, -}; - -const std::vector kGen2CollisionPose{ - -0.42656969579233, - 1.41426471041774, - -2.67949400419915, - 2.45814854129954, - -2.35907388079205, - 1.14125209449898, - 1.53232912981414, -}; - -const std::vector kGen2TorsoCollisionPose{ - 1.57607137794121, - 2.06613762981425, - -1.76915077905899, - 0.959251437141443, - -0.725973209527894, - 1.79390262120717, - 0.2223354372144, -}; - -std::string collisionUrdfPath() -{ - return std::string(CMVR_ES_SOURCE_DIR) + - "/model/xiaoyan_description/dual_arm_collision.urdf"; -} - -std::string gen2CollisionUrdfPath() -{ - return std::string(CMVR_ES_SOURCE_DIR) + - "/model/gen2/collision/robot_collision.urdf"; -} - -SelfCollisionOptions gen2CollisionOptions() -{ - SelfCollisionOptions options; - options.ignored_pairs.push_back({"arm_link_5_2", "arm_link_7_2"}); - options.ignored_pairs.push_back({"body_link", "arm_link_2_2"}); - return options; -} - -CollisionGeometrySnapshot singleObjectSnapshot(double x, - double angle, - double radius) -{ - CollisionGeometrySnapshot snapshot; - CollisionObjectPose pose; - pose.geometry_index = 1; - pose.position = Eigen::Vector3d(x, 0.0, 0.0); - pose.orientation = Eigen::AngleAxisd(angle, Eigen::Vector3d::UnitZ()); - pose.bounding_radius_m = radius; - snapshot.objects.push_back(pose); - return snapshot; -} - -TEST(SelfCollisionCheckerTest, LoadsRightArmFromDualArmUrdf) -{ - SelfCollisionChecker checker; - std::string error; - ASSERT_TRUE(checker.init(collisionUrdfPath(), kRightArmJoints, {}, &error)) << error; - EXPECT_EQ(checker.dof(), 7U); - EXPECT_GT(checker.activePairCount(), 0U); - - CollisionGeometrySnapshot snapshot; - ASSERT_TRUE(checker.makeSnapshot(std::vector(7, 0.0), &snapshot, &error)) << error; - EXPECT_EQ(snapshot.objects.size(), 11U); - - const SelfCollisionResult result = checker.check(snapshot); - ASSERT_TRUE(result.valid) << result.error; - EXPECT_TRUE(result.first.rfind("L_", 0) != 0); - EXPECT_TRUE(result.second.rfind("L_", 0) != 0); -} - -TEST(SelfCollisionCheckerTest, RejectsWrongJointVectorSize) -{ - SelfCollisionChecker checker; - std::string error; - ASSERT_TRUE(checker.init(collisionUrdfPath(), kRightArmJoints, {}, &error)) << error; - - CollisionGeometrySnapshot snapshot; - EXPECT_FALSE(checker.makeSnapshot(std::vector(6, 0.0), &snapshot, &error)); - EXPECT_NE(error.find("size mismatch"), std::string::npos); -} - -TEST(SelfCollisionCheckerTest, RemovesConfiguredIgnoredPair) -{ - SelfCollisionChecker baseline; - SelfCollisionChecker filtered; - std::string error; - ASSERT_TRUE(baseline.init(collisionUrdfPath(), kRightArmJoints, {}, &error)) << error; - - SelfCollisionOptions options; - options.ignored_pairs.push_back({"base_link", "R_ELBOW_R_S"}); - ASSERT_TRUE(filtered.init(collisionUrdfPath(), kRightArmJoints, options, &error)) << error; - EXPECT_EQ(filtered.activePairCount() + 1, baseline.activePairCount()); -} - -TEST(SelfCollisionCheckerTest, LoadsGen2RightArmCollisionModel) -{ - SelfCollisionChecker checker; - std::string error; - ASSERT_TRUE(checker.init( - gen2CollisionUrdfPath(), - kGen2RightArmJoints, - gen2CollisionOptions(), - &error)) << error; - EXPECT_EQ(checker.dof(), 7U); - EXPECT_EQ(checker.activePairCount(), 19U); - - CollisionGeometrySnapshot snapshot; - ASSERT_TRUE(checker.makeSnapshot(kGen2SetupPose, &snapshot, &error)) << error; - EXPECT_EQ(snapshot.objects.size(), 8U); - - const SelfCollisionResult setup_result = checker.check(snapshot); - ASSERT_TRUE(setup_result.valid) << setup_result.error; - EXPECT_FALSE(setup_result.in_collision); - EXPECT_GT(setup_result.minimum_distance_m, 0.02); -} - -TEST(SelfCollisionCheckerTest, ClassifiesGen2SafetyDistances) -{ - SelfCollisionChecker checker; - std::string error; - ASSERT_TRUE(checker.init( - gen2CollisionUrdfPath(), - kGen2RightArmJoints, - gen2CollisionOptions(), - &error)) << error; - - const SelfCollisionResult warning_result = checker.check(kGen2WarningPose); - ASSERT_TRUE(warning_result.valid) << warning_result.error; - EXPECT_FALSE(warning_result.in_collision); - EXPECT_GT(warning_result.minimum_distance_m, 0.005); - EXPECT_LE(warning_result.minimum_distance_m, 0.02); - - const SelfCollisionResult stop_result = checker.check(kGen2StopPose); - ASSERT_TRUE(stop_result.valid) << stop_result.error; - EXPECT_FALSE(stop_result.in_collision); - EXPECT_GT(stop_result.minimum_distance_m, 0.0); - EXPECT_LE(stop_result.minimum_distance_m, 0.005); - - const SelfCollisionResult collision_result = checker.check(kGen2CollisionPose); - ASSERT_TRUE(collision_result.valid) << collision_result.error; - EXPECT_TRUE(collision_result.in_collision); - EXPECT_LE(collision_result.minimum_distance_m, 0.0); - - const SelfCollisionResult torso_result = - checker.check(kGen2TorsoCollisionPose); - ASSERT_TRUE(torso_result.valid) << torso_result.error; - EXPECT_TRUE(torso_result.in_collision); - EXPECT_LE(torso_result.minimum_distance_m, 0.0); - EXPECT_TRUE(torso_result.first == "body_link" || - torso_result.second == "body_link"); -} - -TEST(DistanceSamplingPolicyTest, SamplesByAccumulatedGeometryDisplacement) -{ - DistanceSamplingPolicy policy; - DistanceSamplingOptions options; - options.max_geometry_displacement_m = 0.002; - options.max_check_period_s = 0.01; - std::string error; - ASSERT_TRUE(policy.configure(options, &error)) << error; - - const auto start = DistanceSamplingPolicy::Clock::now(); - const auto initial = singleObjectSnapshot(0.0, 0.0, 0.2); - EXPECT_TRUE(policy.shouldCheck(initial, start)); - policy.markChecked(initial, start); - - EXPECT_FALSE(policy.shouldCheck( - singleObjectSnapshot(0.001, 0.0, 0.2), start + std::chrono::milliseconds(1))); - EXPECT_TRUE(policy.shouldCheck( - singleObjectSnapshot(0.0021, 0.0, 0.2), start + std::chrono::milliseconds(2))); - EXPECT_TRUE(policy.shouldCheck( - singleObjectSnapshot(0.0, 0.011, 0.2), start + std::chrono::milliseconds(2))); - EXPECT_TRUE(policy.shouldCheck( - initial, start + std::chrono::milliseconds(10))); -} - -} // namespace -} // namespace cmvr diff --git a/cmvr-es/algorithms/collision_detection/src/collision_checker.cpp b/cmvr-es/algorithms/collision_detection/src/collision_checker.cpp new file mode 100644 index 00000000..973b910a --- /dev/null +++ b/cmvr-es/algorithms/collision_detection/src/collision_checker.cpp @@ -0,0 +1,468 @@ +#include "algorithms/collision_detection/include/collision_checker.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "cmvr/config/collision_config.pb.h" +#include "common/config/config_files.h" + +namespace cmvr { +namespace { + +using LinkPairKey = std::pair; + +LinkPairKey canonicalPair(std::string first, std::string second) +{ + if (second < first) { + std::swap(first, second); + } + return {std::move(first), std::move(second)}; +} + +void setError(std::string* error, const std::string& message) +{ + if (error) { + *error = message; + } +} + +} // namespace + +class CollisionChecker::Impl { +public: + bool init(const RobotModel& robot_model, + const std::vector& active_joint_names, + const CollisionOptions& options, + std::string* error) + { + reset(); + const auto reject = [&](const std::string& message) { + reset(); + setError(error, message); + return false; + }; + if (!robot_model.hasCollisionGeometry()) { + return reject("RobotModel contains no collision geometry"); + } + if (active_joint_names.empty()) { + return reject("Active joint list is empty"); + } + robot_model_ = robot_model; + joint_names_ = active_joint_names; + const auto bodies = robot_model_.collisionBodies( + std::vector(joint_names_.size(), 0.0), joint_names_); + if (bodies.empty()) { + return reject("No collision geometry remains after arm filtering"); + } + + std::unordered_set selected_link_names; + for (const auto& body : bodies) { + if (!body.geometry) { + return reject("Collision geometry is null for link: " + body.link_name); + } + geometry_indices_.push_back(body.geometry_index); + objects_.push_back({body.link_name, body.geometry, coal::Transform3s::Identity()}); + selected_link_names.insert(body.link_name); + } + std::set ignored_pairs; + for (const auto& pair : options.ignored_pairs) { + if (pair.first.empty() || pair.second.empty() || pair.first == pair.second) { + return reject("Ignored collision pairs require two different non-empty links"); + } + if (!selected_link_names.count(pair.first) || !selected_link_names.count(pair.second)) { + return reject("Ignored collision pair references an inactive or unknown link: " + + pair.first + ", " + pair.second); + } + ignored_pairs.insert(canonicalPair(pair.first, pair.second)); + } + for (std::size_t first = 0; first < bodies.size(); ++first) { + for (std::size_t second = first + 1; second < bodies.size(); ++second) { + const auto& a = bodies[first]; + const auto& b = bodies[second]; + if (a.joint_name == b.joint_name || a.parent_joint_name == b.joint_name || + b.parent_joint_name == a.joint_name || + ignored_pairs.count(canonicalPair(a.link_name, b.link_name))) { + continue; + } + pairs_.emplace_back(first, second, objects_); + } + } + + std::unordered_set obstacle_names; + for (const auto& obstacle : options.obstacles) { + if (obstacle.name.empty() || !obstacle_names.insert(obstacle.name).second || + robot_model_.containsName(obstacle.name)) { + return reject("Obstacle name must be unique and distinct from robot names: " + + obstacle.name); + } + Eigen::Isometry3d frame_pose; + if (!robot_model_.fixedFramePose(obstacle.frame_id, frame_pose)) { + return reject("Cannot resolve fixed obstacle frame: " + obstacle.frame_id); + } + const double orientation_norm = obstacle.orientation.norm(); + if (!obstacle.size_m.allFinite() || (obstacle.size_m.array() <= 0.0).any() || + !obstacle.position_m.allFinite() || !obstacle.orientation.coeffs().allFinite() || + !std::isfinite(orientation_norm) || + orientation_norm <= std::numeric_limits::epsilon()) { + return reject("Obstacle requires positive finite sizes and a valid pose: " + + obstacle.name); + } + Eigen::Isometry3d box_pose = Eigen::Isometry3d::Identity(); + box_pose.linear() = obstacle.orientation.normalized().toRotationMatrix(); + box_pose.translation() = obstacle.position_m; + const Eigen::Isometry3d placement = frame_pose * box_pose; + if (!placement.matrix().allFinite()) { + return reject("Obstacle transform is not finite: " + obstacle.name); + } + auto box = std::make_shared( + obstacle.size_m.x(), obstacle.size_m.y(), obstacle.size_m.z()); + box->computeLocalAABB(); + const auto obstacle_index = objects_.size(); + objects_.push_back({obstacle.name, std::move(box), + coal::Transform3s(placement.linear(), placement.translation())}); + // World pairs include every selected robot body, including the base. + for (std::size_t robot_index = 0; robot_index < bodies.size(); ++robot_index) { + pairs_.emplace_back(robot_index, obstacle_index, objects_); + } + } + if (pairs_.empty()) { + return reject("No active collision pairs remain after filtering"); + } + initialized_ = true; + setError(error, ""); + return true; + } + + std::vector collisionBodies(const std::vector& joint_positions) const + { + if (!initialized_) { + throw std::logic_error("CollisionChecker is not initialized"); + } + return robot_model_.collisionBodies(joint_positions, joint_names_); + } + + CollisionResult check(const std::vector& bodies) + { + CollisionResult result; + if (!initialized_) { + result.error = "CollisionChecker is not initialized"; + return result; + } + if (bodies.size() != geometry_indices_.size()) { + result.error = "Collision body count does not match initialized geometry"; + return result; + } + for (std::size_t index = 0; index < bodies.size(); ++index) { + const auto& pose = bodies[index]; + if (pose.geometry_index != geometry_indices_[index]) { + result.error = "Collision body geometry order is invalid"; + return result; + } + const double norm = pose.orientation.norm(); + if (!pose.position.allFinite() || !pose.orientation.coeffs().allFinite() || + !std::isfinite(norm) || norm <= std::numeric_limits::epsilon()) { + result.error = "Collision body contains an invalid pose"; + return result; + } + objects_[index].placement = coal::Transform3s( + pose.orientation.normalized().toRotationMatrix(), pose.position); + } + // World placements are fixed and independent of the supplied robot body poses. + try { + result.minimum_distance_m = std::numeric_limits::infinity(); + for (auto& pair : pairs_) { + pair.result.clear(); + pair.compute(objects_[pair.first].placement, objects_[pair.second].placement, + pair.request, pair.result); + const double distance = pair.result.min_distance; + if (!std::isfinite(distance)) { + result.error = "Collision distance is not finite"; + return result; + } + if (distance < result.minimum_distance_m) { + result.minimum_distance_m = distance; + result.first = objects_[pair.first].name; + result.second = objects_[pair.second].name; + } + } + result.in_collision = result.minimum_distance_m <= 0.0; + result.valid = true; + } catch (const std::exception& exception) { + result.error = "Collision distance computation failed: " + std::string(exception.what()); + } + return result; + } + + CollisionResult check(const std::vector& joint_positions) + { + try { + return check(collisionBodies(joint_positions)); + } catch (const std::exception& exception) { + CollisionResult result; + result.error = exception.what(); + return result; + } + } + + void reset() + { + initialized_ = false; + joint_names_.clear(); + pairs_.clear(); + objects_.clear(); + geometry_indices_.clear(); + robot_model_ = RobotModel{}; + } + + struct QueryObject { + std::string name; + std::shared_ptr geometry; + coal::Transform3s placement; + }; + + struct DistancePair { + std::size_t first; + std::size_t second; + coal::ComputeDistance compute; + coal::DistanceRequest request{true}; + coal::DistanceResult result; + + DistancePair(std::size_t a, std::size_t b, const std::vector& objects) + : first(a), second(b), compute(objects[a].geometry.get(), objects[b].geometry.get()) + { + request.enable_signed_distance = true; + request.enable_cached_gjk_guess = true; + } + }; + + bool initialized_{false}; + std::vector joint_names_; + RobotModel robot_model_; + std::vector geometry_indices_; + std::vector objects_; + std::vector pairs_; +}; + +CollisionChecker::CollisionChecker() + : impl_(std::make_unique()) +{ +} + +CollisionChecker::~CollisionChecker() = default; +CollisionChecker::CollisionChecker(CollisionChecker&&) noexcept = default; +CollisionChecker& CollisionChecker::operator=(CollisionChecker&&) noexcept = default; + +bool CollisionChecker::init(const RobotModel& model, + const std::vector& active_joint_names, + const CollisionOptions& options, + std::string* error) +{ + try { + return impl_->init(model, active_joint_names, options, error); + } catch (const std::exception& exception) { + impl_->reset(); + setError(error, "Failed to initialize collision checker: " + std::string(exception.what())); + return false; + } +} + +bool CollisionChecker::init(const std::string& urdf_path, + const std::vector& active_joint_names, + const CollisionOptions& options, + std::string* error) +{ + impl_->reset(); + RobotModel model; + if (!model.loadUrdf(urdf_path) || !model.loadCollisionGeometry(urdf_path)) { + setError(error, "Failed to load robot collision model: " + urdf_path); + return false; + } + return init(model, active_joint_names, options, error); +} + +bool CollisionChecker::init(const config::CollisionCheckerConfig& config, + const std::vector& active_joint_names, + std::string* error) +{ + RobotModel model; + model.dof = active_joint_names.size(); + model.joint_names = active_joint_names; + return init(config, model, error); +} + +bool CollisionChecker::init(const config::CollisionCheckerConfig& config, + const RobotModel& robot_model, + std::string* error) +{ + impl_->reset(); + try { + CollisionOptions options; + for (const auto& pair : config.ignored_pairs()) { + options.ignored_pairs.push_back({pair.first(), pair.second()}); + } + auto model = robot_model; + if (!config.urdf_path().empty()) { + const auto path = ConfigHelper::resolveResourceFile(config.urdf_path()); + if (model.collisionUrdfPath().empty() || + std::filesystem::weakly_canonical(path) != + std::filesystem::weakly_canonical(model.collisionUrdfPath())) { + if ((!model.hasKinematics() && !model.loadUrdf(path)) || + !model.loadCollisionGeometry(path)) { + setError(error, "Failed to load robot collision model: " + path); + return false; + } + } + } + return init(model, robot_model.joint_names, options, error); + } catch (const std::exception& exception) { + impl_->reset(); + setError(error, "Failed to initialize collision checker: " + std::string(exception.what())); + return false; + } +} + +std::vector CollisionChecker::collisionBodies( + const std::vector& joint_positions) const +{ + return impl_->collisionBodies(joint_positions); +} + +CollisionResult CollisionChecker::check(const std::vector& bodies) +{ + return impl_->check(bodies); +} + +CollisionResult CollisionChecker::check(const std::vector& joint_positions) +{ + return impl_->check(joint_positions); +} + +bool CollisionChecker::isStateValid(const std::vector& joint_positions, + const CollisionValidationOptions& options) +{ + if (!std::isfinite(options.minimum_distance_m) || options.minimum_distance_m < 0.0) { + throw std::invalid_argument("Collision minimum distance must be finite and non-negative"); + } + const auto collision = check(joint_positions); + if (!collision.valid) { + throw std::runtime_error(collision.error); + } + if (collision.in_collision || !(collision.minimum_distance_m > options.minimum_distance_m)) { + return false; + } + return !options.additional_state_valid || options.additional_state_valid(joint_positions); +} + +CollisionTrajectoryResult CollisionChecker::checkTrajectory( + const device::JointTrajectory& trajectory, const CollisionValidationOptions& options) +{ + CollisionTrajectoryResult result; + if (!initialized()) { + result.error = "CollisionChecker is not initialized"; + return result; + } + if (trajectory.empty()) { + result.error = "Collision trajectory is empty"; + return result; + } + if (!std::isfinite(options.joint_step_rad) || options.joint_step_rad <= 0.0 || + !std::isfinite(options.minimum_distance_m) || options.minimum_distance_m < 0.0) { + result.error = "Collision validation requires a positive finite joint step and non-negative finite clearance"; + return result; + } + + try { + std::vector checked_position(dof()); + double distance_to_check = 0.0; + for (std::size_t i = 0; i < trajectory.size(); ++i) { + if (options.is_cancelled && options.is_cancelled()) { + result.error = "Collision trajectory validation cancelled"; + return result; + } + const auto& to = trajectory[i].position; + const auto& from = trajectory[i == 0 ? 0 : i - 1].position; + if (to.size() != dof()) { + result.error = "Collision trajectory joint position size mismatch at sample " + std::to_string(i); + return result; + } + double maximum_delta = 0.0; + for (std::size_t joint = 0; joint < dof(); ++joint) { + const double delta = to[joint] - from[joint]; + if (!std::isfinite(to[joint]) || !std::isfinite(delta)) { + result.error = "Collision trajectory has a non-finite position or segment at sample " + std::to_string(i); + return result; + } + maximum_delta = std::max(maximum_delta, std::abs(delta)); + } + // Sum each segment's maximum joint increment. Keeping the remainder + // across segments prevents reversals from cancelling travel distance. + while (distance_to_check <= maximum_delta || i + 1 == trajectory.size()) { + if (options.is_cancelled && options.is_cancelled()) { + result.error = "Collision trajectory validation cancelled"; + return result; + } + if (result.validity_checks >= 1000000) { + result.error = "Collision trajectory validation exceeds one million checks"; + return result; + } + const double ratio = maximum_delta > 0.0 + ? std::min(1.0, distance_to_check / maximum_delta) : 1.0; + for (std::size_t joint = 0; joint < dof(); ++joint) { + checked_position[joint] = ratio == 1.0 + ? to[joint] + : from[joint] + ratio * (to[joint] - from[joint]); + } + ++result.validity_checks; + if (!isStateValid(checked_position, options)) { + result.error = "Trajectory failed collision/clearance or additional constraint check at sample " + + std::to_string(i); + return result; + } + distance_to_check += options.joint_step_rad; + if (ratio == 1.0) break; + } + distance_to_check -= maximum_delta; + } + if (options.is_cancelled && options.is_cancelled()) { + result.error = "Collision trajectory validation cancelled"; + return result; + } + result.valid = true; + } catch (const std::exception& exception) { + result.error = "Collision trajectory validation failed: " + std::string(exception.what()); + } catch (...) { + result.error = "Collision trajectory validation callback threw an unknown exception"; + } + return result; +} + +bool CollisionChecker::initialized() const +{ + return impl_->initialized_; +} + +std::size_t CollisionChecker::dof() const +{ + return impl_->joint_names_.size(); +} + +std::size_t CollisionChecker::activePairCount() const +{ + return impl_->pairs_.size(); +} + +const std::vector& CollisionChecker::jointNames() const +{ + return impl_->joint_names_; +} + +} // namespace cmvr diff --git a/cmvr-es/algorithms/collision_detection/self_collision/src/distance_sampling_policy.cpp b/cmvr-es/algorithms/collision_detection/src/distance_sampling_policy.cpp similarity index 80% rename from cmvr-es/algorithms/collision_detection/self_collision/src/distance_sampling_policy.cpp rename to cmvr-es/algorithms/collision_detection/src/distance_sampling_policy.cpp index e45df763..555e2372 100644 --- a/cmvr-es/algorithms/collision_detection/self_collision/src/distance_sampling_policy.cpp +++ b/cmvr-es/algorithms/collision_detection/src/distance_sampling_policy.cpp @@ -1,4 +1,4 @@ -#include "algorithms/collision_detection/self_collision/include/distance_sampling_policy.h" +#include "algorithms/collision_detection/include/distance_sampling_policy.h" #include #include @@ -46,7 +46,7 @@ bool DistanceSamplingPolicy::configure(const DistanceSamplingOptions& options, return true; } -bool DistanceSamplingPolicy::shouldCheck(const CollisionGeometrySnapshot& current, +bool DistanceSamplingPolicy::shouldCheck(const std::vector& current, const Clock::time_point now) const { if (!configured_ || !has_baseline_) { @@ -59,7 +59,7 @@ bool DistanceSamplingPolicy::shouldCheck(const CollisionGeometrySnapshot& curren return displacementSinceLastCheck(current) >= options_.max_geometry_displacement_m; } -void DistanceSamplingPolicy::markChecked(const CollisionGeometrySnapshot& current, +void DistanceSamplingPolicy::markChecked(const std::vector& current, const Clock::time_point now) { last_checked_ = current; @@ -69,22 +69,22 @@ void DistanceSamplingPolicy::markChecked(const CollisionGeometrySnapshot& curren void DistanceSamplingPolicy::reset() { - last_checked_.objects.clear(); + last_checked_.clear(); last_check_time_ = Clock::time_point{}; has_baseline_ = false; } double DistanceSamplingPolicy::displacementSinceLastCheck( - const CollisionGeometrySnapshot& current) const + const std::vector& current) const { - if (!has_baseline_ || current.objects.size() != last_checked_.objects.size()) { + if (!has_baseline_ || current.size() != last_checked_.size()) { return std::numeric_limits::infinity(); } double maximum_displacement = 0.0; - for (std::size_t index = 0; index < current.objects.size(); ++index) { - const auto& previous = last_checked_.objects[index]; - const auto& now = current.objects[index]; + for (std::size_t index = 0; index < current.size(); ++index) { + const auto& previous = last_checked_[index]; + const auto& now = current[index]; if (previous.geometry_index != now.geometry_index) { return std::numeric_limits::infinity(); } diff --git a/cmvr-es/algorithms/collision_detection/test/collision_checker_test.cpp b/cmvr-es/algorithms/collision_detection/test/collision_checker_test.cpp new file mode 100644 index 00000000..d818a005 --- /dev/null +++ b/cmvr-es/algorithms/collision_detection/test/collision_checker_test.cpp @@ -0,0 +1,840 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "algorithms/collision_detection/include/distance_sampling_policy.h" +#include "algorithms/collision_detection/include/collision_checker.h" +#include "common/types/arm/arm_types.h" +#include "environment/include/robot_model.h" + +namespace cmvr { +namespace { + +const std::vector kRightArmJoints{ + "R_SHOULDER_P", + "R_SHOULDER_R", + "R_SHOULDER_Y", + "R_ELBOW_R", + "R_WRIST_P", + "R_WRIST_Y", + "R_WRIST_R", +}; + +const std::vector kGen2RightArmJoints{ + "right_arm_J1", + "right_arm_J2", + "right_arm_J3", + "right_arm_J4", + "right_arm_J5", + "right_arm_J6", + "right_arm_J7", +}; + +const std::vector kGen2SetupPose{ + 0.0, -0.50, 1.5708, 1.5708, -0.041, 0.0, 0.0, +}; + +const std::vector kGen2WarningPose{ + 2.45028525340088, + 0.413065394330014, + -1.78610031118294, + 2.3232081721811, + -2.96828882895788, + -1.59350098130002, + 0.582912411114367, +}; + +const std::vector kGen2StopPose{ + 2.13758633436379, + 1.61835160165575, + -2.3836142221041, + 0.964538527544213, + -0.00382525077004825, + 1.74586899135531, + -0.336868659266887, +}; + +const std::vector kGen2CollisionPose{ + -0.42656969579233, + 1.41426471041774, + -2.67949400419915, + 2.45814854129954, + -2.35907388079205, + 1.14125209449898, + 1.53232912981414, +}; + +const std::vector kGen2TorsoCollisionPose{ + 1.57607137794121, + 2.06613762981425, + -1.76915077905899, + 0.959251437141443, + -0.725973209527894, + 1.79390262120717, + 0.2223354372144, +}; + +std::string collisionUrdfPath() +{ + return std::string(CMVR_ES_SOURCE_DIR) + + "/model/xiaoyan_description/dual_arm_collision.urdf"; +} + +std::string gen2CollisionUrdfPath() +{ + return std::string(CMVR_ES_SOURCE_DIR) + + "/model/gen2/collision/robot_collision.urdf"; +} + +CollisionOptions gen2CollisionOptions() +{ + CollisionOptions options; + options.ignored_pairs.push_back({"arm_link_5_2", "arm_link_7_2"}); + options.ignored_pairs.push_back({"body_link", "arm_link_2_2"}); + return options; +} + +std::vector singleBody(double x, double angle, double radius) +{ + CollisionBody body; + body.geometry_index = 1; + body.position = Eigen::Vector3d(x, 0.0, 0.0); + body.orientation = Eigen::AngleAxisd(angle, Eigen::Vector3d::UnitZ()); + body.bounding_radius_m = radius; + return {body}; +} + +// A translated, rotated fixed frame and one moving joint make world-frame +// transforms and pairs excluded by the self-collision adjacency rules observable. +class BoxSceneUrdf { +public: + explicit BoxSceneUrdf(bool base_collision = true, + bool tip_collision = true, + double mount_x = 2.0) + { + char path[] = "/tmp/cmvr_collision_scene_XXXXXX"; + const int fd = mkstemp(path); + if (fd < 0) { + throw std::runtime_error("Failed to create collision test URDF"); + } + close(fd); + path_ = path; + std::ofstream file(path_); + file << R"()"; + if (base_collision) { + file << R"()"; + } + file << R"( + + + + + + )"; + if (tip_collision) { + file << R"()"; + } + file << R"( + + + + + )"; + } + + ~BoxSceneUrdf() + { + std::error_code error; + std::filesystem::remove(path_, error); + } + + const std::string& path() const { return path_; } + +private: + std::string path_; +}; + +BoxObstacle testBox() +{ + BoxObstacle box; + box.name = "screen"; + box.frame_id = "base"; + box.size_m = Eigen::Vector3d::Constant(0.2); + return box; +} + +CollisionOptions slideBoxOptions(double position = 2.0) +{ + auto box = testBox(); + box.frame_id = "mount"; + box.position_m.x() = position; + CollisionOptions options; + options.obstacles.push_back(box); + return options; +} + +device::JointTrajectory slideTrajectory(std::initializer_list positions) +{ + device::JointTrajectory trajectory; + for (const double position : positions) { + device::JointTrajectoryPoint point; + point.time_s = static_cast(trajectory.size()) * 0.001; + point.position = {position}; + trajectory.push_back(point); + } + return trajectory; +} + +class TemporaryUrdf { +public: + explicit TemporaryUrdf(const std::string& content) + { + char path[] = "/tmp/cmvr_test_urdf_XXXXXX"; + const int fd = mkstemp(path); + if (fd < 0) throw std::runtime_error("Failed to create test URDF"); + close(fd); + path_ = path; + std::ofstream(path_) << content; + } + ~TemporaryUrdf() + { + std::error_code error; + std::filesystem::remove(path_, error); + } + const std::string& path() const { return path_; } + +private: + std::string path_; +}; + +TEST(RobotModelTest, OptionalCollisionGeometryDoesNotInvalidateKinematics) +{ + const BoxSceneUrdf urdf(false, false); + RobotModel model; + std::string error; + ASSERT_TRUE(model.loadUrdf(urdf.path())); + EXPECT_TRUE(model.valid()); + EXPECT_TRUE(model.hasKinematics()); + EXPECT_EQ(model.joint_names, std::vector{"slide"}); + EXPECT_FALSE(model.hasCollisionGeometry()); + EXPECT_EQ(model.collisionGeometryCount(), 0U); + EXPECT_TRUE(model.collisionBodies({0.5}).empty()); + + // A valid URDF without collision elements remains a usable robot model. + ASSERT_TRUE(model.loadCollisionGeometry(urdf.path())); + EXPECT_TRUE(model.valid()); + EXPECT_TRUE(model.hasKinematics()); + EXPECT_FALSE(model.hasCollisionGeometry()); + EXPECT_TRUE(model.collisionBodies({0.5}).empty()); + CollisionChecker checker; + EXPECT_FALSE(checker.init(model, {"slide"}, slideBoxOptions(), &error)); + EXPECT_FALSE(error.empty()); + EXPECT_FALSE(checker.initialized()); + EXPECT_FALSE(checker.check(std::vector{0.0}).valid); +} + +TEST(RobotModelTest, SharedModelKeepsCollisionQueriesAndScenesIndependent) +{ + const BoxSceneUrdf urdf(false); + RobotModel model; + std::string error; + ASSERT_TRUE(model.loadUrdf(urdf.path())); + ASSERT_TRUE(model.loadCollisionGeometry(urdf.path())); + ASSERT_TRUE(model.hasCollisionGeometry()); + EXPECT_EQ(model.collisionGeometryCount(), 1U); // Only tip has geometry. + const auto copy = model; + const auto first_bodies = model.collisionBodies({0.0}); + const auto second_bodies = copy.collisionBodies({1.0}, {"slide"}); + ASSERT_EQ(first_bodies.size(), 1U); + ASSERT_EQ(second_bodies.size(), 1U); + EXPECT_EQ(first_bodies[0].geometry, second_bodies[0].geometry); + EXPECT_EQ(first_bodies[0].link_name, "tip"); + EXPECT_EQ(first_bodies[0].joint_name, "slide"); + const auto& first_pose = first_bodies[0]; + const auto& second_pose = second_bodies[0]; + EXPECT_EQ(first_pose.geometry_index, second_pose.geometry_index); + EXPECT_TRUE(first_pose.position.isApprox(Eigen::Vector3d(2.0, 0.0, 0.0), 1e-12)); + EXPECT_TRUE(second_pose.position.isApprox(Eigen::Vector3d(2.0, 1.0, 0.0), 1e-12)); + EXPECT_TRUE((second_pose.orientation * Eigen::Vector3d::UnitX()).isApprox( + Eigen::Vector3d::UnitY(), 1e-12)); + + CollisionChecker first; + CollisionChecker second; + ASSERT_TRUE(first.init(model, {"slide"}, slideBoxOptions(0.0), &error)) << error; + ASSERT_TRUE(second.init(copy, {"slide"}, slideBoxOptions(1.0), &error)) << error; + for (const double position : {0.0, 1.0, 0.0}) { + const auto first_result = first.check(std::vector{position}); + const auto second_result = second.check(std::vector{position}); + ASSERT_TRUE(first_result.valid) << first_result.error; + ASSERT_TRUE(second_result.valid) << second_result.error; + EXPECT_EQ(first_result.in_collision, position == 0.0); + EXPECT_EQ(second_result.in_collision, position == 1.0); + } + // World obstacles belong to individual checkers, never the shared model. + EXPECT_EQ(model.collisionGeometryCount(), 1U); +} + +TEST(RobotModelTest, FailedCollisionReloadClearsGeometryAndPreservesModelCopies) +{ + const BoxSceneUrdf urdf(false); + const BoxSceneUrdf incompatible(false, true, 3.0); + RobotModel model; + std::string error; + ASSERT_TRUE(model.loadUrdf(urdf.path())); + ASSERT_TRUE(model.loadCollisionGeometry(urdf.path())); + const auto copy = model; + const auto bodies = model.collisionBodies({0.0}); + ASSERT_EQ(bodies.size(), 1U); + ASSERT_FALSE(model.loadCollisionGeometry(incompatible.path())); + EXPECT_TRUE(model.valid()); + EXPECT_TRUE(model.hasKinematics()); + EXPECT_EQ(model.urdfPath(), urdf.path()); + EXPECT_FALSE(model.hasCollisionGeometry()); + EXPECT_TRUE(model.collisionUrdfPath().empty()); + EXPECT_TRUE(copy.hasCollisionGeometry()); + EXPECT_EQ(copy.collisionUrdfPath(), urdf.path()); + EXPECT_TRUE(model.collisionBodies({0.0}).empty()); + const auto copy_bodies = copy.collisionBodies({0.0}); + ASSERT_EQ(copy_bodies.size(), 1U); + EXPECT_EQ(copy_bodies[0].geometry, bodies[0].geometry); + EXPECT_TRUE(copy_bodies[0].position.isApprox(bodies[0].position, 1e-12)); + + RobotModel other; + ASSERT_TRUE(other.loadUrdf(urdf.path())); + ASSERT_TRUE(other.loadCollisionGeometry(urdf.path())); + const auto other_bodies = other.collisionBodies({1.0}); + ASSERT_EQ(other_bodies.size(), 1U); + EXPECT_TRUE(other_bodies[0].position.isApprox(Eigen::Vector3d(2.0, 1.0, 0.0), 1e-12)); + EXPECT_TRUE(bodies[0].position.isApprox(Eigen::Vector3d(2.0, 0.0, 0.0), 1e-12)); + + CollisionChecker checker; + ASSERT_TRUE(checker.init(copy, {"slide"}, slideBoxOptions(0.0), &error)) << error; + EXPECT_TRUE(checker.check(std::vector{0.0}).in_collision); + ASSERT_TRUE(model.loadCollisionGeometry(urdf.path())); + ASSERT_TRUE(model.loadCollisionGeometry("")); + EXPECT_TRUE(model.hasKinematics()); + EXPECT_FALSE(model.hasCollisionGeometry()); + EXPECT_TRUE(model.collisionUrdfPath().empty()); + EXPECT_TRUE(copy.hasCollisionGeometry()); + EXPECT_TRUE(bodies[0].geometry); + EXPECT_TRUE(bodies[0].position.isApprox(Eigen::Vector3d(2.0, 0.0, 0.0), 1e-12)); +} + +TEST(RobotModelTest, CombinesProductionKinematicsAndCollisionUrdfs) +{ + struct ModelCase { + std::string kinematics_path; + std::string collision_path; + std::vector joints; + std::vector position; + CollisionOptions options; + }; + const std::string root = CMVR_ES_SOURCE_DIR; + for (const auto& test : std::vector{ + {root + "/model/xiaoyan_description/dual_arm.urdf", collisionUrdfPath(), + kRightArmJoints, std::vector(7, 0.0), {}}, + {root + "/model/gen2/robot.urdf", gen2CollisionUrdfPath(), + kGen2RightArmJoints, kGen2SetupPose, gen2CollisionOptions()}}) { + SCOPED_TRACE(test.kinematics_path); + RobotModel model; + model.joint_names = test.joints; + model.dof = test.joints.size(); + std::string error; + ASSERT_TRUE(model.loadUrdf(test.kinematics_path)); + EXPECT_TRUE(model.valid()); + EXPECT_TRUE(model.hasKinematics()); + EXPECT_FALSE(model.hasCollisionGeometry()); + ASSERT_TRUE(model.loadCollisionGeometry(test.collision_path)); + EXPECT_TRUE(model.hasCollisionGeometry()); + EXPECT_GT(model.collisionGeometryCount(), 0U); + EXPECT_EQ(model.joint_names, test.joints); + CollisionChecker checker; + ASSERT_TRUE(checker.init(model, test.joints, test.options, &error)) << error; + EXPECT_EQ(checker.dof(), 7U); + const auto model_bodies = model.collisionBodies(test.position, test.joints); + const auto checker_bodies = checker.collisionBodies(test.position); + ASSERT_EQ(model_bodies.size(), checker_bodies.size()); + for (std::size_t index = 0; index < checker_bodies.size(); ++index) { + const auto& from_model = model_bodies[index]; + const auto& from_checker = checker_bodies[index]; + EXPECT_EQ(from_model.geometry_index, from_checker.geometry_index); + EXPECT_TRUE(from_model.position.isApprox(from_checker.position, 1e-12)); + EXPECT_NEAR(from_model.orientation.angularDistance(from_checker.orientation), 0.0, 1e-12); + EXPECT_DOUBLE_EQ(from_model.bounding_radius_m, from_checker.bounding_radius_m); + } + // Compare cold distance queries: cached GJK may converge to slightly + // different values on a repeated query within its solver tolerance. + CollisionChecker bodies_checker; + ASSERT_TRUE(bodies_checker.init(model, test.joints, test.options, &error)) << error; + const auto result = checker.check(test.position); + const auto bodies_result = bodies_checker.check(model_bodies); + ASSERT_TRUE(result.valid) << result.error; + ASSERT_TRUE(bodies_result.valid) << bodies_result.error; + EXPECT_EQ(result.in_collision, bodies_result.in_collision); + EXPECT_DOUBLE_EQ(result.minimum_distance_m, bodies_result.minimum_distance_m); + } +} + +TEST(RobotModelTest, RejectsInvalidCollisionBodySelectionAndJointInput) +{ + RobotModel missing_model; + EXPECT_ANY_THROW(missing_model.collisionBodies({})); + + const BoxSceneUrdf urdf(false); + RobotModel model; + ASSERT_TRUE(model.loadUrdf(urdf.path())); + ASSERT_TRUE(model.loadCollisionGeometry(urdf.path())); + EXPECT_ANY_THROW(model.collisionBodies({0.0}, {"missing"})); + EXPECT_ANY_THROW(model.collisionBodies({0.0, 0.0}, {"slide", "slide"})); + EXPECT_ANY_THROW(model.collisionBodies({0.0}, {"fixed_mount"})); + for (const auto& invalid : std::vector>{ + {}, {0.0, 1.0}, {std::numeric_limits::quiet_NaN()}, + {std::numeric_limits::infinity()}}) { + ASSERT_FALSE(model.collisionBodies({0.0}, {"slide"}).empty()); + EXPECT_ANY_THROW(model.collisionBodies(invalid, {"slide"})); + } + EXPECT_EQ(model.collisionBodies({0.25}, {"slide"}).size(), 1U); +} + +TEST(RobotModelTest, RejectsJointRequiringMultipleConfigurationCoordinates) +{ + const TemporaryUrdf urdf(R"( + + + + + + )"); + RobotModel model; + ASSERT_TRUE(model.loadUrdf(urdf.path())); + EXPECT_ANY_THROW(model.collisionBodies({0.0}, {"continuous_joint"})); +} + +TEST(RobotModelTest, ResolvesOnlyFixedFramesForWorldObstaclePlacement) +{ + const BoxSceneUrdf urdf; + RobotModel model; + ASSERT_TRUE(model.loadUrdf(urdf.path())); + EXPECT_TRUE(model.containsName("base")); + EXPECT_TRUE(model.containsName("mount")); + EXPECT_TRUE(model.containsName("fixed_mount")); + EXPECT_TRUE(model.containsName("slide")); + EXPECT_TRUE(model.containsName("tip")); + EXPECT_FALSE(model.containsName("screen")); + Eigen::Isometry3d pose; + ASSERT_TRUE(model.fixedFramePose("base", pose)); + EXPECT_TRUE(pose.matrix().isApprox(Eigen::Matrix4d::Identity(), 1e-12)); + ASSERT_TRUE(model.fixedFramePose("mount", pose)); + EXPECT_TRUE(pose.translation().isApprox(Eigen::Vector3d(2.0, 0.0, 0.0), 1e-12)); + EXPECT_TRUE((pose.linear() * Eigen::Vector3d::UnitX()).isApprox( + Eigen::Vector3d::UnitY(), 1e-12)); + EXPECT_FALSE(model.fixedFramePose("tip", pose)); + EXPECT_FALSE(model.fixedFramePose("unknown", pose)); +} + +TEST(CollisionCheckerTest, LoadsRightArmFromDualArmUrdf) +{ + CollisionChecker checker; + std::string error; + ASSERT_TRUE(checker.init(collisionUrdfPath(), kRightArmJoints, {}, &error)) << error; + EXPECT_EQ(checker.dof(), 7U); + EXPECT_GT(checker.activePairCount(), 0U); + + const auto bodies = checker.collisionBodies(std::vector(7, 0.0)); + EXPECT_EQ(bodies.size(), 11U); + + const CollisionResult result = checker.check(bodies); + ASSERT_TRUE(result.valid) << result.error; + EXPECT_TRUE(result.first.rfind("L_", 0) != 0); + EXPECT_TRUE(result.second.rfind("L_", 0) != 0); +} + +TEST(CollisionCheckerTest, RejectsWrongJointVectorSize) +{ + CollisionChecker checker; + std::string error; + ASSERT_TRUE(checker.init(collisionUrdfPath(), kRightArmJoints, {}, &error)) << error; + + EXPECT_ANY_THROW(checker.collisionBodies(std::vector(6, 0.0))); + EXPECT_FALSE(checker.check(std::vector(6, 0.0)).valid); +} + +TEST(CollisionCheckerTest, RemovesConfiguredIgnoredPair) +{ + CollisionChecker baseline; + CollisionChecker filtered; + std::string error; + ASSERT_TRUE(baseline.init(collisionUrdfPath(), kRightArmJoints, {}, &error)) << error; + + CollisionOptions options; + options.ignored_pairs.push_back({"base_link", "R_ELBOW_R_S"}); + ASSERT_TRUE(filtered.init(collisionUrdfPath(), kRightArmJoints, options, &error)) << error; + EXPECT_EQ(filtered.activePairCount() + 1, baseline.activePairCount()); +} + +TEST(CollisionCheckerTest, LoadsGen2RightArmCollisionModel) +{ + CollisionChecker checker; + std::string error; + ASSERT_TRUE(checker.init( + gen2CollisionUrdfPath(), + kGen2RightArmJoints, + gen2CollisionOptions(), + &error)) << error; + EXPECT_EQ(checker.dof(), 7U); + EXPECT_EQ(checker.activePairCount(), 19U); + + const auto bodies = checker.collisionBodies(kGen2SetupPose); + EXPECT_EQ(bodies.size(), 8U); + + const CollisionResult setup_result = checker.check(bodies); + ASSERT_TRUE(setup_result.valid) << setup_result.error; + EXPECT_FALSE(setup_result.in_collision); + EXPECT_GT(setup_result.minimum_distance_m, 0.02); +} + +TEST(CollisionCheckerTest, ClassifiesGen2SafetyDistances) +{ + CollisionChecker checker; + std::string error; + ASSERT_TRUE(checker.init( + gen2CollisionUrdfPath(), + kGen2RightArmJoints, + gen2CollisionOptions(), + &error)) << error; + + const CollisionResult warning_result = checker.check(kGen2WarningPose); + ASSERT_TRUE(warning_result.valid) << warning_result.error; + EXPECT_FALSE(warning_result.in_collision); + EXPECT_GT(warning_result.minimum_distance_m, 0.005); + EXPECT_LE(warning_result.minimum_distance_m, 0.02); + + const CollisionResult stop_result = checker.check(kGen2StopPose); + ASSERT_TRUE(stop_result.valid) << stop_result.error; + EXPECT_FALSE(stop_result.in_collision); + EXPECT_GT(stop_result.minimum_distance_m, 0.0); + EXPECT_LE(stop_result.minimum_distance_m, 0.005); + + const CollisionResult collision_result = checker.check(kGen2CollisionPose); + ASSERT_TRUE(collision_result.valid) << collision_result.error; + EXPECT_TRUE(collision_result.in_collision); + EXPECT_LE(collision_result.minimum_distance_m, 0.0); + + const CollisionResult torso_result = + checker.check(kGen2TorsoCollisionPose); + ASSERT_TRUE(torso_result.valid) << torso_result.error; + EXPECT_TRUE(torso_result.in_collision); + EXPECT_LE(torso_result.minimum_distance_m, 0.0); + EXPECT_TRUE(torso_result.first == "body_link" || + torso_result.second == "body_link"); +} + +TEST(CollisionCheckerTest, WorldPairsIncludeStaticBaseAndFirstJointDespiteSelfFilters) +{ + const BoxSceneUrdf urdf; + CollisionOptions options; + options.ignored_pairs.push_back({"base", "tip"}); + auto box = testBox(); + options.obstacles = {box}; + CollisionChecker checker; + std::string error; + ASSERT_TRUE(checker.init(urdf.path(), {"slide"}, options, &error)) << error; + EXPECT_EQ(checker.activePairCount(), 2U); + auto result = checker.check(std::vector{0.0}); + ASSERT_TRUE(result.valid) << result.error; + EXPECT_TRUE(result.in_collision); + EXPECT_EQ(result.first, "base"); + EXPECT_EQ(result.second, "screen"); + + options.obstacles.front().position_m.x() = 2.0; + ASSERT_TRUE(checker.init(urdf.path(), {"slide"}, options, &error)) << error; + result = checker.check(std::vector{0.0}); + ASSERT_TRUE(result.valid) << result.error; + EXPECT_TRUE(result.in_collision); + EXPECT_EQ(result.first, "tip"); + + options.obstacles.front().position_m.x() = 5.0; + ASSERT_TRUE(checker.init(urdf.path(), {"slide"}, options, &error)) << error; + result = checker.check(std::vector{0.0}); + ASSERT_TRUE(result.valid) << result.error; + EXPECT_FALSE(result.in_collision); + EXPECT_NEAR(result.minimum_distance_m, 2.85, 1e-6); + + // The scene is owned by the checker after initialization. + options.obstacles.front().position_m.setZero(); + EXPECT_FALSE(checker.check(std::vector{0.0}).in_collision); + + // Overlapping world boxes do not create world-world collision pairs. + box.position_m.x() = 5.0; + options.obstacles = {box, box}; + options.obstacles.back().name = "table"; + ASSERT_TRUE(checker.init(urdf.path(), {"slide"}, options, &error)) << error; + EXPECT_EQ(checker.activePairCount(), 4U); + EXPECT_FALSE(checker.check(std::vector{0.0}).in_collision); +} + +TEST(CollisionCheckerTest, RotatesBoxesInFixedFramesAndChecksExternalRobotBodies) +{ + const BoxSceneUrdf urdf(false); + CollisionOptions options; + auto box = testBox(); + box.frame_id = "mount"; + box.size_m = Eigen::Vector3d(0.6, 0.06, 0.06); + box.position_m = Eigen::Vector3d(1.0, 0.2, 0.0); + box.orientation = Eigen::AngleAxisd(std::acos(-1.0) / 2.0, Eigen::Vector3d::UnitZ()); + box.orientation.coeffs() *= 2.0; // Non-unit finite quaternions are normalized. + options.obstacles = {box}; + CollisionChecker checker; + std::string error; + ASSERT_TRUE(checker.init(urdf.path(), {"slide"}, options, &error)) << error; + EXPECT_EQ(checker.activePairCount(), 1U); + + RobotModel model; + ASSERT_TRUE(model.loadUrdf(urdf.path())); + ASSERT_TRUE(model.loadCollisionGeometry(urdf.path())); + auto bodies = model.collisionBodies({1.0}); + ASSERT_EQ(bodies.size(), 1U); + auto result = checker.check(bodies); // No preceding checker FK query. + ASSERT_TRUE(result.valid) << result.error; + EXPECT_TRUE(result.in_collision); + EXPECT_EQ(result.first, "tip"); + EXPECT_EQ(result.second, "screen"); + + bodies = checker.collisionBodies({0.0}); + EXPECT_EQ(bodies.size(), 1U); + result = checker.check(bodies); + ASSERT_TRUE(result.valid) << result.error; + EXPECT_FALSE(result.in_collision); + EXPECT_TRUE(checker.check(std::vector{1.0}).in_collision); + + options.obstacles.front().orientation.setIdentity(); + ASSERT_TRUE(checker.init(urdf.path(), {"slide"}, options, &error)) << error; + result = checker.check(std::vector{1.0}); + ASSERT_TRUE(result.valid) << result.error; + EXPECT_FALSE(result.in_collision); +} + +TEST(CollisionCheckerTest, RejectsInvalidObstacleScenes) +{ + const BoxSceneUrdf urdf; + CollisionChecker checker; + const auto reject = [&](const BoxObstacle& box) { + CollisionOptions options; + options.obstacles = {box}; + std::string error; + EXPECT_FALSE(checker.init(urdf.path(), {"slide"}, options, &error)); + EXPECT_FALSE(error.empty()); + EXPECT_FALSE(checker.initialized()); + }; + for (const auto& name : {"", "base", "tip", "slide", "tip_0"}) { + auto box = testBox(); + box.name = name; + reject(box); + } + for (const auto& frame : {"", "missing", "tip", "slide"}) { + auto box = testBox(); + box.frame_id = frame; + reject(box); + } + for (const auto value : {0.0, -1.0, std::numeric_limits::infinity(), + std::numeric_limits::quiet_NaN()}) { + auto box = testBox(); + box.size_m.x() = value; + reject(box); + } + auto box = testBox(); + box.position_m.y() = std::numeric_limits::infinity(); + reject(box); + box = testBox(); + box.orientation.coeffs().setZero(); + reject(box); + box.orientation.x() = std::numeric_limits::quiet_NaN(); + reject(box); + + CollisionOptions options; + options.obstacles = {testBox(), testBox()}; + std::string error; + EXPECT_FALSE(checker.init(urdf.path(), {"slide"}, options, &error)); + EXPECT_NE(error.find("unique"), std::string::npos); + EXPECT_FALSE(checker.initialized()); +} + +TEST(CollisionCheckerTest, TrajectoryRejectsObstacleBetweenValidEndpoints) +{ + const BoxSceneUrdf urdf(false); + CollisionChecker checker; + std::string error; + ASSERT_TRUE(checker.init(urdf.path(), {"slide"}, slideBoxOptions(0.0), &error)) << error; + ASSERT_TRUE(checker.isStateValid({-0.4})); + ASSERT_TRUE(checker.isStateValid({0.4})); + + const auto result = checker.checkTrajectory(slideTrajectory({-0.4, 0.4})); + EXPECT_FALSE(result.valid); + EXPECT_GT(result.validity_checks, 2U); + EXPECT_FALSE(result.error.empty()); +} + +TEST(CollisionCheckerTest, TrajectoryAccumulatesShortSegmentsAcrossReversal) +{ + const BoxSceneUrdf urdf(false); + CollisionChecker checker; + std::string error; + ASSERT_TRUE(checker.init(urdf.path(), {"slide"}, slideBoxOptions(), &error)) << error; + CollisionValidationOptions options; + options.joint_step_rad = 0.01; + std::vector checked; + options.additional_state_valid = [&](const std::vector& q) { + checked.push_back(q[0]); + return true; + }; + const auto result = checker.checkTrajectory(slideTrajectory({0.0, 0.006, 0.012, 0.006, 0.0}), options); + ASSERT_TRUE(result.valid) << result.error; + ASSERT_EQ(checked.size(), 4U); + EXPECT_EQ(result.validity_checks, checked.size()); + EXPECT_DOUBLE_EQ(checked[0], 0.0); + EXPECT_NEAR(checked[1], 0.01, 1e-12); + EXPECT_NEAR(checked[2], 0.004, 1e-12); + EXPECT_DOUBLE_EQ(checked[3], 0.0); +} + +TEST(CollisionCheckerTest, TrajectoryChecksEndpointEvenBelowSamplingStep) +{ + const BoxSceneUrdf urdf(false); + CollisionChecker checker; + std::string error; + ASSERT_TRUE(checker.init(urdf.path(), {"slide"}, slideBoxOptions(), &error)) << error; + CollisionValidationOptions options; + options.joint_step_rad = 0.02; + options.additional_state_valid = [](const std::vector& q) { return q[0] < 0.014; }; + const auto result = checker.checkTrajectory(slideTrajectory({0.0, 0.015}), options); + EXPECT_FALSE(result.valid); + EXPECT_EQ(result.validity_checks, 2U); + EXPECT_FALSE(result.error.empty()); +} + +TEST(CollisionCheckerTest, StateAndTrajectoryShareClearanceAndAdditionalConstraints) +{ + const BoxSceneUrdf urdf(false); + CollisionChecker checker; + std::string error; + ASSERT_TRUE(checker.init(urdf.path(), {"slide"}, slideBoxOptions(0.0), &error)) << error; + CollisionValidationOptions options; + options.minimum_distance_m = 0.2; + EXPECT_FALSE(checker.isStateValid({0.3}, options)); // Physical gap is 0.15 m. + EXPECT_FALSE(checker.checkTrajectory(slideTrajectory({0.3, 0.4}), options).valid); + options.minimum_distance_m = 0.1; + EXPECT_TRUE(checker.isStateValid({0.3}, options)); + options.additional_state_valid = [](const std::vector& q) { + // A caller's TCP workspace constraint can reject a collision-free sample. + return q[0] <= 0.31 || q[0] >= 0.35; + }; + EXPECT_TRUE(checker.isStateValid({0.3}, options)); + EXPECT_TRUE(checker.isStateValid({0.4}, options)); + EXPECT_FALSE(checker.isStateValid({0.33}, options)); + const auto result = checker.checkTrajectory(slideTrajectory({0.3, 0.4}), options); + EXPECT_FALSE(result.valid); + EXPECT_GE(result.validity_checks, 2U); +} + +TEST(CollisionCheckerTest, TrajectoryCancellationStopsFurtherQueries) +{ + const BoxSceneUrdf urdf(false); + CollisionChecker checker; + std::string error; + ASSERT_TRUE(checker.init(urdf.path(), {"slide"}, slideBoxOptions(), &error)) << error; + CollisionValidationOptions options; + std::size_t checked = 0; + options.additional_state_valid = [&](const std::vector&) { + ++checked; + return true; + }; + options.is_cancelled = [] { return true; }; + auto result = checker.checkTrajectory(slideTrajectory({0.0, 0.5}), options); + EXPECT_FALSE(result.valid); + EXPECT_EQ(checked, 0U); + EXPECT_EQ(result.validity_checks, 0U); + EXPECT_FALSE(result.error.empty()); + + options.is_cancelled = [&] { return checked >= 2; }; + result = checker.checkTrajectory(slideTrajectory({0.0, 0.5}), options); + EXPECT_FALSE(result.valid); + EXPECT_EQ(checked, 2U); + EXPECT_EQ(result.validity_checks, 2U); + EXPECT_FALSE(result.error.empty()); +} + +TEST(CollisionCheckerTest, ValidationRejectsMalformedInputAndCallbackFailure) +{ + const BoxSceneUrdf urdf(false); + CollisionChecker checker; + std::string error; + ASSERT_TRUE(checker.init(urdf.path(), {"slide"}, slideBoxOptions(), &error)) << error; + EXPECT_FALSE(checker.checkTrajectory({}).valid); + for (const auto& q : std::vector>{ + {}, {0.0, 0.0}, {std::numeric_limits::infinity()}, + {std::numeric_limits::quiet_NaN()}}) { + EXPECT_THROW(checker.isStateValid(q), std::exception); + auto trajectory = slideTrajectory({0.0, 0.001, 0.002}); + trajectory[1].position = q; + const auto result = checker.checkTrajectory(trajectory); + EXPECT_FALSE(result.valid); + EXPECT_FALSE(result.error.empty()); + } + for (const double step : {0.0, -0.01, std::numeric_limits::infinity(), + std::numeric_limits::quiet_NaN()}) { + CollisionValidationOptions options; + options.joint_step_rad = step; + EXPECT_FALSE(checker.checkTrajectory(slideTrajectory({0.0, 0.1}), options).valid); + } + for (const double clearance : {-0.01, std::numeric_limits::infinity(), + std::numeric_limits::quiet_NaN()}) { + CollisionValidationOptions options; + options.minimum_distance_m = clearance; + EXPECT_THROW(checker.isStateValid({0.0}, options), std::exception); + EXPECT_FALSE(checker.checkTrajectory(slideTrajectory({0.0, 0.1}), options).valid); + } + CollisionValidationOptions options; + options.additional_state_valid = [](const std::vector&) -> bool { + throw std::runtime_error("TCP constraint query failed"); + }; + const auto result = checker.checkTrajectory(slideTrajectory({0.0, 0.1}), options); + EXPECT_FALSE(result.valid); + EXPECT_NE(result.error.find("TCP constraint query failed"), std::string::npos); +} + +TEST(DistanceSamplingPolicyTest, SamplesByAccumulatedGeometryDisplacement) +{ + DistanceSamplingPolicy policy; + DistanceSamplingOptions options; + options.max_geometry_displacement_m = 0.002; + options.max_check_period_s = 0.01; + std::string error; + ASSERT_TRUE(policy.configure(options, &error)) << error; + + const auto start = DistanceSamplingPolicy::Clock::now(); + const auto initial = singleBody(0.0, 0.0, 0.2); + EXPECT_TRUE(policy.shouldCheck(initial, start)); + policy.markChecked(initial, start); + + EXPECT_FALSE(policy.shouldCheck( + singleBody(0.001, 0.0, 0.2), start + std::chrono::milliseconds(1))); + EXPECT_TRUE(policy.shouldCheck( + singleBody(0.0021, 0.0, 0.2), start + std::chrono::milliseconds(2))); + EXPECT_TRUE(policy.shouldCheck( + singleBody(0.0, 0.011, 0.2), start + std::chrono::milliseconds(2))); + EXPECT_TRUE(policy.shouldCheck( + initial, start + std::chrono::milliseconds(10))); +} + +} // namespace +} // namespace cmvr diff --git a/cmvr-es/algorithms/controllers/CMakeLists.txt b/cmvr-es/algorithms/controllers/CMakeLists.txt index 07fe6948..71fbc1b3 100644 --- a/cmvr-es/algorithms/controllers/CMakeLists.txt +++ b/cmvr-es/algorithms/controllers/CMakeLists.txt @@ -1,6 +1,3 @@ - -add_subdirectory(arm_control) - #find_package(VISP REQUIRED) # 如果报 relocation ... can not be used when making a shared object; recompile with -fPIC ,说明SRC 中包含了test文件 ,test diff --git a/cmvr-es/algorithms/controllers/arm_control/CMakeLists.txt b/cmvr-es/algorithms/controllers/arm_control/CMakeLists.txt deleted file mode 100644 index 3194deb1..00000000 --- a/cmvr-es/algorithms/controllers/arm_control/CMakeLists.txt +++ /dev/null @@ -1,17 +0,0 @@ -add_library(arm_control SHARED - src/cartesian_velocity_controller.cpp -) - -target_include_directories(arm_control PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) - -target_link_libraries(arm_control - PUBLIC - cmvr_es::algorithms::arm_motion -) - -add_library(cmvr_es::algorithms::arm_control ALIAS arm_control) -install(TARGETS arm_control LIBRARY DESTINATION lib) - -add_executable(cartesian_velocity_controller_test src/cartesian_velocity_controller_test.cpp) -target_link_libraries(cartesian_velocity_controller_test PRIVATE - cmvr_es::algorithms::arm_control gtest gtest_main pthread) diff --git a/cmvr-es/algorithms/controllers/arm_control/include/cartesian_velocity_controller.h b/cmvr-es/algorithms/controllers/arm_control/include/cartesian_velocity_controller.h deleted file mode 100644 index cc6fc7ff..00000000 --- a/cmvr-es/algorithms/controllers/arm_control/include/cartesian_velocity_controller.h +++ /dev/null @@ -1,92 +0,0 @@ -#ifndef CMVR_ES_CARTESIAN_VELOCITY_CONTROLLER_H -#define CMVR_ES_CARTESIAN_VELOCITY_CONTROLLER_H - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "algorithms/motion_planner/arm_motion/cartesian_motion/cartesian_motion_planner.h" -#include "common/types/arm/arm_types.h" - -namespace cmvr::device { - -class CartesianVelocityController { -public: - struct Config { - double control_period_s{0.001}; - double stop_twist_norm{1e-9}; - double stop_command_velocity_norm{1e-3}; - double stop_measured_velocity_norm{1e-2}; - double stop_acceleration{0.5}; - double stop_timeout_s{2.0}; - }; - - using ReadStateCallback = std::function& q, std::vector& qd)>; - using SendVelocityCallback = std::function; - - CartesianVelocityController(Config config, - std::shared_ptr planner, - std::size_t dof, - ReadStateCallback read_state, - SendVelocityCallback send_velocity); - ~CartesianVelocityController(); - - CartesianVelocityController(const CartesianVelocityController&) = delete; - CartesianVelocityController& operator=(const CartesianVelocityController&) = delete; - - Result speedL(const CartesianVelocity& velocity, - double acceleration, - double duration, - FrameType frame); - Result stop(std::optional acceleration = std::nullopt); - Result speedL(const CartesianVelocity& velocity, const SpeedLOptions& options, - double duration, FrameType frame); - SpeedLReference getReference() const; - void shutdown(); - - bool busy() const { return busy_.load(); } - double stopTimeoutS() const { return config_.stop_timeout_s; } - CartesianVelocity getCommandTwistBase() const; - -private: - void ensureWorkerStarted_(); - void workerLoop_(); - void requestStop_(std::optional acceleration = std::nullopt); - void abortCommand_(); - void sendZero_(); - - static double velocityNorm_(const std::vector& velocity); - static double twistNorm_(const CartesianVelocity& velocity); - -private: - Config config_; - std::shared_ptr planner_; - std::size_t dof_{0}; - ReadStateCallback read_state_; - SendVelocityCallback send_velocity_; - - std::unique_ptr worker_; - mutable std::mutex mutex_; - std::condition_variable cv_; - std::atomic stop_requested_{false}; - bool command_active_{false}; - CartesianVelocity target_twist_{}; - FrameType target_frame_{FrameType::Base}; - double target_acceleration_{0.25}; - SpeedLOptions target_options_{}; - SpeedLReference reference_{}; - CartesianVelocity command_twist_snapshot_{}; - std::uint64_t command_version_{0}; - std::atomic busy_{false}; -}; - -} // namespace cmvr::device - -#endif // CMVR_ES_CARTESIAN_VELOCITY_CONTROLLER_H diff --git a/cmvr-es/algorithms/controllers/arm_control/src/cartesian_velocity_controller.cpp b/cmvr-es/algorithms/controllers/arm_control/src/cartesian_velocity_controller.cpp deleted file mode 100644 index 073a7d47..00000000 --- a/cmvr-es/algorithms/controllers/arm_control/src/cartesian_velocity_controller.cpp +++ /dev/null @@ -1,379 +0,0 @@ -#include "algorithms/controllers/arm_control/include/cartesian_velocity_controller.h" - -#include -#include -#include -#include - -#include "common/base/logging/logger.h" - -namespace cmvr::device { - -namespace { - -CartesianVelocityController::Config normalizeConfig(CartesianVelocityController::Config config) -{ - const CartesianVelocityController::Config defaults; - if (config.control_period_s <= 0.0) { - config.control_period_s = defaults.control_period_s; - } - if (config.stop_twist_norm <= 0.0) { - config.stop_twist_norm = defaults.stop_twist_norm; - } - if (config.stop_command_velocity_norm <= 0.0) { - config.stop_command_velocity_norm = defaults.stop_command_velocity_norm; - } - if (config.stop_measured_velocity_norm <= 0.0) { - config.stop_measured_velocity_norm = defaults.stop_measured_velocity_norm; - } - if (config.stop_acceleration <= 0.0) { - config.stop_acceleration = defaults.stop_acceleration; - } - if (!std::isfinite(config.stop_timeout_s) || config.stop_timeout_s <= 0.0) { - config.stop_timeout_s = defaults.stop_timeout_s; - } - return config; -} - -} // namespace - -CartesianVelocityController::CartesianVelocityController( - Config config, - std::shared_ptr planner, - const std::size_t dof, - ReadStateCallback read_state, - SendVelocityCallback send_velocity) - : config_(normalizeConfig(config)), - planner_(std::move(planner)), - dof_(dof), - read_state_(std::move(read_state)), - send_velocity_(std::move(send_velocity)) -{ -} - -CartesianVelocityController::~CartesianVelocityController() -{ - shutdown(); -} - -Result CartesianVelocityController::speedL(const CartesianVelocity& velocity, - const double acceleration, - const double duration, - const FrameType frame) -{ - SpeedLOptions options; - options.acceleration = acceleration; - return speedL(velocity, options, duration, frame); -} - -Result CartesianVelocityController::speedL(const CartesianVelocity& velocity, - const SpeedLOptions& options, - const double duration, const FrameType frame) -{ - const double acceleration = options.acceleration; - if (!planner_ || !read_state_ || !send_velocity_ || dof_ == 0 || - !std::isfinite(acceleration) || acceleration <= 0.0 || - !std::isfinite(duration) || duration < 0.0 || !std::isfinite(twistNorm_(velocity)) || - (options.linear_jerk && (!std::isfinite(*options.linear_jerk) || *options.linear_jerk <= 0.0))) { - return Result::failure(ArmErrorCode::InvalidArgument, "speedL invalid input"); - } - if (!worker_ || !worker_->joinable()) { - if (busy_.exchange(true)) { - return Result::failure(ArmErrorCode::RobotNotReady, "arm is busy"); - } - } - - ensureWorkerStarted_(); - - std::uint64_t command_version = 0; - { - std::lock_guard lock(mutex_); - target_twist_ = velocity; - target_acceleration_ = acceleration; - target_frame_ = frame; - target_options_ = options; - reference_ = {}; - command_active_ = true; - busy_.store(true); - command_version = ++command_version_; - } - cv_.notify_all(); - - if (duration > 0.0) { - std::this_thread::sleep_for(std::chrono::duration(duration)); - bool should_stop = false; - { - std::lock_guard lock(mutex_); - if (command_version_ == command_version) { - target_twist_ = {}; - target_frame_ = FrameType::Base; - command_active_ = true; - ++command_version_; - should_stop = true; - } - } - if (should_stop) { - cv_.notify_all(); - } - } - return Result::success(); -} - -Result CartesianVelocityController::stop(const std::optional acceleration) -{ - if (!worker_ || !worker_->joinable()) { - return Result::success(); - } - // A completed speedL command leaves the worker thread joinable but idle. - // Do not turn that idle worker into a new command just because a caller - // requests a stop during a task transition. - if (!busy_.load()) { - return Result::success(); - } - requestStop_(acceleration); - return Result::success(); -} - -void CartesianVelocityController::shutdown() -{ - if (!worker_ || !worker_->joinable()) { - busy_.store(false); - return; - } - { - std::lock_guard lock(mutex_); - stop_requested_.store(true); - command_active_ = false; - target_twist_ = {}; - target_frame_ = FrameType::Base; - } - cv_.notify_all(); - worker_->join(); - worker_.reset(); - stop_requested_.store(false); - busy_.store(false); -} - -CartesianVelocity CartesianVelocityController::getCommandTwistBase() const -{ - std::lock_guard lock(mutex_); - return command_twist_snapshot_; -} - -SpeedLReference CartesianVelocityController::getReference() const -{ - std::lock_guard lock(mutex_); - return reference_; -} - -void CartesianVelocityController::ensureWorkerStarted_() -{ - if (worker_ && worker_->joinable()) { - return; - } - stop_requested_.store(false); - worker_ = std::make_unique(&CartesianVelocityController::workerLoop_, this); -} - -void CartesianVelocityController::workerLoop_() -{ - const double dt = config_.control_period_s; - auto next_tick = std::chrono::steady_clock::now(); - - while (true) { - CartesianVelocity target_twist; - double acceleration = 0.25; - FrameType target_frame = FrameType::Base; - SpeedLOptions options; - std::uint64_t applied_version = 0; - bool capture_reference = false; - { - std::unique_lock lock(mutex_); - cv_.wait(lock, [&]() { - return stop_requested_.load() || command_active_; - }); - if (stop_requested_.load()) { - break; - } - target_twist = target_twist_; - acceleration = target_acceleration_; - target_frame = target_frame_; - } - - next_tick = std::chrono::steady_clock::now(); - while (true) { - { - std::lock_guard lock(mutex_); - if (stop_requested_.load()) { - sendZero_(); - busy_.store(false); - return; - } - if (!command_active_) { - break; - } - target_twist = target_twist_; - acceleration = target_acceleration_; - target_frame = target_frame_; - options = target_options_; - options.acceleration = acceleration; - applied_version = command_version_; - capture_reference = options.capture_reference && !reference_.valid; - } - - if (!planner_->updateSpeedLLimits(options)) { - if (twistNorm_(target_twist) < config_.stop_twist_norm) { - abortCommand_(); - break; - } - CMVR_LOG(ERROR) << "[CartesianVelocityController][speedL] updateSpeedLAcceleration failed, acceleration=" - << acceleration; - requestStop_(); - continue; - } - - std::vector q_now; - std::vector qd_now; - if (!read_state_(q_now, qd_now)) { - CMVR_LOG(ERROR) << "[CartesianVelocityController][speedL] read_state failed"; - if (twistNorm_(target_twist) < config_.stop_twist_norm) { - abortCommand_(); - break; - } - requestStop_(); - continue; - } - - std::vector qd_cmd; - SpeedLReference reference; - if (capture_reference && - !planner_->captureSpeedLReference(q_now, target_twist, target_frame, reference)) { - CMVR_LOG(ERROR) << "[CartesianVelocityController][speedL] cannot capture motion reference"; - abortCommand_(); - break; - } - if (!planner_->speedLStep(target_twist, dt, q_now, qd_now, qd_cmd, target_frame)) { - CMVR_LOG(ERROR) << "[CartesianVelocityController][speedL] speedLStep failed, target_twist=[" - << target_twist.vx << ", " << target_twist.vy << ", " - << target_twist.vz << ", " << target_twist.wx << ", " - << target_twist.wy << ", " << target_twist.wz - << "], frame=" << (target_frame == FrameType::Tool ? "Tool" : "Base"); - if (twistNorm_(target_twist) < config_.stop_twist_norm) { - abortCommand_(); - break; - } - requestStop_(); - continue; - } - - JointVelocityCommand velocity_command; - velocity_command.velocity = qd_cmd; - const auto send_result = send_velocity_(velocity_command, acceleration); - if (!send_result.ok()) { - CMVR_LOG(ERROR) << "[CartesianVelocityController][speedL] send_velocity failed: " - << send_result.message; - if (twistNorm_(target_twist) < config_.stop_twist_norm) { - abortCommand_(); - break; - } - requestStop_(); - continue; - } - - { - std::lock_guard lock(mutex_); - command_twist_snapshot_ = planner_->getSpeedLCommandTwistBase(); - if (capture_reference && command_version_ == applied_version) { - reference.command_version = applied_version; - reference_ = reference; - // Lock a captured Tool-frame translation in Base for the - // entire command, matching its distance reference axis. - target_twist_ = reference.target_base; - target_frame_ = FrameType::Base; - } - } - - if (twistNorm_(target_twist) < config_.stop_twist_norm && - velocityNorm_(qd_cmd) < config_.stop_command_velocity_norm && - velocityNorm_(qd_now) < config_.stop_measured_velocity_norm) { - { - std::lock_guard lock(mutex_); - // A newer target may have arrived during planning/I/O. - if (command_version_ != applied_version) continue; - command_active_ = false; - // Serialize the final zero and busy transition with new - // submissions, not only the version comparison. - sendZero_(); - busy_.store(false); - } - break; - } - - next_tick += std::chrono::duration_cast( - std::chrono::duration(dt)); - std::this_thread::sleep_until(next_tick); - } - } - - sendZero_(); - busy_.store(false); -} - -void CartesianVelocityController::requestStop_(const std::optional acceleration) -{ - { - std::lock_guard lock(mutex_); - target_twist_ = {}; - target_frame_ = FrameType::Base; - target_acceleration_ = acceleration.has_value() ? *acceleration - : config_.stop_acceleration; - target_options_.acceleration = target_acceleration_; - target_options_.capture_reference = false; - command_active_ = true; - ++command_version_; - } - cv_.notify_all(); -} - -void CartesianVelocityController::abortCommand_() -{ - { - std::lock_guard lock(mutex_); - command_active_ = false; - target_twist_ = {}; - target_frame_ = FrameType::Base; - sendZero_(); - busy_.store(false); - } -} - -void CartesianVelocityController::sendZero_() -{ - if (!send_velocity_) { - return; - } - JointVelocityCommand zero; - zero.velocity.assign(dof_, 0.0); - (void)send_velocity_(zero, 0.0); -} - -double CartesianVelocityController::velocityNorm_(const std::vector& velocity) -{ - double value = 0.0; - for (const double item : velocity) { - value += item * item; - } - return std::sqrt(value); -} - -double CartesianVelocityController::twistNorm_(const CartesianVelocity& velocity) -{ - return std::sqrt(velocity.vx * velocity.vx + - velocity.vy * velocity.vy + - velocity.vz * velocity.vz + - velocity.wx * velocity.wx + - velocity.wy * velocity.wy + - velocity.wz * velocity.wz); -} - -} // namespace cmvr::device diff --git a/cmvr-es/algorithms/controllers/arm_control/src/cartesian_velocity_controller_test.cpp b/cmvr-es/algorithms/controllers/arm_control/src/cartesian_velocity_controller_test.cpp deleted file mode 100644 index daf2ed72..00000000 --- a/cmvr-es/algorithms/controllers/arm_control/src/cartesian_velocity_controller_test.cpp +++ /dev/null @@ -1,131 +0,0 @@ -#include -#include "algorithms/controllers/arm_control/include/cartesian_velocity_controller.h" -#include -#include -#include -#include - -namespace cmvr::device { -namespace { -using namespace std::chrono_literals; -class Planner final : public CartesianMotionPlanner { -public: - bool configureSpeedL(const config::SpeedLPlannerConfig&, std::size_t) override { return true; } - bool configureMoveL(const config::MoveLPlannerConfig&) override { return true; } - bool planMoveL(const CartesianPose&, const std::vector&, const std::vector&, - double, double, double, FrameType, CartesianJointTrajectory&) override { return false; } - bool updateSpeedLAcceleration(double) override { return true; } - bool updateSpeedLLimits(const SpeedLOptions& options) override { - applied_reversal.store(options.continuous_linear_reversal.value_or(false)); - applied_jerk.store(options.linear_jerk.value_or(10.0)); return true; - } - bool captureSpeedLReference(const std::vector&, const CartesianVelocity& target, - FrameType, SpeedLReference& ref) override { - ref.valid = true; - ref.tcp_pose_base.y = .5; - ref.target_base.vx = target.vy; - return true; - } - bool speedLStep(const CartesianVelocity& v, double, const std::vector&, - const std::vector&, std::vector& out, FrameType) override { - current = v; out = {v.vy}; return true; - } - CartesianVelocity getSpeedLCommandTwistBase() const override { return current; } - CartesianVelocity current; - std::atomic applied_jerk{0.0}; - std::atomic applied_reversal{false}; -}; -TEST(CartesianVelocityController, CompletedStopCannotClearNewReversal) { - std::mutex mutex; - std::condition_variable cv; - bool forward_sent = false, block_zero = false, zero_entered = false; - bool release_zero = false, reverse_sent = false; - auto planner = std::make_shared(); - CartesianVelocityController controller({}, planner, 1, - [](auto& q, auto& qd) { q = {0}; qd = {0}; return true; }, - [&](const JointVelocityCommand& command, double) { - std::unique_lock lock(mutex); - forward_sent |= command.velocity[0] > 0; - reverse_sent |= command.velocity[0] < 0; - if (command.velocity[0] == 0 && block_zero && !zero_entered) { - zero_entered = true; cv.notify_all(); - cv.wait_for(lock, 2s, [&] { return release_zero; }); - } - cv.notify_all(); return Result::success(); - }); - CartesianVelocity v; v.vy = .08; - ASSERT_TRUE(controller.speedL(v, 3, 0, FrameType::Base).ok()); - { - std::unique_lock lock(mutex); - ASSERT_TRUE(cv.wait_for(lock, 1s, [&] { return forward_sent; })); - block_zero = true; - } - ASSERT_TRUE(controller.stop(3).ok()); - { - std::unique_lock lock(mutex); - ASSERT_TRUE(cv.wait_for(lock, 1s, [&] { return zero_entered; })); - } - v.vy = -.08; - ASSERT_TRUE(controller.speedL(v, 3, 0, FrameType::Base).ok()); - { - std::unique_lock lock(mutex); - release_zero = true; cv.notify_all(); - EXPECT_TRUE(cv.wait_for(lock, 1s, [&] { return reverse_sent; })); - } - EXPECT_TRUE(controller.busy()); - controller.shutdown(); -} -TEST(CartesianVelocityController, PublishesReferenceAfterSendAndKeepsCommandLimits) { - std::mutex mutex; - std::condition_variable cv; - bool entered = false, release = false; - auto planner = std::make_shared(); - CartesianVelocityController controller({}, planner, 1, - [](auto& q, auto& qd) { q = {0}; qd = {0}; return true; }, - [&](const JointVelocityCommand&, double) { - std::unique_lock lock(mutex); - if (!entered) { - entered = true; cv.notify_all(); - cv.wait_for(lock, 2s, [&] { return release; }); - } - return Result::success(); - }); - CartesianVelocity v; v.vy = -.08; - SpeedLOptions options; - options.acceleration = 3; - options.linear_jerk = 60; - options.continuous_linear_reversal = true; - options.capture_reference = true; - ASSERT_TRUE(controller.speedL(v, options, 0, FrameType::Tool).ok()); - { - std::unique_lock lock(mutex); - ASSERT_TRUE(cv.wait_for(lock, 1s, [&] { return entered; })); - EXPECT_FALSE(controller.getReference().valid); - release = true; cv.notify_all(); - } - const auto deadline = std::chrono::steady_clock::now() + 1s; - while (!controller.getReference().valid && std::chrono::steady_clock::now() < deadline) - std::this_thread::sleep_for(1ms); - const auto ref = controller.getReference(); - EXPECT_TRUE(ref.valid); - EXPECT_GT(ref.command_version, 0U); - EXPECT_DOUBLE_EQ(ref.tcp_pose_base.y, .5); - EXPECT_DOUBLE_EQ(ref.target_base.vx, -.08); - EXPECT_DOUBLE_EQ(planner->applied_jerk.load(), 60); - EXPECT_TRUE(planner->applied_reversal.load()); - controller.shutdown(); -} -TEST(CartesianVelocityController, RejectsInvalidMotionLimitsBeforeStarting) { - auto planner = std::make_shared(); - CartesianVelocityController controller({}, planner, 1, - [](auto&, auto&) { return false; }, - [](const auto&, double) { return Result::success(); }); - SpeedLOptions options; - options.linear_jerk = std::numeric_limits::quiet_NaN(); - EXPECT_FALSE(controller.speedL({}, options, 0, FrameType::Base).ok()); - options.linear_jerk = -1; - EXPECT_FALSE(controller.speedL({}, options, 0, FrameType::Base).ok()); - EXPECT_FALSE(controller.busy()); -} -} -} diff --git a/cmvr-es/algorithms/controllers/pbvs/include/pbvs_controller.h b/cmvr-es/algorithms/controllers/pbvs/include/pbvs_controller.h index 645ddd83..45cdedfa 100644 --- a/cmvr-es/algorithms/controllers/pbvs/include/pbvs_controller.h +++ b/cmvr-es/algorithms/controllers/pbvs/include/pbvs_controller.h @@ -9,7 +9,8 @@ #include "common/types/arm/arm_types.h" -namespace cmvr { +namespace cmvr +{ /** * @brief 基于相对 3D 位姿的 PBVS 控制器。 @@ -44,7 +45,6 @@ namespace cmvr { * 姿态误差: * * R_err = R_des * R_cur^T - * * e_R = Log(R_err)^vee * * 控制律: @@ -60,9 +60,11 @@ namespace cmvr { * - IK * - speedL 下发 */ -class PbvsController { +class PbvsController +{ public: - enum class ComputeStatus { + enum class ComputeStatus + { OK = 0, TARGET_NOT_SET, INVALID_INPUT, @@ -71,36 +73,25 @@ public: INVALID_CURRENT_POSE }; - struct Output { + struct Output + { // 当前位置误差,单位 m - Eigen::Vector3d position_error_G{ - Eigen::Vector3d::Zero() - }; + Eigen::Vector3d position_error_G{Eigen::Vector3d::Zero()}; // 当前姿态误差 rotation-vector,单位 rad - Eigen::Vector3d rotation_error_G{ - Eigen::Vector3d::Zero() - }; + Eigen::Vector3d rotation_error_G{Eigen::Vector3d::Zero()}; // PBVS 计算得到的原始线速度,单位 m/s - Eigen::Vector3d raw_linear_velocity_G{ - Eigen::Vector3d::Zero() - }; + Eigen::Vector3d raw_linear_velocity_G{Eigen::Vector3d::Zero()}; // PBVS 计算得到的原始角速度,单位 rad/s - Eigen::Vector3d raw_angular_velocity_G{ - Eigen::Vector3d::Zero() - }; + Eigen::Vector3d raw_angular_velocity_G{Eigen::Vector3d::Zero()}; // 经过限幅 / 加速度 / 滤波后的线速度 - Eigen::Vector3d linear_velocity_G{ - Eigen::Vector3d::Zero() - }; + Eigen::Vector3d linear_velocity_G{Eigen::Vector3d::Zero()}; // 经过限幅 / 加速度 / 滤波后的角速度 - Eigen::Vector3d angular_velocity_G{ - Eigen::Vector3d::Zero() - }; + Eigen::Vector3d angular_velocity_G{Eigen::Vector3d::Zero()}; // 可直接取出的 CartesianVelocity。 // @@ -111,7 +102,6 @@ public: bool position_reached{false}; bool orientation_reached{false}; bool reached{false}; - bool valid{false}; }; @@ -123,8 +113,7 @@ public: * * @param T_G_P_des TCP(P) 相对于 ScreenTag(G) 的目标位姿。 */ - bool setTargetPose( - const Eigen::Matrix4d& T_G_P_des); + bool setTargetPose(const Eigen::Matrix4d& T_G_P_des); /** * @brief 使用目标位置 + 目标姿态设置期望位姿。 @@ -136,16 +125,12 @@ public: /** * @brief 当前是否已经设置有效目标。 */ - bool hasTarget() const { - return target_valid_; - } + bool hasTarget() const { return target_valid_; } /** * @brief 获取目标位姿。 */ - const Eigen::Matrix4d& targetPose() const { - return T_G_P_des_; - } + const Eigen::Matrix4d& targetPose() const { return T_G_P_des_; } /** * @brief 根据当前 TCP 位姿计算 PBVS 速度命令。 @@ -176,16 +161,14 @@ public: * * x/y/z 分别控制。 */ - void setPositionGain( - const Eigen::Vector3d& kp); + void setPositionGain(const Eigen::Vector3d& kp); /** * @brief 设置姿态比例增益。 * * rx/ry/rz 分别控制。 */ - void setRotationGain( - const Eigen::Vector3d& kr); + void setRotationGain(const Eigen::Vector3d& kr); /** * @brief 设置六维速度上限。 @@ -195,8 +178,7 @@ public: * 前三维 m/s; * 后三维 rad/s。 */ - void setVelocityLimit6( - const std::array& vmax6); + void setVelocityLimit6(const std::array& vmax6); /** * @brief 设置六维加速度限制。 @@ -206,8 +188,7 @@ public: * * <= 0 表示对应维度不限制。 */ - void setAccelerationLimit6( - const std::array& amax6); + void setAccelerationLimit6(const std::array& amax6); /** * @brief 设置六维误差阈值。 @@ -217,21 +198,16 @@ public: * 前三维 m; * 后三维 rad。 */ - void setTolerance6( - const std::array& tolerance6); + void setTolerance6(const std::array& tolerance6); /** * @brief 设置一阶低通 alpha。 * - * alpha = 1: - * 不滤波。 + * alpha = 1:不滤波。 * * 0 < alpha < 1: * - * cmd = - * alpha * current - * + - * (1-alpha) * previous + * cmd = alpha * current + (1 - alpha) * previous */ void setTwistFilterAlpha(double alpha); @@ -244,8 +220,7 @@ public: * * enabled[5] = false; */ - void setAxisEnabled( - const std::array& enabled); + void setAxisEnabled(const std::array& enabled); /** * @brief 清空速度历史,但保留目标。 @@ -257,70 +232,42 @@ public: */ void reset(); - ComputeStatus lastComputeStatus() const { - return last_compute_status_; - } + ComputeStatus lastComputeStatus() const { return last_compute_status_; } - static const char* statusToString( - ComputeStatus status); + static const char* statusToString(ComputeStatus status); - const Eigen::Vector3d& lastPositionError() const { - return last_position_error_G_; - } + const Eigen::Vector3d& lastPositionError() const { return last_position_error_G_; } + const Eigen::Vector3d& lastRotationError() const { return last_rotation_error_G_; } - const Eigen::Vector3d& lastRotationError() const { - return last_rotation_error_G_; - } + const Eigen::Vector3d& positionGain() const { return kp_position_; } + const Eigen::Vector3d& rotationGain() const { return kp_rotation_; } - const Eigen::Vector3d& positionGain() const { - return kp_position_; - } + const std::array& velocityLimit6() const { return vmax6_; } + const std::array& accelerationLimit6() const { return amax6_; } + const std::array& tolerance6() const { return tolerance6_; } - const Eigen::Vector3d& rotationGain() const { - return kp_rotation_; - } + double twistFilterAlpha() const { return twist_lpf_alpha_; } - const std::array& velocityLimit6() const { - return vmax6_; - } - - const std::array& accelerationLimit6() const { - return amax6_; - } - - const std::array& tolerance6() const { - return tolerance6_; - } - - double twistFilterAlpha() const { - return twist_lpf_alpha_; - } - - const Eigen::Matrix& - lastTwistCommandG() const { + const Eigen::Matrix& lastTwistCommandG() const + { return last_twist_cmd_G_; } - bool lastReached() const { - return last_reached_; - } + bool lastReached() const { return last_reached_; } private: - static bool isFiniteTransform( - const Eigen::Matrix4d& T); + static bool isFiniteTransform(const Eigen::Matrix4d& T); static bool hasValidBottomRow( const Eigen::Matrix4d& T, double tolerance = 1e-6); - static bool isValidTransform( - const Eigen::Matrix4d& T); + static bool isValidTransform(const Eigen::Matrix4d& T); /** * @brief 将可能有微小数值误差的旋转矩阵投影到 SO(3)。 */ - static Eigen::Matrix3d projectToSO3( - const Eigen::Matrix3d& R); + static Eigen::Matrix3d projectToSO3(const Eigen::Matrix3d& R); /** * @brief 计算空间旋转误差,在 G frame 表达。 @@ -333,43 +280,27 @@ private: const Eigen::Matrix3d& R_des, const Eigen::Matrix3d& R_cur); - static double clampValue( - double value, - double lower, - double upper); + static double clampValue(double value, double lower, double upper); - static device::CartesianVelocity - toCartesianVelocity( + static device::CartesianVelocity toCartesianVelocity( const Eigen::Matrix& twist); private: // ---------------- target ---------------- - Eigen::Matrix4d T_G_P_des_{ - Eigen::Matrix4d::Identity() - }; - + Eigen::Matrix4d T_G_P_des_{Eigen::Matrix4d::Identity()}; bool target_valid_{false}; // ---------------- gains ---------------- - Eigen::Vector3d kp_position_{ - 2.0, - 2.0, - 1.5 - }; - - Eigen::Vector3d kp_rotation_{ - 1.5, - 1.5, - 1.5 - }; + Eigen::Vector3d kp_position_{2.0, 2.0, 1.5}; + Eigen::Vector3d kp_rotation_{1.5, 1.5, 1.5}; // ---------------- velocity limits ---------------- - // // [vx vy vz wx wy wz] // + std::array vmax6_{{ 0.10, 0.10, @@ -393,13 +324,12 @@ private: // ---------------- tolerance ---------------- std::array tolerance6_{{ - 0.0015, // x 1.5 mm - 0.0015, // y 1.5 mm - 0.0020, // z 2.0 mm - - 0.05, // rx ~2.9 deg - 0.05, // ry - 0.05 // rz + 0.0015, // x 1.5 mm + 0.0015, // y 1.5 mm + 0.0020, // z 2.0 mm + 0.05, // rx ~2.9 deg + 0.05, // ry + 0.05 // rz }}; // ---------------- axis enable ---------------- @@ -419,33 +349,24 @@ private: // ---------------- command history ---------------- - Eigen::Matrix - previous_twist_cmd_G_{ - Eigen::Matrix::Zero() - }; + Eigen::Matrix previous_twist_cmd_G_{ + Eigen::Matrix::Zero() + }; bool has_previous_twist_{false}; // ---------------- last output ---------------- - Eigen::Vector3d last_position_error_G_{ - Eigen::Vector3d::Zero() - }; + Eigen::Vector3d last_position_error_G_{Eigen::Vector3d::Zero()}; + Eigen::Vector3d last_rotation_error_G_{Eigen::Vector3d::Zero()}; - Eigen::Vector3d last_rotation_error_G_{ - Eigen::Vector3d::Zero() + Eigen::Matrix last_twist_cmd_G_{ + Eigen::Matrix::Zero() }; - Eigen::Matrix - last_twist_cmd_G_{ - Eigen::Matrix::Zero() - }; - bool last_reached_{false}; - ComputeStatus last_compute_status_{ - ComputeStatus::TARGET_NOT_SET - }; + ComputeStatus last_compute_status_{ComputeStatus::TARGET_NOT_SET}; }; } // namespace cmvr diff --git a/cmvr-es/algorithms/controllers/pbvs/src/pbvs_controller.cpp b/cmvr-es/algorithms/controllers/pbvs/src/pbvs_controller.cpp index fedd1f87..f83cc787 100644 --- a/cmvr-es/algorithms/controllers/pbvs/src/pbvs_controller.cpp +++ b/cmvr-es/algorithms/controllers/pbvs/src/pbvs_controller.cpp @@ -6,597 +6,478 @@ #include #include -namespace cmvr { - -PbvsController::PbvsController() +namespace cmvr { - resetTwistCommandState(); -} - -bool PbvsController::setTargetPose( - const Eigen::Matrix4d& T_G_P_des) -{ - if (!isValidTransform(T_G_P_des)) { - target_valid_ = false; - last_compute_status_ = - ComputeStatus::INVALID_TARGET; - return false; + PbvsController::PbvsController() + { + resetTwistCommandState(); } - T_G_P_des_ = T_G_P_des; - - // - // 视觉位姿可能有微小数值误差。 - // 强制把 rotation 投影到 SO(3)。 - // - T_G_P_des_.block<3, 3>(0, 0) = - projectToSO3( - T_G_P_des.block<3, 3>(0, 0)); - - target_valid_ = true; - last_compute_status_ = - ComputeStatus::OK; - - return true; -} - -bool PbvsController::setTargetPose( - const Eigen::Vector3d& position_G, - const Eigen::Matrix3d& rotation_G_P) -{ - if (!position_G.allFinite() || - !rotation_G_P.allFinite()) { - - target_valid_ = false; - last_compute_status_ = - ComputeStatus::INVALID_TARGET; - - return false; - } - - Eigen::Matrix4d T = - Eigen::Matrix4d::Identity(); - - T.block<3, 3>(0, 0) = - projectToSO3(rotation_G_P); - - T.block<3, 1>(0, 3) = - position_G; - - return setTargetPose(T); -} - -bool PbvsController::compute( - const Eigen::Matrix4d& T_G_P_cur, - const double dt, - Output& output) -{ - output = Output{}; - - last_reached_ = false; - last_position_error_G_.setZero(); - last_rotation_error_G_.setZero(); - last_twist_cmd_G_.setZero(); - - if (!target_valid_) { - last_compute_status_ = - ComputeStatus::TARGET_NOT_SET; - - return false; - } - - if (!std::isfinite(dt) || - dt <= 0.0) { - - last_compute_status_ = - ComputeStatus::INVALID_DT; - - return false; - } - - if (!isValidTransform(T_G_P_cur)) { - last_compute_status_ = - ComputeStatus::INVALID_CURRENT_POSE; - - return false; - } - - // ===================================================== - // 1. Current pose - // ===================================================== - - const Eigen::Vector3d p_cur_G = - T_G_P_cur.block<3, 1>(0, 3); - - const Eigen::Matrix3d R_cur_G_P = - projectToSO3( - T_G_P_cur.block<3, 3>(0, 0)); - - // ===================================================== - // 2. Desired pose - // ===================================================== - - const Eigen::Vector3d p_des_G = - T_G_P_des_.block<3, 1>(0, 3); - - const Eigen::Matrix3d R_des_G_P = - T_G_P_des_.block<3, 3>(0, 0); - - // ===================================================== - // 3. Position error - // - // e_p = p_des - p_cur - // - // expressed in G frame. - // ===================================================== - - Eigen::Vector3d e_pos_G = - p_des_G - - p_cur_G; - - // ===================================================== - // 4. Rotation error - // - // R_err = - // R_des * R_cur^T - // - // e_R = - // Log(R_err)^vee - // - // e_R is also expressed in G frame. - // ===================================================== - - Eigen::Vector3d e_rot_G = - rotationError( - R_des_G_P, - R_cur_G_P); - - if (!e_pos_G.allFinite() || - !e_rot_G.allFinite()) { - - last_compute_status_ = - ComputeStatus::INVALID_INPUT; - - return false; - } - - // ===================================================== - // 5. Disabled axes - // ===================================================== - - for (int i = 0; i < 3; ++i) { - if (!axis_enabled_[i]) { - e_pos_G[i] = 0.0; + bool PbvsController::setTargetPose(const Eigen::Matrix4d& T_G_P_des) + { + if (!isValidTransform(T_G_P_des)) + { + target_valid_ = false; + last_compute_status_ = ComputeStatus::INVALID_TARGET; + return false; } - if (!axis_enabled_[i + 3]) { - e_rot_G[i] = 0.0; - } - } + T_G_P_des_ = T_G_P_des; - last_position_error_G_ = - e_pos_G; + // + // 视觉位姿可能有微小数值误差。 + // 强制把 rotation 投影到 SO(3)。 + // + T_G_P_des_.block<3, 3>(0, 0) = projectToSO3(T_G_P_des.block<3, 3>(0, 0)); - last_rotation_error_G_ = - e_rot_G; - - output.position_error_G = - e_pos_G; - - output.rotation_error_G = - e_rot_G; - - // ===================================================== - // 6. Reached check - // ===================================================== - - bool position_reached = true; - bool orientation_reached = true; - - for (int i = 0; i < 3; ++i) { - - if (axis_enabled_[i] && - std::abs(e_pos_G[i]) > - tolerance6_[i]) { - - position_reached = false; - } - - if (axis_enabled_[i + 3] && - std::abs(e_rot_G[i]) > - tolerance6_[i + 3]) { - - orientation_reached = false; - } - } - - const bool reached = - position_reached && - orientation_reached; - - output.position_reached = - position_reached; - - output.orientation_reached = - orientation_reached; - - output.reached = - reached; - - last_reached_ = - reached; - - // ===================================================== - // 7. PBVS P control - // - // v = Kp * e_pos - // - // w = Kr * e_rot - // ===================================================== - - Eigen::Matrix - twist_raw_G = - Eigen::Matrix::Zero(); - - twist_raw_G.head<3>() = - kp_position_.cwiseProduct( - e_pos_G); - - twist_raw_G.tail<3>() = - kp_rotation_.cwiseProduct( - e_rot_G); - - // ===================================================== - // 8. Dead zone - // - // 某个轴已经进入误差阈值,则这个轴不再主动运动。 - // ===================================================== - - for (int i = 0; i < 6; ++i) { - - if (!axis_enabled_[i]) { - twist_raw_G[i] = 0.0; - continue; - } - - const double error_value = - i < 3 - ? e_pos_G[i] - : e_rot_G[i - 3]; - - if (std::abs(error_value) <= - tolerance6_[i]) { - - twist_raw_G[i] = 0.0; - } - } - - output.raw_linear_velocity_G = - twist_raw_G.head<3>(); - - output.raw_angular_velocity_G = - twist_raw_G.tail<3>(); - - // ===================================================== - // 9. Velocity limits - // ===================================================== - - Eigen::Matrix - twist_vel_limited = - twist_raw_G; - - for (int i = 0; i < 6; ++i) { - - const double vmax = - vmax6_[i]; - - if (!std::isfinite(vmax) || - vmax <= 0.0) { - - twist_vel_limited[i] = 0.0; - continue; - } - - twist_vel_limited[i] = - clampValue( - twist_vel_limited[i], - -vmax, - vmax); - } - - // ===================================================== - // 10. Reached: - // - // 进入完整目标阈值后直接输出 0。 - // - // 上层可以随后调用 RobotArm::stopL()。 - // ===================================================== - - if (reached) { - - previous_twist_cmd_G_.setZero(); - has_previous_twist_ = true; - - last_twist_cmd_G_.setZero(); - - output.linear_velocity_G.setZero(); - output.angular_velocity_G.setZero(); - - output.twist_G = - device::CartesianVelocity{}; - - output.valid = true; - - last_compute_status_ = - ComputeStatus::OK; + target_valid_ = true; + last_compute_status_ = ComputeStatus::OK; return true; } - // ===================================================== - // 11. Acceleration limits - // ===================================================== + bool PbvsController::setTargetPose(const Eigen::Vector3d& position_G, const Eigen::Matrix3d& rotation_G_P) + { + if (!position_G.allFinite() || !rotation_G_P.allFinite()) + { + target_valid_ = false; + last_compute_status_ = ComputeStatus::INVALID_TARGET; - Eigen::Matrix - twist_acc_limited; + return false; + } - if (!has_previous_twist_) { + Eigen::Matrix4d T = Eigen::Matrix4d::Identity(); + T.block<3, 3>(0, 0) = projectToSO3(rotation_G_P); + + T.block<3, 1>(0, 3) = position_G; + + return setTargetPose(T); + } + + bool PbvsController::compute(const Eigen::Matrix4d& T_G_P_cur, const double dt, Output& output) + { + output = Output{}; + + last_reached_ = false; + last_position_error_G_.setZero(); + last_rotation_error_G_.setZero(); + last_twist_cmd_G_.setZero(); + + if (!target_valid_) + { + last_compute_status_ = ComputeStatus::TARGET_NOT_SET; + + return false; + } + + if (!std::isfinite(dt) || dt <= 0.0) + { + last_compute_status_ = ComputeStatus::INVALID_DT; + + return false; + } + + if (!isValidTransform(T_G_P_cur)) + { + last_compute_status_ = ComputeStatus::INVALID_CURRENT_POSE; + + return false; + } + + // ===================================================== + // 1. Current pose + // ===================================================== + + const Eigen::Vector3d p_cur_G = T_G_P_cur.block<3, 1>(0, 3); + + const Eigen::Matrix3d R_cur_G_P = projectToSO3(T_G_P_cur.block<3, 3>(0, 0)); + + // ===================================================== + // 2. Desired pose + // ===================================================== + + const Eigen::Vector3d p_des_G = T_G_P_des_.block<3, 1>(0, 3); + + const Eigen::Matrix3d R_des_G_P = T_G_P_des_.block<3, 3>(0, 0); + + // ===================================================== + // 3. Position error + // + // e_p = p_des - p_cur + // + // expressed in G frame. + // ===================================================== + + Eigen::Vector3d e_pos_G = p_des_G - p_cur_G; + + // ===================================================== + // 4. Rotation error + // + // R_err = + // R_des * R_cur^T + // + // e_R = + // Log(R_err)^vee + // + // e_R is also expressed in G frame. + // ===================================================== + + Eigen::Vector3d e_rot_G = rotationError(R_des_G_P, R_cur_G_P); + + if (!e_pos_G.allFinite() || !e_rot_G.allFinite()) + { + last_compute_status_ = ComputeStatus::INVALID_INPUT; + + return false; + } + + // ===================================================== + // 5. Disabled axes + // ===================================================== + + for (int i = 0; i < 3; ++i) + { + if (!axis_enabled_[i]) + { + e_pos_G[i] = 0.0; + } + + if (!axis_enabled_[i + 3]) + { + e_rot_G[i] = 0.0; + } + } + + last_position_error_G_ = e_pos_G; + + last_rotation_error_G_ = e_rot_G; + + output.position_error_G = e_pos_G; + + output.rotation_error_G = e_rot_G; + + // ===================================================== + // 6. Reached check + // ===================================================== + + bool position_reached = true; + bool orientation_reached = true; + + for (int i = 0; i < 3; ++i) + { + if (axis_enabled_[i] && std::abs(e_pos_G[i]) > tolerance6_[i]) + { + position_reached = false; + } + + if (axis_enabled_[i + 3] && std::abs(e_rot_G[i]) > tolerance6_[i + 3]) + { + orientation_reached = false; + } + } + + const bool reached = position_reached && orientation_reached; + + output.position_reached = position_reached; + + output.orientation_reached = orientation_reached; + + output.reached = reached; + + last_reached_ = reached; + + // ===================================================== + // 7. PBVS P control + // + // v = Kp * e_pos + // + // w = Kr * e_rot + // ===================================================== + + Eigen::Matrix twist_raw_G = Eigen::Matrix::Zero(); + + twist_raw_G.head<3>() = kp_position_.cwiseProduct(e_pos_G); + + twist_raw_G.tail<3>() = kp_rotation_.cwiseProduct(e_rot_G); + + // ===================================================== + // 8. Dead zone + // + // 某个轴已经进入误差阈值,则这个轴不再主动运动。 + // ===================================================== + + for (int i = 0; i < 6; ++i) + { + if (!axis_enabled_[i]) + { + twist_raw_G[i] = 0.0; + continue; + } + + const double error_value = i < 3 ? e_pos_G[i] : e_rot_G[i - 3]; + + if (std::abs(error_value) <= tolerance6_[i]) + { + twist_raw_G[i] = 0.0; + } + } + + output.raw_linear_velocity_G = twist_raw_G.head<3>(); + + output.raw_angular_velocity_G = twist_raw_G.tail<3>(); + + // ===================================================== + // 9. Velocity limits + // ===================================================== + + Eigen::Matrix twist_vel_limited = twist_raw_G; + + for (int i = 0; i < 6; ++i) + { + const double vmax = vmax6_[i]; + + if (!std::isfinite(vmax) || vmax <= 0.0) + { + twist_vel_limited[i] = 0.0; + continue; + } + + twist_vel_limited[i] = clampValue(twist_vel_limited[i], -vmax, vmax); + } + + // ===================================================== + // 10. Reached: + // + // 进入完整目标阈值后直接输出 0。 + // + // 上层可以随后调用 RobotArm::stopL()。 + // ===================================================== + + if (reached) + { + previous_twist_cmd_G_.setZero(); + has_previous_twist_ = true; + + last_twist_cmd_G_.setZero(); + + output.linear_velocity_G.setZero(); + output.angular_velocity_G.setZero(); + + output.twist_G = device::CartesianVelocity{}; + + output.valid = true; + + last_compute_status_ = ComputeStatus::OK; + + return true; + } + + // ===================================================== + // 11. Acceleration limits + // ===================================================== + + Eigen::Matrix twist_acc_limited; + + if (!has_previous_twist_) + { + previous_twist_cmd_G_.setZero(); + has_previous_twist_ = true; + } + + twist_acc_limited = previous_twist_cmd_G_; + + for (int i = 0; i < 6; ++i) + { + if (!axis_enabled_[i]) + { + twist_acc_limited[i] = 0.0; + continue; + } + + const double amax = amax6_[i]; + + // <=0:不做加速度限制 + if (!std::isfinite(amax) || amax <= 0.0) + { + twist_acc_limited[i] = twist_vel_limited[i]; + + continue; + } + + const double dv_max = amax * dt; + + const double dv_des = twist_vel_limited[i] - previous_twist_cmd_G_[i]; + + const double dv = clampValue(dv_des, -dv_max, dv_max); + + twist_acc_limited[i] = previous_twist_cmd_G_[i] + dv; + } + + // ===================================================== + // 12. First-order LPF + // ===================================================== + + Eigen::Matrix twist_filtered = twist_acc_limited; + + const double alpha = std::clamp(twist_lpf_alpha_, 0.0, 1.0); + + if (alpha > 0.0 && alpha < 1.0) + { + twist_filtered = alpha * twist_acc_limited + (1.0 - alpha) * previous_twist_cmd_G_; + } + + // ===================================================== + // 13. Make sure disabled axis is zero + // ===================================================== + + for (int i = 0; i < 6; ++i) + { + if (!axis_enabled_[i]) + { + twist_filtered[i] = 0.0; + } + } + + // ===================================================== + // 14. Save state + // ===================================================== + + previous_twist_cmd_G_ = twist_filtered; + + last_twist_cmd_G_ = twist_filtered; + + // ===================================================== + // 15. Output + // ===================================================== + + output.linear_velocity_G = twist_filtered.head<3>(); + + output.angular_velocity_G = twist_filtered.tail<3>(); + + output.twist_G = toCartesianVelocity(twist_filtered); + + output.valid = true; + + last_compute_status_ = ComputeStatus::OK; + + return true; + } + + bool PbvsController::compute(const Eigen::Matrix4d& T_G_P_cur, const double dt, device::CartesianVelocity& twist_G_out) + { + Output output; + + if (!compute(T_G_P_cur, dt, output)) + { + twist_G_out = device::CartesianVelocity{}; + + return false; + } + + twist_G_out = output.twist_G; + + return true; + } + + void PbvsController::setPositionGain(const Eigen::Vector3d& kp) + { + for (int i = 0; i < 3; ++i) + { + if (std::isfinite(kp[i]) && kp[i] >= 0.0) + { + kp_position_[i] = kp[i]; + } + } + } + + void PbvsController::setRotationGain(const Eigen::Vector3d& kr) + { + for (int i = 0; i < 3; ++i) + { + if (std::isfinite(kr[i]) && kr[i] >= 0.0) + { + kp_rotation_[i] = kr[i]; + } + } + } + + void PbvsController::setVelocityLimit6(const std::array& vmax6) + { + for (int i = 0; i < 6; ++i) + { + if (std::isfinite(vmax6[i]) && vmax6[i] >= 0.0) + { + vmax6_[i] = vmax6[i]; + } + } + } + + void PbvsController::setAccelerationLimit6(const std::array& amax6) + { + for (int i = 0; i < 6; ++i) + { + if (std::isfinite(amax6[i])) + { + amax6_[i] = amax6[i]; + } + } + } + + void PbvsController::setTolerance6(const std::array& tolerance6) + { + for (int i = 0; i < 6; ++i) + { + if (std::isfinite(tolerance6[i]) && tolerance6[i] >= 0.0) + { + tolerance6_[i] = tolerance6[i]; + } + } + } + + void PbvsController::setTwistFilterAlpha(const double alpha) + { + if (!std::isfinite(alpha)) + { + return; + } + + twist_lpf_alpha_ = std::clamp(alpha, 0.0, 1.0); + } + + void PbvsController::setAxisEnabled(const std::array& enabled) + { + axis_enabled_ = enabled; + } + + void PbvsController::resetTwistCommandState() + { previous_twist_cmd_G_.setZero(); - has_previous_twist_ = true; + last_twist_cmd_G_.setZero(); + + has_previous_twist_ = false; } - twist_acc_limited = - previous_twist_cmd_G_; + void PbvsController::reset() + { + T_G_P_des_.setIdentity(); - for (int i = 0; i < 6; ++i) { + target_valid_ = false; - if (!axis_enabled_[i]) { - twist_acc_limited[i] = 0.0; - continue; - } + last_position_error_G_.setZero(); + last_rotation_error_G_.setZero(); - const double amax = - amax6_[i]; + last_reached_ = false; - // <=0:不做加速度限制 - if (!std::isfinite(amax) || - amax <= 0.0) { + resetTwistCommandState(); - twist_acc_limited[i] = - twist_vel_limited[i]; - - continue; - } - - const double dv_max = - amax * dt; - - const double dv_des = - twist_vel_limited[i] - - - previous_twist_cmd_G_[i]; - - const double dv = - clampValue( - dv_des, - -dv_max, - dv_max); - - twist_acc_limited[i] = - previous_twist_cmd_G_[i] - + - dv; + last_compute_status_ = ComputeStatus::TARGET_NOT_SET; } - // ===================================================== - // 12. First-order LPF - // ===================================================== - - Eigen::Matrix - twist_filtered = - twist_acc_limited; - - const double alpha = - std::clamp( - twist_lpf_alpha_, - 0.0, - 1.0); - - if (alpha > 0.0 && - alpha < 1.0) { - - twist_filtered = - alpha * - twist_acc_limited - + - (1.0 - alpha) * - previous_twist_cmd_G_; - } - - // ===================================================== - // 13. Make sure disabled axis is zero - // ===================================================== - - for (int i = 0; i < 6; ++i) { - if (!axis_enabled_[i]) { - twist_filtered[i] = 0.0; - } - } - - // ===================================================== - // 14. Save state - // ===================================================== - - previous_twist_cmd_G_ = - twist_filtered; - - last_twist_cmd_G_ = - twist_filtered; - - // ===================================================== - // 15. Output - // ===================================================== - - output.linear_velocity_G = - twist_filtered.head<3>(); - - output.angular_velocity_G = - twist_filtered.tail<3>(); - - output.twist_G = - toCartesianVelocity( - twist_filtered); - - output.valid = true; - - last_compute_status_ = - ComputeStatus::OK; - - return true; -} - -bool PbvsController::compute( - const Eigen::Matrix4d& T_G_P_cur, - const double dt, - device::CartesianVelocity& twist_G_out) -{ - Output output; - - if (!compute( - T_G_P_cur, - dt, - output)) { - - twist_G_out = - device::CartesianVelocity{}; - - return false; - } - - twist_G_out = - output.twist_G; - - return true; -} - -void PbvsController::setPositionGain( - const Eigen::Vector3d& kp) -{ - for (int i = 0; i < 3; ++i) { - if (std::isfinite(kp[i]) && - kp[i] >= 0.0) { - - kp_position_[i] = - kp[i]; - } - } -} - -void PbvsController::setRotationGain( - const Eigen::Vector3d& kr) -{ - for (int i = 0; i < 3; ++i) { - if (std::isfinite(kr[i]) && - kr[i] >= 0.0) { - - kp_rotation_[i] = - kr[i]; - } - } -} - -void PbvsController::setVelocityLimit6( - const std::array& vmax6) -{ - for (int i = 0; i < 6; ++i) { - - if (std::isfinite(vmax6[i]) && - vmax6[i] >= 0.0) { - - vmax6_[i] = - vmax6[i]; - } - } -} - -void PbvsController::setAccelerationLimit6( - const std::array& amax6) -{ - for (int i = 0; i < 6; ++i) { - - if (std::isfinite(amax6[i])) { - amax6_[i] = - amax6[i]; - } - } -} - -void PbvsController::setTolerance6( - const std::array& tolerance6) -{ - for (int i = 0; i < 6; ++i) { - - if (std::isfinite(tolerance6[i]) && - tolerance6[i] >= 0.0) { - - tolerance6_[i] = - tolerance6[i]; - } - } -} - -void PbvsController::setTwistFilterAlpha( - const double alpha) -{ - if (!std::isfinite(alpha)) { - return; - } - - twist_lpf_alpha_ = - std::clamp( - alpha, - 0.0, - 1.0); -} - -void PbvsController::setAxisEnabled( - const std::array& enabled) -{ - axis_enabled_ = - enabled; -} - -void PbvsController::resetTwistCommandState() -{ - previous_twist_cmd_G_.setZero(); - last_twist_cmd_G_.setZero(); - - has_previous_twist_ = false; -} - -void PbvsController::reset() -{ - T_G_P_des_.setIdentity(); - - target_valid_ = false; - - last_position_error_G_.setZero(); - last_rotation_error_G_.setZero(); - - last_reached_ = false; - - resetTwistCommandState(); - - last_compute_status_ = - ComputeStatus::TARGET_NOT_SET; -} - -const char* PbvsController::statusToString( - const ComputeStatus status) -{ - switch (status) { - + const char* PbvsController::statusToString(const ComputeStatus status) + { + switch (status) + { case ComputeStatus::OK: return "ok"; @@ -617,158 +498,121 @@ const char* PbvsController::statusToString( default: return "unknown"; - } -} - -bool PbvsController::isFiniteTransform( - const Eigen::Matrix4d& T) -{ - return T.allFinite(); -} - -bool PbvsController::hasValidBottomRow( - const Eigen::Matrix4d& T, - const double tolerance) -{ - return - std::abs(T(3, 0)) <= tolerance && - std::abs(T(3, 1)) <= tolerance && - std::abs(T(3, 2)) <= tolerance && - std::abs(T(3, 3) - 1.0) <= tolerance; -} - -bool PbvsController::isValidTransform( - const Eigen::Matrix4d& T) -{ - if (!isFiniteTransform(T)) { - return false; + } } - if (!hasValidBottomRow(T)) { - return false; + bool PbvsController::isFiniteTransform(const Eigen::Matrix4d& T) + { + return T.allFinite(); } - return true; -} - -Eigen::Matrix3d PbvsController::projectToSO3( - const Eigen::Matrix3d& R) -{ - if (!R.allFinite()) { - return Eigen::Matrix3d::Identity(); + bool PbvsController::hasValidBottomRow(const Eigen::Matrix4d& T, const double tolerance) + { + return std::abs(T(3, 0)) <= tolerance && std::abs(T(3, 1)) <= tolerance && + std::abs(T(3, 2)) <= tolerance && std::abs(T(3, 3) - 1.0) <= tolerance; } - Eigen::JacobiSVD svd( - R, - Eigen::ComputeFullU | - Eigen::ComputeFullV); + bool PbvsController::isValidTransform(const Eigen::Matrix4d& T) + { + if (!isFiniteTransform(T)) + { + return false; + } - Eigen::Matrix3d U = - svd.matrixU(); + if (!hasValidBottomRow(T)) + { + return false; + } - const Eigen::Matrix3d V = - svd.matrixV(); - - Eigen::Matrix3d R_projected = - U * V.transpose(); - - // - // 确保 det = +1,而不是 reflection。 - // - if (R_projected.determinant() < 0.0) { - - U.col(2) *= -1.0; - - R_projected = - U * V.transpose(); + return true; } - return R_projected; -} + Eigen::Matrix3d PbvsController::projectToSO3(const Eigen::Matrix3d& R) + { + if (!R.allFinite()) + { + return Eigen::Matrix3d::Identity(); + } -Eigen::Vector3d PbvsController::rotationError( - const Eigen::Matrix3d& R_des, - const Eigen::Matrix3d& R_cur) -{ - const Eigen::Matrix3d R_d = - projectToSO3(R_des); + Eigen::JacobiSVD svd(R, Eigen::ComputeFullU | Eigen::ComputeFullV); - const Eigen::Matrix3d R_c = - projectToSO3(R_cur); + Eigen::Matrix3d U = svd.matrixU(); - // - // 空间旋转误差,在 G frame 表达。 - // - // 当前为 I,目标绕 +Z 旋转 theta: - // - // R_err = R_des - // - // 得到 +theta Z, - // 因此角速度方向正确。 - // - const Eigen::Matrix3d R_err = - R_d * - R_c.transpose(); + const Eigen::Matrix3d V = svd.matrixV(); - Eigen::AngleAxisd aa( - R_err); + Eigen::Matrix3d R_projected = U * V.transpose(); - const double angle = - aa.angle(); + // + // 确保 det = +1,而不是 reflection。 + // + if (R_projected.determinant() < 0.0) + { + U.col(2) *= -1.0; - if (!std::isfinite(angle) || - std::abs(angle) <= 1e-12) { + R_projected = U * V.transpose(); + } - return Eigen::Vector3d::Zero(); + return R_projected; } - const Eigen::Vector3d axis = - aa.axis(); + Eigen::Vector3d PbvsController::rotationError(const Eigen::Matrix3d& R_des, const Eigen::Matrix3d& R_cur) + { + const Eigen::Matrix3d R_d = projectToSO3(R_des); - if (!axis.allFinite()) { - return Eigen::Vector3d::Zero(); + const Eigen::Matrix3d R_c = projectToSO3(R_cur); + + // + // 空间旋转误差,在 G frame 表达。 + // + // 当前为 I,目标绕 +Z 旋转 theta: + // + // R_err = R_des + // + // 得到 +theta Z, + // 因此角速度方向正确。 + // + const Eigen::Matrix3d R_err = R_d * R_c.transpose(); + + Eigen::AngleAxisd aa(R_err); + + const double angle = aa.angle(); + + if (!std::isfinite(angle) || std::abs(angle) <= 1e-12) + { + return Eigen::Vector3d::Zero(); + } + + const Eigen::Vector3d axis = aa.axis(); + + if (!axis.allFinite()) + { + return Eigen::Vector3d::Zero(); + } + + return axis * angle; } - return axis * angle; -} + double PbvsController::clampValue(const double value, const double lower, const double upper) + { + return std::max(lower, std::min(value, upper)); + } -double PbvsController::clampValue( - const double value, - const double lower, - const double upper) -{ - return std::max( - lower, - std::min( - value, - upper)); -} + device::CartesianVelocity PbvsController::toCartesianVelocity(const Eigen::Matrix& twist) + { + device::CartesianVelocity velocity; -device::CartesianVelocity -PbvsController::toCartesianVelocity( - const Eigen::Matrix& twist) -{ - device::CartesianVelocity velocity; + velocity.vx = twist[0]; - velocity.vx = - twist[0]; + velocity.vy = twist[1]; - velocity.vy = - twist[1]; + velocity.vz = twist[2]; - velocity.vz = - twist[2]; + velocity.wx = twist[3]; - velocity.wx = - twist[3]; + velocity.wy = twist[4]; - velocity.wy = - twist[4]; + velocity.wz = twist[5]; - velocity.wz = - twist[5]; - - return velocity; -} - -} // namespace cmvr \ No newline at end of file + return velocity; + } +} // namespace cmvr diff --git a/cmvr-es/algorithms/kinematics/ik_solver/CMakeLists.txt b/cmvr-es/algorithms/kinematics/ik_solver/CMakeLists.txt index 1ade9e29..2f2488c2 100644 --- a/cmvr-es/algorithms/kinematics/ik_solver/CMakeLists.txt +++ b/cmvr-es/algorithms/kinematics/ik_solver/CMakeLists.txt @@ -14,6 +14,7 @@ add_library(ik_solver SHARED target_include_directories(ik_solver PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) target_link_libraries(ik_solver PUBLIC + cmvr_es::environment osqp OsqpEigen pinocchio_default diff --git a/cmvr-es/algorithms/kinematics/ik_solver/common/include/ik_solver.h b/cmvr-es/algorithms/kinematics/ik_solver/common/include/ik_solver.h index bc6b0660..f8c422a8 100644 --- a/cmvr-es/algorithms/kinematics/ik_solver/common/include/ik_solver.h +++ b/cmvr-es/algorithms/kinematics/ik_solver/common/include/ik_solver.h @@ -6,12 +6,12 @@ #include #include #include -#include +#include #include +#include "environment/include/robot_model.h" +#include "algorithms/kinematics/ik_solver/common/include/urdf_parser.h" namespace cmvr { - class UrdfParser; - class IKSolver { public: /** @@ -24,12 +24,12 @@ namespace cmvr { const std::string& base_frame_name, const std::string& tip_frame_name); /** - * @brief 构造时按外部解析器初始化链路缓存。 - * @param parser 已加载模型的 URDF 解析器。 + * @brief 构造时按已加载的机器人模型初始化链路缓存。 + * @param model 已加载运动学的机器人模型。 * @param base_frame_name 链路基座 frame 名称。 * @param tip_frame_name 链路末端 frame 名称。 */ - IKSolver(std::shared_ptr parser, + IKSolver(const RobotModel& model, const std::string& base_frame_name, const std::string& tip_frame_name); virtual ~IKSolver()=default; @@ -86,6 +86,9 @@ namespace cmvr { */ bool getChainJointNames(std::vector& names) const; + // Shares the immutable URDF resources; metadata describes this chain. + RobotModel getRobotModel() const; + protected: /** @@ -100,21 +103,22 @@ namespace cmvr { const std::string& tip_frame_name); /** - * @brief 使用外部 UrdfParser 初始化链路信息缓存(关节限位/关节名)。 - * @param parser 已加载模型的 URDF 解析器。 + * @brief 使用 RobotModel 初始化链路信息缓存(关节限位/关节名)。 + * @param model 已加载运动学的机器人模型。 * @param base_frame_name 链路基座 frame 名称。 * @param tip_frame_name 链路末端 frame 名称。 * @return 成功返回 true,失败返回 false。 */ - bool initUrdfChain(const std::shared_ptr& parser, + bool initUrdfChain(const RobotModel& model, const std::string& base_frame_name, const std::string& tip_frame_name); // 上次调用ik 时计算的结果 std::vector cur_joints_angle_{}; - // URDF 解析器(用于统一管理链路限位/关节名)。 - std::shared_ptr urdf_parser_{}; + // 共享只读模型;链路信息在初始化时提取一次。 + RobotModel robot_model_; + UrdfParser::ChainInfo chain_info_; // 当前缓存链路的基座 frame 名称。 std::string chain_base_frame_name_{}; @@ -131,9 +135,6 @@ namespace cmvr { // 当前缓存链路关节速度上限(rad/s, 绝对值)。 Eigen::VectorXd joint_vel_limits_{}; - // 当前缓存链路关节名称(base->tip 顺序)。 - std::vector chain_joint_names_{}; - // 链路缓存是否有效。 bool urdf_chain_cached_{false}; diff --git a/cmvr-es/algorithms/kinematics/ik_solver/common/include/urdf_parser.h b/cmvr-es/algorithms/kinematics/ik_solver/common/include/urdf_parser.h index dea8ff81..34e6bd89 100644 --- a/cmvr-es/algorithms/kinematics/ik_solver/common/include/urdf_parser.h +++ b/cmvr-es/algorithms/kinematics/ik_solver/common/include/urdf_parser.h @@ -6,15 +6,14 @@ #include -#include +#include "environment/include/robot_model.h" namespace cmvr { /** - * @brief 基于 Pinocchio 的 URDF 解析工具类。 + * @brief 从已加载的 RobotModel 提取运动链信息。 * * 主要职责: - * - 加载 URDF 到 Pinocchio 模型 * - 提取 base->tip 链路信息 * - 输出链路 q/v 索引范围、关节顺序、位置/速度限位 */ @@ -64,39 +63,24 @@ public: std::vector joints; }; - /** - * @brief 加载 URDF 模型。 - * @param urdf_path URDF 文件路径。 - * @param error 可选错误信息输出。 - * @return 成功返回 true,失败返回 false。 - */ - bool loadModel(const std::string& urdf_path, std::string* error = nullptr); - /** * @brief 提取 base->tip 链路信息。 * * 实现方式:从 tip 的父关节向上回溯到 base 的父关节, * 再反转为 base->tip 顺序。 * + * @param robot_model 已加载运动学的机器人模型。 * @param base_frame_name 基坐标系 frame 名称。 * @param tip_frame_name 末端 frame 名称。 * @param out 输出链路信息。 * @param error 可选错误信息输出。 * @return 成功返回 true,失败返回 false。 */ - bool extractChain(const std::string& base_frame_name, - const std::string& tip_frame_name, - ChainInfo& out, - std::string* error = nullptr) const; - - /** @brief 获取已加载的 Pinocchio 模型。 */ - const pinocchio::Model& model() const { return model_; } - /** @brief 当前是否已成功加载模型。 */ - bool loaded() const { return loaded_; } - -private: - pinocchio::Model model_; - bool loaded_{false}; + static bool extractChain(const RobotModel& robot_model, + const std::string& base_frame_name, + const std::string& tip_frame_name, + ChainInfo& out, + std::string* error = nullptr); }; } // namespace cmvr diff --git a/cmvr-es/algorithms/kinematics/ik_solver/common/src/ik_solver.cpp b/cmvr-es/algorithms/kinematics/ik_solver/common/src/ik_solver.cpp index 35918db2..ddc2def9 100644 --- a/cmvr-es/algorithms/kinematics/ik_solver/common/src/ik_solver.cpp +++ b/cmvr-es/algorithms/kinematics/ik_solver/common/src/ik_solver.cpp @@ -5,6 +5,7 @@ #include "algorithms/kinematics/ik_solver/common/include/ik_solver.h" #include "algorithms/kinematics/ik_solver/common/include/urdf_parser.h" #include "common/base/logging/logger.h" +#include namespace cmvr { @@ -16,59 +17,59 @@ IKSolver::IKSolver(const std::string& urdf_path, } } -IKSolver::IKSolver(std::shared_ptr parser, +IKSolver::IKSolver(const RobotModel& model, const std::string& base_frame_name, const std::string& tip_frame_name) { - if (parser && !base_frame_name.empty() && !tip_frame_name.empty()) { - initUrdfChain(parser, base_frame_name, tip_frame_name); + if (model.hasKinematics() && !base_frame_name.empty() && !tip_frame_name.empty()) { + initUrdfChain(model, base_frame_name, tip_frame_name); } } bool IKSolver::initUrdfChain(const std::string& urdf_path, const std::string& base_frame_name, const std::string& tip_frame_name) { - auto parser = std::make_shared(); - std::string err; - if (!parser->loadModel(urdf_path, &err)) { - CMVR_LOG(ERROR) << "[IKSolver] Failed to load URDF: " << err; + RobotModel model; + if (!model.loadUrdf(urdf_path)) { return false; } - return initUrdfChain(parser, base_frame_name, tip_frame_name); + return initUrdfChain(model, base_frame_name, tip_frame_name); } -bool IKSolver::initUrdfChain(const std::shared_ptr& parser, +bool IKSolver::initUrdfChain(const RobotModel& source_model, const std::string& base_frame_name, const std::string& tip_frame_name) { - if (!parser) { - CMVR_LOG(ERROR) << "[IKSolver] initUrdfChain failed: parser is null"; - return false; - } - if (!parser->loaded()) { - CMVR_LOG(ERROR) << "[IKSolver] initUrdfChain failed: parser model not loaded"; - return false; - } - UrdfParser::ChainInfo chain_info; std::string err; - if (!parser->extractChain(base_frame_name, tip_frame_name, chain_info, &err)) { + if (!UrdfParser::extractChain(source_model, base_frame_name, tip_frame_name, chain_info, &err)) { CMVR_LOG(ERROR) << "[IKSolver] Failed to extract chain: " << err; return false; } - urdf_parser_ = parser; + auto model = source_model; + std::vector names; + std::vector limits; + names.reserve(chain_info.joints.size()); + limits.reserve(chain_info.joints.size()); + for (const auto& joint : chain_info.joints) { + const auto found = std::find(model.joint_names.begin(), model.joint_names.end(), joint.name); + if (found == model.joint_names.end() || model.joint_limits.size() != model.joint_names.size()) { + CMVR_LOG(ERROR) << "[IKSolver] Missing joint metadata for " << joint.name; + return false; + } + names.push_back(joint.name); + limits.push_back(model.joint_limits[std::distance(model.joint_names.begin(), found)]); + } + model.dof = names.size(); + model.joint_names = std::move(names); + model.joint_limits = std::move(limits); + chain_base_frame_name_ = base_frame_name; chain_tip_frame_name_ = tip_frame_name; - - chain_joint_names_.clear(); - joint_pos_lower_limits_ = chain_info.q_lower; joint_pos_upper_limits_ = chain_info.q_upper; joint_vel_limits_ = chain_info.v_limit; - chain_joint_names_.reserve(chain_info.joints.size()); - for (const auto& joint : chain_info.joints) { - chain_joint_names_.push_back(joint.name); - } - + chain_info_ = std::move(chain_info); + robot_model_ = std::move(model); urdf_chain_cached_ = true; return true; } @@ -92,11 +93,15 @@ bool IKSolver::getJointVelocityLimits(Eigen::VectorXd& limits) const { } bool IKSolver::getChainJointNames(std::vector& names) const { - if (!urdf_chain_cached_ || chain_joint_names_.empty()) { + if (!urdf_chain_cached_ || robot_model_.joint_names.empty()) { return false; } - names = chain_joint_names_; + names = robot_model_.joint_names; return true; } +RobotModel IKSolver::getRobotModel() const { + return robot_model_; +} + } // namespace cmvr diff --git a/cmvr-es/algorithms/kinematics/ik_solver/common/src/urdf_parser.cpp b/cmvr-es/algorithms/kinematics/ik_solver/common/src/urdf_parser.cpp index 41a3b494..1a7d94bf 100644 --- a/cmvr-es/algorithms/kinematics/ik_solver/common/src/urdf_parser.cpp +++ b/cmvr-es/algorithms/kinematics/ik_solver/common/src/urdf_parser.cpp @@ -3,37 +3,23 @@ #include "algorithms/kinematics/ik_solver/common/include/urdf_parser.h" #include - -#include +#include namespace cmvr { -bool UrdfParser::loadModel(const std::string& urdf_path, std::string* error) { - try { - // 使用 Pinocchio 官方 URDF 解析入口构建模型。 - pinocchio::urdf::buildModel(urdf_path, model_); - loaded_ = true; - return true; - } catch (const std::exception& e) { - loaded_ = false; - if (error) { - *error = e.what(); - } - return false; - } -} - -bool UrdfParser::extractChain(const std::string& base_frame_name, +bool UrdfParser::extractChain(const RobotModel& robot_model, + const std::string& base_frame_name, const std::string& tip_frame_name, ChainInfo& out, - std::string* error) const { + std::string* error) { // 1) 基础合法性检查。 - if (!loaded_) { + if (!robot_model.hasKinematics()) { if (error) { *error = "model not loaded"; } return false; } + const auto& model_ = robot_model.kinematics(); if (!model_.existFrame(base_frame_name)) { if (error) { *error = "base frame not found: " + base_frame_name; diff --git a/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_ik_base.h b/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_ik_base.h index d9b81444..3b04c01c 100644 --- a/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_ik_base.h +++ b/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_ik_base.h @@ -12,6 +12,7 @@ #include #include +#include #include #include @@ -39,9 +40,9 @@ public: const std::string& tcp_frame_name = std::string()); /** - * @brief 按外部 URDF 解析器构造。 + * @brief 按已加载的机器人模型构造。 */ - PinocchioIKBase(std::shared_ptr parser, + PinocchioIKBase(const RobotModel& model, const std::string& base_frame_name, const std::string& flange_frame_name, const std::string& tcp_frame_name = std::string()); @@ -92,7 +93,7 @@ public: bool is_tcp, Eigen::Matrix4d& pose_base, Eigen::MatrixXd& jacobian_base, - Eigen::Matrix3d& base_R_ee); + Eigen::Matrix3d& base_R_ee) const; bool computeTwistBaseAtQ(const std::vector& q_chain, const std::vector& qdot_chain, @@ -114,12 +115,27 @@ public: std::vector& qdot_out, double qdot_abs_max = std::numeric_limits::infinity()) const; + // Constrained solvers incorporate these bounds during velocity IK. Callers + // must not clip their solution afterward, which would change the TCP twist. + virtual bool supportsJointVelocityBounds() const { return false; } + virtual bool solveVelocityBase(const Eigen::MatrixXd&, + const Eigen::Matrix&, + const std::vector&, + std::vector& qdot_out, + const Eigen::VectorXd&, + const Eigen::VectorXd&, + double = std::numeric_limits::infinity()) const + { + qdot_out.clear(); + return false; + } + protected: /** * @brief 从父类缓存的 URDF 链信息初始化 Pinocchio 运行时对象与 frame 索引。 * * 调用前要求: - * - `urdf_parser_` 已有效并 loaded + * - `robot_model_` 已加载,链路信息已缓存 * - `chain_base_frame_name_` 与 `chain_tip_frame_name_` 已设置 * * @param chain_info_out 可选输出链信息(用于子类读取 q/v 区间)。 @@ -171,7 +187,7 @@ protected: static double disabledJointLimitAbs(); /** - * @brief 在当前 `model_` 上更新 FK 与 frame placement。 + * @brief 在共享模型上更新 FK 与 frame placement。 */ void updateKinematics(const Eigen::VectorXd& q_full); @@ -190,15 +206,19 @@ protected: std::string tcp_frame_name_; /** @brief Pinocchio 模型。 */ - pinocchio::Model model_; + const pinocchio::Model& model() const; /** @brief Pinocchio 运行时数据。 */ std::unique_ptr data_; + // Feedback and online planning reuse a separate workspace, serialized here. + // Never share mutable IK data_ with concurrent read-only queries. + std::unique_ptr query_data_; + mutable std::mutex query_mutex_; - /** @brief base frame 在 `model_.frames` 中的索引。 */ + /** @brief base frame 在 共享模型的 frames 中的索引。 */ pinocchio::FrameIndex base_frame_id_{(pinocchio::FrameIndex)(-1)}; - /** @brief flange frame 在 `model_.frames` 中的索引。 */ + /** @brief flange frame 在 共享模型的 frames 中的索引。 */ pinocchio::FrameIndex flange_frame_id_{(pinocchio::FrameIndex)(-1)}; - /** @brief tcp frame 在 `model_.frames` 中的索引。 */ + /** @brief tcp frame 在 共享模型的 frames 中的索引。 */ pinocchio::FrameIndex tcp_frame_id_{(pinocchio::FrameIndex)(-1)}; /** @brief 是否存在有效 TCP frame。 */ bool has_tcp_{false}; diff --git a/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_qp_ik_solver.h b/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_qp_ik_solver.h index ffce089f..c2546591 100644 --- a/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_qp_ik_solver.h +++ b/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_qp_ik_solver.h @@ -45,11 +45,31 @@ public: std::vector& qdot_out, double qdot_abs_max = std::numeric_limits::infinity()) const override; + bool supportsJointVelocityBounds() const override { return true; } + + // Additional bounds are intersected with the configured joint limits. + // Both vectors may be empty when the caller has no additional constraints. + bool solveVelocityBase(const Eigen::MatrixXd& jacobian_base, + const Eigen::Matrix& target_twist_base, + const std::vector& q_chain, + std::vector& qdot_out, + const Eigen::VectorXd& lower, + const Eigen::VectorXd& upper, + double qdot_abs_max = std::numeric_limits::infinity()) const override; + // Projects a secondary joint velocity into the Cartesian task null space. static Eigen::VectorXd projectJointLimitAvoidanceToNullspace( const Eigen::MatrixXd& jacobian_base, const Eigen::VectorXd& qdot_avoid); + // Largest feasible scale in [0, 1], allowing all redundant joint motions. + // Bounds must be finite. Failure returns false and resets scale to zero. + static bool computeVelocityScale(const Eigen::MatrixXd& jacobian_base, + const Eigen::Matrix& target_twist_base, + const Eigen::VectorXd& lower, + const Eigen::VectorXd& upper, + double& scale); + /// 如你有更严格的速度 / 加速度限位,可以覆盖默认值 void setVelocityLimits(const Eigen::VectorXd &qd_max); void setAccelerationLimits(const Eigen::VectorXd &qdd_max); diff --git a/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/src/pinocchio_dls_ik_solver.cpp b/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/src/pinocchio_dls_ik_solver.cpp index bccc0236..3829af19 100644 --- a/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/src/pinocchio_dls_ik_solver.cpp +++ b/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/src/pinocchio_dls_ik_solver.cpp @@ -153,7 +153,7 @@ bool PinocchioDlsIKSolver::init() { } { - Eigen::VectorXd q0 = pinocchio::neutral(model_); + Eigen::VectorXd q0 = pinocchio::neutral(model()); updateKinematics(q0); oM_base_cached_ = data_->oMf[base_frame_id_]; base_pose_cached_ = true; @@ -165,7 +165,7 @@ bool PinocchioDlsIKSolver::init() { CMVR_LOG(INFO) << "[PinocchioDlsIKSolver] Chain '" << chain_base_frame_name_ << "' -> '" << chain_tip_frame_name_ << "': q_start=" << chain_q_start_ << " q_dof=" << chain_q_dof_ << ", v_start=" << chain_v_start_ << " v_dof=" << chain_v_dof_ - << ", nq=" << model_.nq << " nv=" << model_.nv; + << ", nq=" << model().nq << " nv=" << model().nv; CMVR_LOG(INFO) << "[PinocchioDlsIKSolver] Chain joint position limits (rad):"; for (const auto& seg : chain_info.joints) { const int q_idx = seg.q_index; @@ -203,21 +203,21 @@ bool PinocchioDlsIKSolver::ik(const std::string& base_link, std::vector& joints_angle) { if (!initialized_) return false; if ((int)cur_joints_angle_.size() != chain_q_dof_) return false; - if (!model_.existFrame(base_link)) { + if (!model().existFrame(base_link)) { CMVR_LOG(ERROR) << "[PinocchioDlsIKSolver] base frame not found: " << base_link; return false; } - if (!model_.existFrame(ee_link)) { + if (!model().existFrame(ee_link)) { CMVR_LOG(ERROR) << "[PinocchioDlsIKSolver] ee frame not found: " << ee_link; return false; } - const pinocchio::FrameIndex base_frame_id = model_.getFrameId(base_link); - const pinocchio::FrameIndex ee_frame_id = model_.getFrameId(ee_link); + const pinocchio::FrameIndex base_frame_id = model().getFrameId(base_link); + const pinocchio::FrameIndex ee_frame_id = model().getFrameId(ee_link); - const pinocchio::JointIndex chain_base_joint = model_.frames[base_frame_id_].parent; - const pinocchio::JointIndex base_joint = model_.frames[base_frame_id].parent; - const pinocchio::JointIndex flange_joint = model_.frames[flange_frame_id_].parent; - const pinocchio::JointIndex ee_joint = model_.frames[ee_frame_id].parent; + const pinocchio::JointIndex chain_base_joint = model().frames[base_frame_id_].parent; + const pinocchio::JointIndex base_joint = model().frames[base_frame_id].parent; + const pinocchio::JointIndex flange_joint = model().frames[flange_frame_id_].parent; + const pinocchio::JointIndex ee_joint = model().frames[ee_frame_id].parent; auto jointOnParentPath = [this](pinocchio::JointIndex from, pinocchio::JointIndex target) { @@ -225,7 +225,7 @@ bool PinocchioDlsIKSolver::ik(const std::string& base_link, pinocchio::JointIndex j = from; while (j != 0) { if (j == target) return true; - j = model_.parents[j]; + j = model().parents[j]; } return false; }; @@ -267,8 +267,8 @@ bool PinocchioDlsIKSolver::ik(const std::string& base_link, break; } - Eigen::Matrix J_full(6, model_.nv); - pinocchio::computeFrameJacobian(model_, *data_, q_full, + Eigen::Matrix J_full(6, model().nv); + pinocchio::computeFrameJacobian(model(), *data_, q_full, ee_frame_id, pinocchio::ReferenceFrame::LOCAL, J_full); @@ -301,7 +301,7 @@ bool PinocchioDlsIKSolver::ik(const std::string& base_link, double qdot_abs_max) { if (!initialized_) return false; - if (!model_.existFrame(base_link)) { + if (!model().existFrame(base_link)) { CMVR_LOG(ERROR) << "[PinocchioDlsIKSolver] base frame not found: " << base_link; return false; } @@ -309,7 +309,7 @@ bool PinocchioDlsIKSolver::ik(const std::string& base_link, CMVR_LOG(ERROR) << "[PinocchioDlsIKSolver] ee_frame_name is empty"; return false; } - if (!model_.existFrame(ee_link)) { + if (!model().existFrame(ee_link)) { CMVR_LOG(ERROR) << "[PinocchioDlsIKSolver] frame not found: " << ee_link; return false; } @@ -324,13 +324,13 @@ bool PinocchioDlsIKSolver::ik(const std::string& base_link, return false; } - const pinocchio::FrameIndex base_id = model_.getFrameId(base_link); - const pinocchio::FrameIndex ee_id = model_.getFrameId(ee_link); + const pinocchio::FrameIndex base_id = model().getFrameId(base_link); + const pinocchio::FrameIndex ee_id = model().getFrameId(ee_link); - const pinocchio::JointIndex chain_base_joint = model_.frames[base_frame_id_].parent; - const pinocchio::JointIndex base_joint = model_.frames[base_id].parent; - const pinocchio::JointIndex flange_joint = model_.frames[flange_frame_id_].parent; - const pinocchio::JointIndex ee_joint = model_.frames[ee_id].parent; + const pinocchio::JointIndex chain_base_joint = model().frames[base_frame_id_].parent; + const pinocchio::JointIndex base_joint = model().frames[base_id].parent; + const pinocchio::JointIndex flange_joint = model().frames[flange_frame_id_].parent; + const pinocchio::JointIndex ee_joint = model().frames[ee_id].parent; auto jointOnParentPath = [this](pinocchio::JointIndex from, pinocchio::JointIndex target) { @@ -338,7 +338,7 @@ bool PinocchioDlsIKSolver::ik(const std::string& base_link, pinocchio::JointIndex j = from; while (j != 0) { if (j == target) return true; - j = model_.parents[j]; + j = model().parents[j]; } return false; }; @@ -373,8 +373,8 @@ bool PinocchioDlsIKSolver::ik(const std::string& base_link, twist_base.head<3>() = R_be * target_vel.head<3>(); twist_base.tail<3>() = R_be * target_vel.tail<3>(); - Eigen::Matrix J_world(6, model_.nv); - pinocchio::computeFrameJacobian(model_, *data_, q_full, + Eigen::Matrix J_world(6, model().nv); + pinocchio::computeFrameJacobian(model(), *data_, q_full, ee_id, pinocchio::ReferenceFrame::LOCAL_WORLD_ALIGNED, J_world); diff --git a/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/src/pinocchio_ik_base.cpp b/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/src/pinocchio_ik_base.cpp index 3ceba79e..5ebec147 100644 --- a/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/src/pinocchio_ik_base.cpp +++ b/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/src/pinocchio_ik_base.cpp @@ -23,40 +23,33 @@ PinocchioIKBase::PinocchioIKBase(const std::string& urdf_path, , tcp_frame_name_(tcp_frame_name) { } -PinocchioIKBase::PinocchioIKBase(std::shared_ptr parser, +PinocchioIKBase::PinocchioIKBase(const RobotModel& model, const std::string& base_frame_name, const std::string& flange_frame_name, const std::string& tcp_frame_name) - : IKSolver(parser, base_frame_name, flange_frame_name) + : IKSolver(model, base_frame_name, flange_frame_name) , tcp_frame_name_(tcp_frame_name) { } bool PinocchioIKBase::initPinocchioFromUrdfChain(UrdfParser::ChainInfo* chain_info_out, std::string* error) { - if (!urdf_parser_ || !urdf_parser_->loaded()) { - if (error) *error = "urdf parser not initialized"; + if (!robot_model_.hasKinematics() || !urdf_chain_cached_) { + if (error) *error = "robot model or chain is not initialized"; return false; } if (chain_base_frame_name_.empty() || chain_tip_frame_name_.empty()) { if (error) *error = "chain base/tip frame name is empty"; return false; } - if (!urdf_chain_cached_) { - if (!initUrdfChain(urdf_parser_, chain_base_frame_name_, chain_tip_frame_name_)) { - if (error) *error = "initUrdfChain failed"; - return false; - } - } + std::lock_guard query_lock(query_mutex_); + data_ = std::make_unique(model()); + query_data_ = std::make_unique(model()); - model_ = urdf_parser_->model(); - data_ = std::make_unique(model_); - - UrdfParser::ChainInfo chain_info; - std::string chain_err; - if (!urdf_parser_->extractChain(chain_base_frame_name_, chain_tip_frame_name_, chain_info, &chain_err)) { - if (error) *error = chain_err; - return false; - } + // Reinitialization starts from URDF limits before the solver reapplies its policy. + const auto& chain_info = chain_info_; + joint_pos_lower_limits_ = chain_info.q_lower; + joint_pos_upper_limits_ = chain_info.q_upper; + joint_vel_limits_ = chain_info.v_limit; base_frame_id_ = chain_info.base_frame_id; flange_frame_id_ = chain_info.tip_frame_id; @@ -67,8 +60,8 @@ bool PinocchioIKBase::initPinocchioFromUrdfChain(UrdfParser::ChainInfo* chain_in has_tcp_ = false; tcp_frame_id_ = (pinocchio::FrameIndex)(-1); - if (!tcp_frame_name_.empty() && model_.existFrame(tcp_frame_name_)) { - tcp_frame_id_ = model_.getFrameId(tcp_frame_name_); + if (!tcp_frame_name_.empty() && model().existFrame(tcp_frame_name_)) { + tcp_frame_id_ = model().getFrameId(tcp_frame_name_); has_tcp_ = true; } @@ -78,20 +71,24 @@ bool PinocchioIKBase::initPinocchioFromUrdfChain(UrdfParser::ChainInfo* chain_in return true; } +const pinocchio::Model& PinocchioIKBase::model() const { + return robot_model_.kinematics(); +} + bool PinocchioIKBase::buildFullQFromInput(const std::vector& joints, Eigen::VectorXd& q_full, const char* context) const { const int size = static_cast(joints.size()); - if (size != chain_q_dof_ && size != model_.nq) { + if (size != chain_q_dof_ && size != model().nq) { if (context != nullptr) { CMVR_LOG(ERROR) << "[PinocchioIKBase] " << context << " joints size mismatch"; } return false; } - q_full = pinocchio::neutral(model_); - if (size == model_.nq) { - q_full = Eigen::Map(joints.data(), model_.nq); + q_full = pinocchio::neutral(model()); + if (size == model().nq) { + q_full = Eigen::Map(joints.data(), model().nq); } else { Eigen::Map q_chain(joints.data(), chain_q_dof_); q_full.segment(chain_q_start_, chain_q_dof_) = q_chain; @@ -108,7 +105,7 @@ bool PinocchioIKBase::buildFullQFromChain(const Eigen::VectorXd& q_chain, } return false; } - q_full = pinocchio::neutral(model_); + q_full = pinocchio::neutral(model()); q_full.segment(chain_q_start_, chain_q_dof_) = q_chain; return true; } @@ -188,8 +185,8 @@ Eigen::VectorXd PinocchioIKBase::applyJointSoftLimitsToVelocity( } void PinocchioIKBase::updateKinematics(const Eigen::VectorXd& q_full) { - pinocchio::forwardKinematics(model_, *data_, q_full); - pinocchio::updateFramePlacements(model_, *data_); + pinocchio::forwardKinematics(model(), *data_, q_full); + pinocchio::updateFramePlacements(model(), *data_); } bool PinocchioIKBase::buildJacobianBaseAtQ(const std::vector& q_chain_std, @@ -217,8 +214,8 @@ bool PinocchioIKBase::buildJacobianBaseAtQ(const std::vector& q_chain_st const pinocchio::SE3 base_M_ee = oM_base.inverse() * oM_ee; base_R_ee = base_M_ee.rotation(); - Eigen::Matrix jacobian_world(6, model_.nv); - pinocchio::computeFrameJacobian(model_, *data_, q_full, + Eigen::Matrix jacobian_world(6, model().nv); + pinocchio::computeFrameJacobian(model(), *data_, q_full, ee_id, pinocchio::ReferenceFrame::LOCAL_WORLD_ALIGNED, jacobian_world); @@ -250,12 +247,12 @@ bool PinocchioIKBase::computeJacobianBaseAtQ(const std::vector& q_chain, Eigen::MatrixXd& jacobian_base, Eigen::Matrix3d& base_R_ee) { - if (!model_.existFrame(ee_frame_name)) { + if (!model().existFrame(ee_frame_name)) { CMVR_LOG(ERROR) << "[PinocchioIKBase] ee frame not found: " << ee_frame_name; return false; } return buildJacobianBaseAtQ(q_chain, - model_.getFrameId(ee_frame_name), + model().getFrameId(ee_frame_name), jacobian_base, base_R_ee, nullptr); @@ -266,9 +263,10 @@ bool PinocchioIKBase::computePoseAndJacobianBaseAtQ( const bool is_tcp, Eigen::Matrix4d& pose_base, Eigen::MatrixXd& jacobian_base, - Eigen::Matrix3d& base_R_ee) + Eigen::Matrix3d& base_R_ee) const { - if (!data_) { + std::lock_guard query_lock(query_mutex_); + if (!query_data_) { CMVR_LOG(ERROR) << "[PinocchioIKBase] computePoseAndJacobianBaseAtQ called before pinocchio init"; return false; } @@ -278,22 +276,27 @@ bool PinocchioIKBase::computePoseAndJacobianBaseAtQ( } const Eigen::Map q_chain(q_chain_std.data(), chain_q_dof_); + if (!q_chain.allFinite()) return false; Eigen::VectorXd q_full; if (!buildFullQFromChain(q_chain, q_full, "computePoseAndJacobianBaseAtQ")) { return false; } - updateKinematics(q_full); + // Reuse the dedicated query workspace instead of allocating Data every cycle. + auto& query_data = *query_data_; + pinocchio::forwardKinematics(model(), query_data, q_full); + pinocchio::updateFramePlacements(model(), query_data); const pinocchio::FrameIndex ee_id = (is_tcp && has_tcp_) ? tcp_frame_id_ : flange_frame_id_; - const pinocchio::SE3& oM_base = getBasePoseWorld(); - const pinocchio::SE3& oM_ee = data_->oMf[ee_id]; + const pinocchio::SE3& oM_base = base_pose_cached_ ? oM_base_cached_ : query_data.oMf[base_frame_id_]; + const pinocchio::SE3& oM_ee = query_data.oMf[ee_id]; const pinocchio::SE3 base_M_ee = oM_base.inverse() * oM_ee; pose_base = se3ToMatrix4(base_M_ee); base_R_ee = base_M_ee.rotation(); - Eigen::Matrix jacobian_world(6, model_.nv); - pinocchio::computeFrameJacobian(model_, *data_, q_full, + Eigen::Matrix jacobian_world(6, model().nv); + jacobian_world.setZero(); + pinocchio::computeFrameJacobian(model(), query_data, q_full, ee_id, pinocchio::ReferenceFrame::LOCAL_WORLD_ALIGNED, jacobian_world); @@ -304,7 +307,7 @@ bool PinocchioIKBase::computePoseAndJacobianBaseAtQ( jacobian_base.topRows(3) = R_bo * jacobian_base.topRows(3); jacobian_base.bottomRows(3) = R_bo * jacobian_base.bottomRows(3); - return true; + return pose_base.allFinite() && jacobian_base.allFinite(); } bool PinocchioIKBase::computeMeasuredTwistBase(const std::vector& q_chain, @@ -363,13 +366,13 @@ bool PinocchioIKBase::computeTwistBaseAtQ(const std::vector& q_chain, Eigen::MatrixXd* jacobian_base_out, Eigen::Matrix3d* base_R_ee_out) { - if (!model_.existFrame(ee_frame_name)) { + if (!model().existFrame(ee_frame_name)) { CMVR_LOG(ERROR) << "[PinocchioIKBase] ee frame not found: " << ee_frame_name; return false; } return computeMeasuredTwistBase(q_chain, qdot_chain, - model_.getFrameId(ee_frame_name), + model().getFrameId(ee_frame_name), twist_base, jacobian_base_out, base_R_ee_out, @@ -406,11 +409,11 @@ bool PinocchioIKBase::fk(const std::string& base_link, CMVR_LOG(ERROR) << "[PinocchioIKBase] fk called before pinocchio init"; return false; } - if (!model_.existFrame(base_link)) { + if (!model().existFrame(base_link)) { CMVR_LOG(ERROR) << "[PinocchioIKBase] base frame not found: " << base_link; return false; } - if (!model_.existFrame(ee_link)) { + if (!model().existFrame(ee_link)) { CMVR_LOG(ERROR) << "[PinocchioIKBase] ee frame not found: " << ee_link; return false; } @@ -421,8 +424,8 @@ bool PinocchioIKBase::fk(const std::string& base_link, } updateKinematics(q_full); - const pinocchio::FrameIndex base_id = model_.getFrameId(base_link); - const pinocchio::FrameIndex ee_id = model_.getFrameId(ee_link); + const pinocchio::FrameIndex base_id = model().getFrameId(base_link); + const pinocchio::FrameIndex ee_id = model().getFrameId(ee_link); const pinocchio::SE3& oM_base = data_->oMf[base_id]; const pinocchio::SE3& oM_ee = data_->oMf[ee_id]; const pinocchio::SE3 base_M_ee = oM_base.inverse() * oM_ee; diff --git a/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/src/pinocchio_qp_ik_solver.cpp b/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/src/pinocchio_qp_ik_solver.cpp index 4825d0a5..fdaf5aea 100644 --- a/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/src/pinocchio_qp_ik_solver.cpp +++ b/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/src/pinocchio_qp_ik_solver.cpp @@ -60,6 +60,7 @@ namespace cmvr { std::string vectorToString(const Eigen::VectorXd& value) { std::ostringstream stream; + stream.precision(12); stream << '['; for (Eigen::Index i = 0; i < value.size(); ++i) { if (i > 0) { @@ -235,7 +236,7 @@ namespace cmvr { } initialized_ = true; - CMVR_LOG(INFO) << "[PinocchioQpIKSolver] Init OK. full nq = " << model_.nq + CMVR_LOG(INFO) << "[PinocchioQpIKSolver] Init OK. full nq = " << model().nq << ", active dof = " << chain_q_dof_ << ", q_start=" << chain_q_start_ << ", v_start=" << chain_v_start_ << ", base frame = " << chain_base_frame_name_ @@ -281,6 +282,61 @@ namespace cmvr { return nullspace * qdot_avoid; } + bool PinocchioQpIKSolver::computeVelocityScale( + const MatrixXd& jacobian_base, + const Eigen::Matrix& target_twist_base, + const VectorXd& lower, const VectorXd& upper, double& scale) + { + scale = 0.0; + const Eigen::Index dof = jacobian_base.cols(); + if (dof == 0 || jacobian_base.rows() != 6 || lower.size() != dof || + upper.size() != dof || !jacobian_base.allFinite() || + !target_twist_base.allFinite() || !lower.allFinite() || + !upper.allFinite() || (lower.array() > upper.array()).any()) { + return false; + } + + // Minimize (alpha - 1)^2 with J*qdot = alpha*target. A QP over + // qdot and alpha preserves redundancy and need not assume alpha=0 is feasible. + MatrixXd cost = MatrixXd::Zero(1, dof + 1); + cost(0, dof) = 1.0; + MatrixXd constraints = MatrixXd::Zero(dof + 7, dof + 1); + constraints.topRows(dof + 1).setIdentity(); + constraints.bottomLeftCorner(6, dof) = jacobian_base; + constraints.bottomRightCorner(6, 1) = -target_twist_base; + VectorXd constraint_lower = VectorXd::Zero(dof + 7); + VectorXd constraint_upper = VectorXd::Zero(dof + 7); + constraint_lower.head(dof) = lower; + constraint_upper.head(dof) = upper; + constraint_upper[dof] = 1.0; + + VectorXd solution; + try { + QPSolver solver; + solver.Setup(dof + 1, dof + 7, 2e-3, 1e-6, 1e-6, true); + solver.SetCostFunction(cost, VectorXd::Ones(1)); + solver.SetConstraintsFunction(constraints, constraint_lower, constraint_upper); + solution = solver.Solve(); + } catch (const std::exception&) { + return false; + } + if (solution.size() != dof + 1 || !solution.allFinite() || + (constraint_lower.head(dof + 1) - solution).maxCoeff() > 1e-6 || + (solution - constraint_upper.head(dof + 1)).maxCoeff() > 1e-6) { + return false; + } + solution = solution.cwiseMax(constraint_lower.head(dof + 1)) + .cwiseMin(constraint_upper.head(dof + 1)); + const Eigen::Matrix residual = + jacobian_base * solution.head(dof) - target_twist_base * solution[dof]; + if (!residual.allFinite() || residual.head<3>().norm() > 2e-6 || + residual.tail<3>().norm() > 2e-6) { + return false; + } + scale = solution[dof]; + return true; + } + bool PinocchioQpIKSolver::ik(const Matrix4d &target_pose, std::vector &joints_angle, bool is_tcp) { @@ -356,8 +412,8 @@ namespace cmvr { dx.tail<3>() *= w_posrot_; // 6×nv Jacobian(LOCAL) - Eigen::Matrix J_full(6, model_.nv); - pinocchio::computeFrameJacobian(model_, *data_, q_full, + Eigen::Matrix J_full(6, model().nv); + pinocchio::computeFrameJacobian(model(), *data_, q_full, target_frame_id, pinocchio::ReferenceFrame::LOCAL, J_full); @@ -446,6 +502,20 @@ namespace cmvr { std::vector& qdot_out, const double qdot_abs_max) const { + return solveVelocityBase(jacobian_base, target_twist_base, q_chain_std, + qdot_out, VectorXd(), VectorXd(), qdot_abs_max); + } + + bool PinocchioQpIKSolver::solveVelocityBase( + const MatrixXd& jacobian_base, + const Eigen::Matrix& target_twist_base, + const std::vector& q_chain_std, + std::vector& qdot_out, + const VectorXd& external_lower, + const VectorXd& external_upper, + const double qdot_abs_max) const + { + qdot_out.clear(); if (!initialized_) { CMVR_LOG(ERROR) << "[PinocchioQpIKSolver] solveVelocityBase called before init()."; return false; @@ -460,24 +530,29 @@ namespace cmvr { } const int dof = chain_v_dof_; + const bool has_external_bounds = external_lower.size() != 0 || external_upper.size() != 0; + if (has_external_bounds && + (external_lower.size() != dof || external_upper.size() != dof)) { + CMVR_LOG(ERROR) << "[PinocchioQpIKSolver] solveVelocityBase bounds size mismatch."; + return false; + } + const Eigen::Map q_chain(q_chain_std.data(), dof); + if (!jacobian_base.allFinite() || !target_twist_base.allFinite() || !q_chain.allFinite()) { + CMVR_LOG(ERROR) << "[PinocchioQpIKSolver] solveVelocityBase non-finite input."; + return false; + } const auto& avoidance = jointLimitPolicy().avoidance(); const bool use_joint_limit_avoidance = - !jointLimitsDisabled() && avoidance.enable() && avoidance.gain() > 0.0; - const int avoidance_rows = use_joint_limit_avoidance ? dof : 0; + !jointLimitsDisabled() && avoidance.enable() && avoidance.gain() > 0.0 && + target_twist_base.squaredNorm() > 1e-12; - MatrixXd cost(6 + dof + avoidance_rows, dof); - VectorXd target(6 + dof + avoidance_rows); - cost.setZero(); - target.setZero(); - cost.topRows(6) = jacobian_base; - target.head(6) = target_twist_base; - cost.middleRows(6, dof) = - std::sqrt(lambda_) * MatrixXd::Identity(dof, dof); - target.segment(6, dof).setZero(); + // The Cartesian task is a hard equality. Joint effort can only choose + // between solutions that achieve the requested twist. + const MatrixXd cost = MatrixXd::Identity(dof, dof); + VectorXd target = VectorXd::Zero(dof); VectorXd lower(dof); VectorXd upper(dof); - const Eigen::Map q_chain(q_chain_std.data(), dof); if (use_joint_limit_avoidance) { const VectorXd qdot_avoid_raw = cmvr::kinematics::computeJointLimitAvoidanceVelocity( @@ -499,9 +574,10 @@ namespace cmvr { jacobian_pinv * jacobian_base; } const VectorXd qdot_avoid_null = nullspace * qdot_avoid_raw; - cost.middleRows(6 + dof, dof) = - nullspace; - target.segment(6 + dof, dof) = qdot_avoid_null; + // With J*qdot fixed, the former secondary objective + // lambda*||qdot||^2 + ||N*qdot - qdot_avoid_null||^2 has the + // same minimizer as this centered joint-norm objective. + target = qdot_avoid_null / (1.0 + lambda_); static std::atomic avoidance_debug_counter{0}; const auto debug_index = @@ -576,19 +652,52 @@ namespace cmvr { } } } + const double policy_lower = lower[i]; + const double policy_upper = upper[i]; + if (has_external_bounds) { + if (std::isnan(external_lower[i]) || std::isnan(external_upper[i])) { + CMVR_LOG(ERROR) << "[PinocchioQpIKSolver] solveVelocityBase NaN joint bound."; + return false; + } + lower[i] = std::max(lower[i], external_lower[i]); + upper[i] = std::min(upper[i], external_upper[i]); + } + if (!std::isfinite(lower[i]) || !std::isfinite(upper[i]) || lower[i] > upper[i]) { + CMVR_LOG(ERROR) << "[PinocchioQpIKSolver] solveVelocityBase infeasible joint bounds: joint=" + << i << ", lower=" << lower[i] << ", upper=" << upper[i] + << ", q=" << q_chain[i] << ", velocity_limit=" << limit + << ", policy_lower=" << policy_lower << ", policy_upper=" << policy_upper + << ", external_lower=" << (has_external_bounds ? external_lower[i] : -std::numeric_limits::infinity()) + << ", external_upper=" << (has_external_bounds ? external_upper[i] : std::numeric_limits::infinity()); + return false; + } } + MatrixXd constraints(dof + 6, dof); + constraints.topRows(dof).setIdentity(); + constraints.bottomRows(6) = jacobian_base; + VectorXd constraint_lower(dof + 6), constraint_upper(dof + 6); + constraint_lower.head(dof) = lower; + constraint_upper.head(dof) = upper; + constraint_lower.tail(6) = target_twist_base; + constraint_upper.tail(6) = target_twist_base; + QPSolver solver; - solver.Setup(dof, dof, qp_time_limit_); + // Polish active constraints to avoid numerical violations at joint limits. + solver.Setup(dof, dof + 6, qp_time_limit_, 1e-6, 1e-6, true); solver.SetCostFunction(cost, target); - solver.SetConstraintsFunction(MatrixXd::Identity(dof, dof), lower, upper); + solver.SetConstraintsFunction(constraints, constraint_lower, constraint_upper); VectorXd qdot; try { qdot = solver.Solve(); } catch (const QPSolverException& e) { CMVR_LOG(ERROR) << "[PinocchioQpIKSolver] solveVelocityBase QP failed: " - << e.what() << " (code=" << e.code() << ")"; + << e.what() << " (code=" << e.code() << ")" + << ", q=" << vectorToString(q_chain) + << ", lower=" << vectorToString(lower) + << ", upper=" << vectorToString(upper) + << ", target_twist=" << vectorToString(target_twist_base); return false; } catch (const std::exception& e) { CMVR_LOG(ERROR) << "[PinocchioQpIKSolver] solveVelocityBase QP failed: " @@ -596,7 +705,26 @@ namespace cmvr { return false; } - if (qdot.size() != dof) { + if (qdot.size() != dof || !qdot.allFinite()) { + return false; + } + constexpr double kJointBoundTolerance = 1e-6; + const double bound_violation = std::max((lower - qdot).maxCoeff(), + (qdot - upper).maxCoeff()); + if (bound_violation > kJointBoundTolerance) { + CMVR_LOG(ERROR) << "[PinocchioQpIKSolver] solveVelocityBase joint bound residual=" + << bound_violation; + return false; + } + // Snap only violations within the solver tolerance, then verify the + // Cartesian equality again. This is not an acceleration limiter. + qdot = qdot.cwiseMax(lower).cwiseMin(upper); + const Eigen::Matrix residual = jacobian_base * qdot - target_twist_base; + constexpr double kTwistResidualTolerance = 2e-6; + if (!residual.allFinite() || residual.head<3>().norm() > kTwistResidualTolerance || + residual.tail<3>().norm() > kTwistResidualTolerance) { + CMVR_LOG(ERROR) << "[PinocchioQpIKSolver] solveVelocityBase Cartesian equality residual: linear=" + << residual.head<3>().norm() << ", angular=" << residual.tail<3>().norm(); return false; } qdot_out.assign(qdot.data(), qdot.data() + qdot.size()); diff --git a/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/src/pinocchio_qp_ik_solver_test.cpp b/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/src/pinocchio_qp_ik_solver_test.cpp index 9edbb089..a2a6005b 100644 --- a/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/src/pinocchio_qp_ik_solver_test.cpp +++ b/cmvr-es/algorithms/kinematics/ik_solver/pinocchio/src/pinocchio_qp_ik_solver_test.cpp @@ -1,5 +1,7 @@ #include "algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_qp_ik_solver.h" +#include +#include #include #include @@ -59,6 +61,80 @@ TEST(PinocchioQpIKSolverTest, JointLimitAvoidanceIsInCartesianNullspace) EXPECT_GT(qdot_null.norm(), 0.0); } +TEST(PinocchioQpIKSolverTest, VelocityScaleUsesRedundancyAtJointLimit) +{ + Eigen::MatrixXd jacobian = Eigen::MatrixXd::Zero(6, 7); + jacobian.leftCols(6).setIdentity(); + jacobian(0, 6) = 1.0; + Eigen::Matrix target = Eigen::Matrix::Zero(); + target[0] = 0.4; + Eigen::VectorXd lower = Eigen::VectorXd::Constant(7, -0.5); + Eigen::VectorXd upper = Eigen::VectorXd::Constant(7, 0.5); + upper[0] = 0.0; + + // The unconstrained least-norm solution moves joint 0 toward its limit; + // joint 6 can instead provide the entire requested Cartesian velocity. + double scale = 0.0; + ASSERT_TRUE(PinocchioQpIKSolver::computeVelocityScale( + jacobian, target, lower, upper, scale)); + EXPECT_NEAR(scale, 1.0, 2e-6); + + // Once the redundant joint is also constrained, the exact maximum is 25%. + upper[6] = 0.1; + ASSERT_TRUE(PinocchioQpIKSolver::computeVelocityScale( + jacobian, target, lower, upper, scale)); + EXPECT_NEAR(scale, 0.25, 2e-6); +} + +TEST(PinocchioQpIKSolverTest, VelocityScaleDoesNotAssumeZeroIsFeasible) +{ + const Eigen::MatrixXd jacobian = Eigen::MatrixXd::Identity(6, 6); + Eigen::Matrix target = Eigen::Matrix::Zero(); + target[0] = 1.0; + Eigen::VectorXd lower = Eigen::VectorXd::Constant(6, -1.0); + Eigen::VectorXd upper = Eigen::VectorXd::Ones(6); + lower[0] = 0.2; + upper[0] = 0.4; + double scale = 0.0; + ASSERT_TRUE(PinocchioQpIKSolver::computeVelocityScale( + jacobian, target, lower, upper, scale)); + EXPECT_NEAR(scale, 0.4, 2e-6); + + // qdot[0] must remain positive, so neither a zero nor a negative task is feasible. + for (const double velocity : {0.0, -1.0}) { + target[0] = velocity; + scale = 1.0; + EXPECT_FALSE(PinocchioQpIKSolver::computeVelocityScale( + jacobian, target, lower, upper, scale)); + EXPECT_DOUBLE_EQ(scale, 0.0); + } +} + +TEST(PinocchioQpIKSolverTest, VelocityScaleRejectsInvalidInputs) +{ + Eigen::MatrixXd jacobian = Eigen::MatrixXd::Identity(6, 6); + Eigen::Matrix target = Eigen::Matrix::Zero(); + Eigen::VectorXd lower = Eigen::VectorXd::Constant(6, -1.0); + Eigen::VectorXd upper = Eigen::VectorXd::Ones(6); + double scale = 1.0; + EXPECT_FALSE(PinocchioQpIKSolver::computeVelocityScale( + jacobian.topRows(5), target, lower, upper, scale)); + EXPECT_DOUBLE_EQ(scale, 0.0); + EXPECT_FALSE(PinocchioQpIKSolver::computeVelocityScale( + jacobian, target, lower.head(5), upper, scale)); + lower[0] = 2.0; + EXPECT_FALSE(PinocchioQpIKSolver::computeVelocityScale( + jacobian, target, lower, upper, scale)); + lower[0] = -std::numeric_limits::infinity(); + EXPECT_FALSE(PinocchioQpIKSolver::computeVelocityScale( + jacobian, target, lower, upper, scale)); + lower[0] = -1.0; + target[0] = std::numeric_limits::quiet_NaN(); + EXPECT_FALSE(PinocchioQpIKSolver::computeVelocityScale( + jacobian, target, lower, upper, scale)); + EXPECT_DOUBLE_EQ(scale, 0.0); +} + TEST(PinocchioQpIKSolverTest, AvoidanceDoesNotDisturbReachableCartesianTwist) { const auto root = findProjectRoot(); @@ -97,7 +173,297 @@ TEST(PinocchioQpIKSolverTest, AvoidanceDoesNotDisturbReachableCartesianTwist) const Eigen::VectorXd achieved_enabled = jacobian * qdot_enabled_eigen; EXPECT_LT((achieved_enabled - achieved_disabled).norm(), 1e-6); - EXPECT_LT((achieved_enabled - target_twist).norm(), 5e-5); + EXPECT_LT((achieved_enabled - target_twist).norm(), 3e-6); + EXPECT_LT(qdot_enabled[6], -1e-3); + EXPECT_NEAR(qdot_disabled[6], 0.0, 1e-8); +} + +TEST(PinocchioQpIKSolverTest, TracksTouchTwistAtShoulderLimitWithoutCartesianCompromise) +{ + const auto root = findProjectRoot(); + ASSERT_FALSE(root.empty()); + PinocchioQpIKSolver solver(loadQpConfig(root)); + ASSERT_TRUE(solver.init()); + + // Reconstructed off-center touch pose: shoulder roll is at its upper limit. + const std::vector q = {0.2667416268, 1.57, 0.9599837007, 1.223555827, + -2.912197805, -0.4882931474, -0.03457454408}; + Eigen::Matrix4d pose; + Eigen::MatrixXd jacobian; + Eigen::Matrix3d rotation; + ASSERT_TRUE(solver.computePoseAndJacobianBaseAtQ(q, true, pose, jacobian, rotation)); + Eigen::Matrix target = Eigen::Matrix::Zero(); + target.head<3>() = -0.04 * rotation.col(1); + std::vector qdot; + ASSERT_TRUE(solver.solveVelocityBase(jacobian, target, q, qdot)); + ASSERT_EQ(qdot.size(), q.size()); + const Eigen::Map velocity(qdot.data(), qdot.size()); + const Eigen::Matrix residual = jacobian * velocity - target; + EXPECT_LT(residual.head<3>().norm(), 2e-6); + EXPECT_LT(residual.tail<3>().norm(), 2e-6); + EXPECT_LE(qdot[1], 0.0); + EXPECT_LE(velocity.cwiseAbs().maxCoeff(), 5.0); +} + +TEST(PinocchioQpIKSolverTest, ExternalBoundsPreserveTaskAndIntersectConfiguredLimits) +{ + const auto root = findProjectRoot(); + ASSERT_FALSE(root.empty()); + PinocchioQpIKSolver solver(loadQpConfig(root)); + ASSERT_TRUE(solver.init()); + EXPECT_TRUE(solver.supportsJointVelocityBounds()); + + Eigen::MatrixXd jacobian = Eigen::MatrixXd::Zero(6, 7); + jacobian.leftCols(6).setIdentity(); + jacobian(0, 6) = 1.0; + Eigen::Matrix target = Eigen::Matrix::Zero(); + target[0] = 0.04; + const std::vector q = {0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0}; + Eigen::VectorXd lower = Eigen::VectorXd::Constant(7, -0.1); + Eigen::VectorXd upper = Eigen::VectorXd::Constant(7, 0.1); + upper[0] = 0.005; + lower[6] = 0.035; + upper[6] = 0.04; + std::vector qdot; + ASSERT_TRUE(solver.solveVelocityBase(jacobian, target, q, qdot, lower, upper)); + const Eigen::Map velocity(qdot.data(), qdot.size()); + EXPECT_LT((jacobian * velocity - target).norm(), 2e-6); + EXPECT_LE(qdot[0], upper[0]); + EXPECT_GE(qdot[6], lower[6]); + EXPECT_LE(qdot[6], upper[6]); + + // An external bound cannot override a smaller configured velocity limit. + solver.setVelocityLimits(Eigen::VectorXd::Constant(7, 0.02)); + EXPECT_FALSE(solver.solveVelocityBase(jacobian, target, q, qdot, lower, upper)); + EXPECT_TRUE(qdot.empty()); +} + +TEST(PinocchioQpIKSolverTest, InfeasibleTwistFailsInsteadOfReturningSlowerOrDeflectedMotion) +{ + const auto root = findProjectRoot(); + ASSERT_FALSE(root.empty()); + PinocchioQpIKSolver solver(loadQpConfig(root)); + ASSERT_TRUE(solver.init()); + Eigen::MatrixXd jacobian = Eigen::MatrixXd::Zero(6, 7); + jacobian.leftCols(6).setIdentity(); + const std::vector q = {0.0, 1.57, 0.0, 1.0, 0.0, 0.0, 0.0}; + Eigen::Matrix target = Eigen::Matrix::Zero(); + target[1] = 0.04; + std::vector qdot(7, 0.1); + EXPECT_FALSE(solver.solveVelocityBase(jacobian, target, q, qdot)); + EXPECT_TRUE(qdot.empty()); + + target.setZero(); + target[0] = 0.04; + const Eigen::VectorXd lower = Eigen::VectorXd::Constant(7, -0.01); + const Eigen::VectorXd upper = Eigen::VectorXd::Constant(7, 0.01); + EXPECT_FALSE(solver.solveVelocityBase(jacobian, target, q, qdot, lower, upper)); + EXPECT_TRUE(qdot.empty()); +} + +TEST(PinocchioQpIKSolverTest, ZeroTwistStopsAvoidanceAndHonorsRemainingNullspaceDeceleration) +{ + const auto root = findProjectRoot(); + ASSERT_FALSE(root.empty()); + auto config = loadQpConfig(root); + config.mutable_joint_limit_policy()->mutable_avoidance()->set_enable(true); + PinocchioQpIKSolver solver(config); + ASSERT_TRUE(solver.init()); + Eigen::MatrixXd jacobian = Eigen::MatrixXd::Zero(6, 7); + jacobian.leftCols(6).setIdentity(); + const std::vector q = {0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.56}; + const Eigen::Matrix target = Eigen::Matrix::Zero(); + std::vector qdot; + ASSERT_TRUE(solver.solveVelocityBase(jacobian, target, q, qdot)); + EXPECT_LT(Eigen::Map(qdot.data(), qdot.size()).norm(), 1e-8); + + Eigen::VectorXd lower = Eigen::VectorXd::Constant(7, -0.1); + Eigen::VectorXd upper = Eigen::VectorXd::Constant(7, 0.1); + // Previous nullspace motion cannot stop within one acceleration-limited step. + for (const double minimum_velocity : {0.04, 0.02, 0.0}) { + lower[6] = minimum_velocity; + upper[6] = minimum_velocity + 0.01; + ASSERT_TRUE(solver.solveVelocityBase(jacobian, target, q, qdot, lower, upper)); + const Eigen::Map velocity(qdot.data(), qdot.size()); + EXPECT_LT((jacobian * velocity).norm(), 2e-6); + EXPECT_NEAR(qdot[6], minimum_velocity, 1e-6); + EXPECT_GE(qdot[6], minimum_velocity); + } +} + +TEST(PinocchioQpIKSolverTest, InfeasibleNearLimitTwistThenHeldVelocityReproducesEmptyBounds) +{ + const auto root = findProjectRoot(); + ASSERT_FALSE(root.empty()); + const auto config = loadQpConfig(root); + PinocchioQpIKSolver solver(config); + ASSERT_TRUE(solver.init()); + + const auto& wrist = config.joint_limit_policy().limits().joints(6); + ASSERT_EQ(wrist.joint_name(), "R_WRIST_R"); + ASSERT_DOUBLE_EQ(wrist.q_lb(), -0.57); + ASSERT_DOUBLE_EQ(wrist.q_ub(), 1.57); + ASSERT_DOUBLE_EQ(wrist.qd(), 5.0); + ASSERT_DOUBLE_EQ(wrist.qdd(), 100.0); + const auto& soft_limit = config.joint_limit_policy().soft_limit(); + ASSERT_TRUE(soft_limit.enable()); + const double margin = std::max(soft_limit.min_margin_rad(), + soft_limit.margin_ratio() * (wrist.q_ub() - wrist.q_lb())); + ASSERT_NEAR(margin, 0.0214, 1e-12); + constexpr double dt = 0.001; + constexpr double logged_lower = -0.210923; + constexpr double logged_upper = -0.21925; + const double previous_velocity = logged_upper - wrist.qdd() * dt; + const double conflict_position = wrist.q_lb() - logged_lower * margin / wrist.qd(); + + // Constructed reproduction, not a replay of measured joint states: the log + // contains neither q nor J. This full-row-rank Jacobian makes the requested + // angular velocity uniquely require wrist velocity, isolating the conflict. + Eigen::MatrixXd jacobian = Eigen::MatrixXd::Zero(6, 7); + jacobian.topLeftCorner(5, 5).setIdentity(); + jacobian(5, 6) = 1.0; + Eigen::Matrix target = Eigen::Matrix::Zero(); + target[5] = previous_velocity; + std::vector q = {0.0, 0.0, 0.0, 1.0, 0.0, 0.0, + conflict_position - 2.0 * previous_velocity * dt}; + Eigen::VectorXd lower = Eigen::VectorXd::Constant(7, -wrist.qdd() * dt); + Eigen::VectorXd upper = -lower; + lower[6] += previous_velocity; + upper[6] += previous_velocity; + const auto soft_lower = [&](double position) { + return -wrist.qd() * (position - wrist.q_lb()) / margin; + }; + + std::vector qdot; + ASSERT_TRUE(solver.solveVelocityBase(jacobian, target, q, qdot, lower, upper)); + ASSERT_EQ(qdot.size(), 7); + EXPECT_NEAR(qdot[6], previous_velocity, 1e-6); + + q[6] += previous_velocity * dt; + const auto first_failure_q = q; + // First failure: the joint interval is nonempty, but cannot satisfy J*qdot. + ASSERT_NEAR(soft_lower(q[6]), -0.285514121495, 1e-10); + ASSERT_LT(soft_lower(q[6]), upper[6]); + ASSERT_LT(target[5], soft_lower(q[6])); + EXPECT_FALSE(solver.solveVelocityBase(jacobian, target, q, qdot, lower, upper)); + EXPECT_TRUE(qdot.empty()); + + // Keeping the previous command for one more tick reproduces the reported + // empty interval. The conflict exists before considering any Cartesian task. + q[6] += previous_velocity * dt; + ASSERT_NEAR(q[6], conflict_position, 1e-12); + ASSERT_NEAR(soft_lower(q[6]), logged_lower, 1e-10); + ASSERT_NEAR(upper[6], logged_upper, 1e-12); + ASSERT_GT(soft_lower(q[6]), upper[6]); + target.setZero(); + EXPECT_FALSE(solver.solveVelocityBase(jacobian, target, q, qdot, lower, upper)); + EXPECT_TRUE(qdot.empty()); + + // Control: at the first failure, an achievable deceleration is still + // feasible. Applying it avoids the second failure; no limits are relaxed. + q = first_failure_q; + double reference_velocity = previous_velocity; + for (int tick = 0; tick < 4; ++tick) { + SCOPED_TRACE(tick); + lower[6] = reference_velocity - wrist.qdd() * dt; + upper[6] = reference_velocity + wrist.qdd() * dt; + target[5] = std::min(0.0, upper[6]); + ASSERT_TRUE(solver.solveVelocityBase(jacobian, target, q, qdot, lower, upper)); + ASSERT_EQ(qdot.size(), 7); + EXPECT_GE(qdot[6], soft_lower(q[6]) - 1e-6); + EXPECT_LE(std::abs(qdot[6] - reference_velocity), wrist.qdd() * dt + 1e-6); + q[6] += qdot[6] * dt; + EXPECT_GT(q[6], wrist.q_lb()); + reference_velocity = qdot[6]; + } + EXPECT_NEAR(reference_velocity, 0.0, 1e-6); +} + +TEST(PinocchioQpIKSolverTest, ReplayedTouchTwistConflictsWithWristSoftLimit) +{ + const auto root = findProjectRoot(); + ASSERT_FALSE(root.empty()); + auto config = loadQpConfig(root); + PinocchioQpIKSolver solver(config); + ASSERT_TRUE(solver.init()); + + // Captured at the first QP failure in the MuJoCo touch replay. Unlike the + // constructed test above, the production URDF supplies the actual Jacobian. + const std::vector q = {0.582722602717, 1.18224927602, 1.476371331, + 0.30800863072, -2.97894487049, 0.408292452313, -0.568806827985}; + Eigen::Matrix target; + target << 0.0396215759735, 0.00324152795861, -0.00442980968738, 0.0, 0.0, 0.0; + Eigen::VectorXd upper(7); + upper << 0.535860147793, 0.16095635899, -0.0472852863641, + -0.602869190529, -0.0512145905955, 0.131906068524, -0.220632525731; + // Previous command +/- 100 rad/s^2 * 1 ms, before soft-limit intersection. + const Eigen::VectorXd lower = upper.array() - 0.2; + Eigen::Matrix4d pose; + Eigen::MatrixXd jacobian; + Eigen::Matrix3d rotation; + ASSERT_TRUE(solver.computePoseAndJacobianBaseAtQ(q, true, pose, jacobian, rotation)); + const double wrist_soft_lower = -5.0 * (q[6] - (-0.57)) / 0.0214; + ASSERT_NEAR(wrist_soft_lower, -0.278778508293, 1e-9); + ASSERT_LT(wrist_soft_lower, upper[6]); + std::vector qdot; + EXPECT_FALSE(solver.solveVelocityBase(jacobian, target, q, qdot, lower, upper)); + EXPECT_TRUE(qdot.empty()); + + // Diagnostic control only: source configurations remain unchanged. Keeping + // position/velocity/acceleration bounds but removing the soft margin makes + // the original Cartesian equality feasible and requires faster wrist motion. + config.mutable_joint_limit_policy()->mutable_soft_limit()->set_enable(false); + PinocchioQpIKSolver without_soft_limit(config); + ASSERT_TRUE(without_soft_limit.init()); + ASSERT_TRUE(without_soft_limit.solveVelocityBase(jacobian, target, q, qdot, lower, upper)); + ASSERT_EQ(qdot.size(), 7); + EXPECT_LT(qdot[6], wrist_soft_lower); + RecordProperty("full_speed_wrist_without_soft_limit", std::to_string(qdot[6])); + + // Counterfactual lower speed along the same line, with all original bounds + // retained. The first feasible sample is the largest on this 0.01 grid. + double feasible_scale = 0.0; + for (int percent = 99; percent > 0; --percent) { + const double scale = percent / 100.0; + if (solver.solveVelocityBase(jacobian, scale * target, q, qdot, lower, upper)) { + feasible_scale = scale; + break; + } + } + ASSERT_GT(feasible_scale, 0.0); + ASSERT_EQ(qdot.size(), 7); + const Eigen::Map velocity(qdot.data(), qdot.size()); + EXPECT_LT((jacobian * velocity - feasible_scale * target).norm(), 3e-6); + EXPECT_GE(qdot[6], wrist_soft_lower - 1e-6); + EXPECT_LE((velocity - upper).maxCoeff(), 1e-6); + EXPECT_LE((lower - velocity).maxCoeff(), 1e-6); + RecordProperty("largest_feasible_scale_on_percent_grid", std::to_string(feasible_scale)); + RecordProperty("scaled_wrist_with_soft_limit", std::to_string(qdot[6])); +} + +TEST(PinocchioQpIKSolverTest, PoseIkStillConvergesWithExistingConfiguration) +{ + const auto root = findProjectRoot(); + ASSERT_FALSE(root.empty()); + PinocchioQpIKSolver solver(loadQpConfig(root)); + ASSERT_TRUE(solver.init()); + const auto model = solver.getRobotModel(); + EXPECT_TRUE(model.valid()); + EXPECT_TRUE(model.hasKinematics()); + EXPECT_FALSE(model.hasCollisionGeometry()); + const std::vector target_q = {0.2, 1.0, 0.8, 1.2, -2.3, -0.3, 0.2}; + Eigen::Matrix4d target_pose; + ASSERT_TRUE(solver.fk(target_q, target_pose, true)); + auto seed = target_q; + seed[0] += 0.02; + seed[3] -= 0.02; + solver.update_joints_state(seed); + std::vector result; + ASSERT_TRUE(solver.ik(target_pose, result, true)); + Eigen::Matrix4d achieved_pose; + ASSERT_TRUE(solver.fk(result, achieved_pose, true)); + EXPECT_LT((achieved_pose.block<3, 1>(0, 3) - target_pose.block<3, 1>(0, 3)).norm(), 1e-5); + EXPECT_LT((achieved_pose.block<3, 3>(0, 0) - target_pose.block<3, 3>(0, 0)).norm(), 1e-5); } } // namespace diff --git a/cmvr-es/algorithms/motion_planner/CMakeLists.txt b/cmvr-es/algorithms/motion_planner/CMakeLists.txt deleted file mode 100644 index aadc080e..00000000 --- a/cmvr-es/algorithms/motion_planner/CMakeLists.txt +++ /dev/null @@ -1,2 +0,0 @@ -add_subdirectory(base_motion) -add_subdirectory(arm_motion) diff --git a/cmvr-es/algorithms/motion_planner/arm_motion/CMakeLists.txt b/cmvr-es/algorithms/motion_planner/arm_motion/CMakeLists.txt deleted file mode 100644 index f5313688..00000000 --- a/cmvr-es/algorithms/motion_planner/arm_motion/CMakeLists.txt +++ /dev/null @@ -1,35 +0,0 @@ -add_library(arm_motion SHARED - cartesian_motion/pinocchio/src/pinocchio_cartesian_motion_planner.cpp - joint_motion/toppra/src/toppra_joint_motion_planner.cpp -) - -target_include_directories(arm_motion PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) - -target_link_libraries(arm_motion - PUBLIC - cmvr_es::ik_solver - cmvr_es::base_motion -) - -add_library(cmvr_es::arm_motion ALIAS arm_motion) -add_library(cmvr_es::algorithms::arm_motion ALIAS arm_motion) -install(TARGETS arm_motion LIBRARY DESTINATION lib) - -add_executable(toppra_joint_motion_planner_test - joint_motion/toppra/test/toppra_joint_motion_planner_test.cpp -) - -target_link_libraries(toppra_joint_motion_planner_test - PRIVATE - cmvr_es::algorithms::arm_motion - gtest - gtest_main -) - -add_executable(pinocchio_speedl_limits_test - cartesian_motion/pinocchio/test/pinocchio_speedl_limits_test.cpp -) -target_compile_definitions(pinocchio_speedl_limits_test PRIVATE - CMVR_TEST_SOURCE_DIR="${PROJECT_SOURCE_DIR}") -target_link_libraries(pinocchio_speedl_limits_test PRIVATE - cmvr_es::algorithms::arm_motion gtest gtest_main) diff --git a/cmvr-es/algorithms/motion_planner/arm_motion/cartesian_motion/cartesian_motion_planner.h b/cmvr-es/algorithms/motion_planner/arm_motion/cartesian_motion/cartesian_motion_planner.h deleted file mode 100644 index 816854f0..00000000 --- a/cmvr-es/algorithms/motion_planner/arm_motion/cartesian_motion/cartesian_motion_planner.h +++ /dev/null @@ -1,58 +0,0 @@ -#ifndef CMVR_ES_CARTESIAN_MOTION_PLANNER_H -#define CMVR_ES_CARTESIAN_MOTION_PLANNER_H - -#include -#include - -#include "cmvr/config/arm_config/arm_config.pb.h" -#include "common/types/arm/arm_types.h" - -namespace cmvr::device { - -struct CartesianJointTrajectory { - std::vector> position; - std::vector> velocity; - std::vector time; - double planned_path_length{0.0}; - double executable_path_length{0.0}; - bool truncated{false}; - std::string truncation_reason; -}; - -class CartesianMotionPlanner { -public: - virtual ~CartesianMotionPlanner() = default; - - virtual bool configureSpeedL(const config::SpeedLPlannerConfig& config, - std::size_t dof) = 0; - virtual bool configureMoveL(const config::MoveLPlannerConfig& config) = 0; - - virtual bool planMoveL(const CartesianPose& target, - const std::vector& q_start, - const std::vector& qd_max, - double velocity, - double acceleration, - double jerk, - FrameType frame, - CartesianJointTrajectory& trajectory) = 0; - - virtual bool speedLStep(const CartesianVelocity& target_velocity, - double dt, - const std::vector& q_measured, - const std::vector& qd_measured, - std::vector& qd_command, - FrameType frame) = 0; - - virtual bool updateSpeedLAcceleration(double acceleration) = 0; - virtual bool updateSpeedLLimits(const SpeedLOptions& options) { - return !options.linear_jerk && !options.continuous_linear_reversal.value_or(false) && - updateSpeedLAcceleration(options.acceleration); - } - virtual bool captureSpeedLReference(const std::vector&, - const CartesianVelocity&, FrameType, SpeedLReference&) { return false; } - virtual CartesianVelocity getSpeedLCommandTwistBase() const = 0; -}; - -} // namespace cmvr::device - -#endif // CMVR_ES_CARTESIAN_MOTION_PLANNER_H diff --git a/cmvr-es/algorithms/motion_planner/arm_motion/cartesian_motion/cartesian_motion_planner_factory.h b/cmvr-es/algorithms/motion_planner/arm_motion/cartesian_motion/cartesian_motion_planner_factory.h deleted file mode 100644 index ec527c68..00000000 --- a/cmvr-es/algorithms/motion_planner/arm_motion/cartesian_motion/cartesian_motion_planner_factory.h +++ /dev/null @@ -1,63 +0,0 @@ -#ifndef CMVR_ES_CARTESIAN_MOTION_PLANNER_FACTORY_H -#define CMVR_ES_CARTESIAN_MOTION_PLANNER_FACTORY_H - -#include - -#include "algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_ik_base.h" -#include "algorithms/motion_planner/arm_motion/cartesian_motion/pinocchio/include/pinocchio_cartesian_motion_planner.h" -#include "algorithms/motion_planner/arm_motion/cartesian_motion/cartesian_motion_planner.h" -#include "cmvr/config/arm_config/arm_config.pb.h" - -namespace cmvr::device { - -class CartesianMotionPlannerFactory { -public: - static std::shared_ptr create( - const config::MoveLConfig& move_l, - const config::SpeedLConfig& speed_l, - const std::shared_ptr& solver) - { - if (!solver) { - return nullptr; - } - switch (move_l.algorithm_case()) { - case config::MoveLConfig::kPinocchioCartesianMotionPlanner: - if (speed_l.algorithm_case() != - config::SpeedLConfig::kPinocchioCartesianMotionPlanner) { - return nullptr; - } - return std::make_shared(solver); - case config::MoveLConfig::ALGORITHM_NOT_SET: - default: - return nullptr; - } - } - - static const config::SpeedLPlannerConfig* speedLConfig( - const config::SpeedLConfig& cfg) - { - switch (cfg.algorithm_case()) { - case config::SpeedLConfig::kPinocchioCartesianMotionPlanner: - return &cfg.pinocchio_cartesian_motion_planner(); - case config::SpeedLConfig::ALGORITHM_NOT_SET: - default: - return nullptr; - } - } - - static const config::MoveLPlannerConfig* moveLConfig( - const config::MoveLConfig& cfg) - { - switch (cfg.algorithm_case()) { - case config::MoveLConfig::kPinocchioCartesianMotionPlanner: - return &cfg.pinocchio_cartesian_motion_planner(); - case config::MoveLConfig::ALGORITHM_NOT_SET: - default: - return nullptr; - } - } -}; - -} // namespace cmvr::device - -#endif // CMVR_ES_CARTESIAN_MOTION_PLANNER_FACTORY_H diff --git a/cmvr-es/algorithms/motion_planner/arm_motion/cartesian_motion/pinocchio/include/pinocchio_cartesian_motion_planner.h b/cmvr-es/algorithms/motion_planner/arm_motion/cartesian_motion/pinocchio/include/pinocchio_cartesian_motion_planner.h deleted file mode 100644 index b83848dc..00000000 --- a/cmvr-es/algorithms/motion_planner/arm_motion/cartesian_motion/pinocchio/include/pinocchio_cartesian_motion_planner.h +++ /dev/null @@ -1,117 +0,0 @@ -#ifndef CMVR_ES_PINOCCHIO_QP_CARTESIAN_MOTION_PLANNER_H -#define CMVR_ES_PINOCCHIO_QP_CARTESIAN_MOTION_PLANNER_H - -#include - -#include -#include - -#include "algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_ik_base.h" -#include "../../cartesian_motion_planner.h" -#include "algorithms/motion_planner/base_motion/cartesian_velocity/twist_limiter/include/cartesian_twist_limiter.h" - -namespace cmvr::device { - -class PinocchioCartesianMotionPlanner final : public CartesianMotionPlanner { -public: - explicit PinocchioCartesianMotionPlanner(std::shared_ptr solver); - - bool configureSpeedL(const config::SpeedLPlannerConfig& config, - std::size_t dof) override; - bool configureMoveL(const config::MoveLPlannerConfig& config) override; - - bool planMoveL(const CartesianPose& target, - const std::vector& q_start, - const std::vector& qd_max, - double velocity, - double acceleration, - double jerk, - FrameType frame, - CartesianJointTrajectory& trajectory) override; - - bool speedLStep(const CartesianVelocity& target_velocity, - double dt, - const std::vector& q_measured, - const std::vector& qd_measured, - std::vector& qd_command, - FrameType frame) override; - - bool updateSpeedLAcceleration(double acceleration) override; - bool updateSpeedLLimits(const SpeedLOptions& options) override; - bool captureSpeedLReference(const std::vector& q, const CartesianVelocity& target, - FrameType frame, SpeedLReference& reference) override; - CartesianVelocity getSpeedLCommandTwistBase() const override; - -private: - bool refreshJointAccelerationLimits_(); - Eigen::VectorXd applyJointAccelerationLimits_(const Eigen::VectorXd& qdot, - const Eigen::VectorXd& reference, - double dt) const; - bool checkMoveLPlanLineDeviation_(const Eigen::Vector3d& p_start, - const Eigen::Vector3d& line_direction, - const Eigen::Vector3d& p_current, - double traveled, - bool& deviation_warned, - bool& direction_warned, - std::string& stop_reason) const; - bool checkMoveLPlanJointContinuity_(const Eigen::VectorXd& q_current, - const Eigen::VectorXd& q_next, - const Eigen::VectorXd& qdot, - const Eigen::VectorXd& prev_qdot, - double dt, - double path_position, - std::string& stop_reason) const; - bool checkMoveLPlanJointPositionLimits_(const Eigen::VectorXd& q_current, - const Eigen::VectorXd& q_next, - const Eigen::VectorXd& qdot, - double dt, - double path_position, - std::string& stop_reason) const; - bool checkMoveLPlanCartesianStepFeasibility_( - const Eigen::Matrix& desired_twist, - const Eigen::Matrix& achieved_twist, - double path_position, - std::string& stop_reason) const; - bool updateAndValidateSpeedLLineDeviation_(const std::vector& q_measured, - bool is_stop_command, - const Eigen::Vector3d& command_linear_base); - bool validateSpeedLJointVelocityCommand_(const Eigen::VectorXd& qdot, - const Eigen::VectorXd& reference, - double dt) const; - bool validateSpeedLPredictedJointPositionLimits_(const std::vector& q_measured, - const Eigen::VectorXd& qdot, - double dt) const; - bool validateSpeedLCartesianVelocityFeasibility_( - const Eigen::Matrix& desired_twist, - const Eigen::Matrix& achieved_twist, - const Eigen::VectorXd& q_current, - const Eigen::VectorXd& qdot) const; - std::string describeJointLimitCandidates_(const Eigen::VectorXd& q_current, - const Eigen::VectorXd& qdot) const; - - std::shared_ptr solver_{nullptr}; - config::MoveLPlannerConfig movel_config_{}; - config::SpeedLPlannerConfig speedl_config_{}; - cmvr::CartesianTwistLimiter twist_limiter_{}; - Eigen::VectorXd joint_acceleration_limits_; - std::vector prev_qdot_command_; - Eigen::Matrix speedl_command_twist_base_{Eigen::Matrix::Zero()}; - Eigen::Vector3d speedl_line_start_tcp_base_{Eigen::Vector3d::Zero()}; - Eigen::Vector3d speedl_line_direction_base_{Eigen::Vector3d::Zero()}; - double speedl_applied_acceleration_{0.25}; - double speedl_applied_angular_acceleration_{0.25}; - double speedl_applied_linear_jerk_{-1.0}; - bool speedl_line_check_active_{false}; - bool speedl_line_deviation_warned_{false}; - bool speedl_line_direction_warned_{false}; - - // speedL 是否已经进入停止阶段。 - // 停止阶段不要每 1 ms 用 measured twist 重新点燃 Cartesian planner。 - bool speedl_stop_active_{false}; - - bool speedl_configured_{false}; -}; - -} // namespace cmvr::device - -#endif // CMVR_ES_PINOCCHIO_QP_CARTESIAN_MOTION_PLANNER_H diff --git a/cmvr-es/algorithms/motion_planner/arm_motion/cartesian_motion/pinocchio/src/pinocchio_cartesian_motion_planner.cpp b/cmvr-es/algorithms/motion_planner/arm_motion/cartesian_motion/pinocchio/src/pinocchio_cartesian_motion_planner.cpp deleted file mode 100644 index 661b771a..00000000 --- a/cmvr-es/algorithms/motion_planner/arm_motion/cartesian_motion/pinocchio/src/pinocchio_cartesian_motion_planner.cpp +++ /dev/null @@ -1,1321 +0,0 @@ -#include "algorithms/motion_planner/arm_motion/cartesian_motion/pinocchio/include/pinocchio_cartesian_motion_planner.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "algorithms/motion_planner/arm_motion/common/include/twist_limiter_config.h" -#include "algorithms/motion_planner/base_motion/motion_profile/s_curve/include/s_curve.h" -#include "common/base/logging/logger.h" -#include "common/math/cartesian_motion_math.h" -#include "common/config/config_files.h" -#include "common/math/transform_math.h" - -namespace cmvr::device { - -using cmvr::common::config::positiveOr; -using cmvr::device::cartesian_motion::clamp; -using cmvr::device::cartesian_motion::directionDeviationDeg; -using cmvr::device::cartesian_motion::lateralDistanceToLine; -using cmvr::device::cartesian_motion::rotationVector; -using cmvr::device::cartesian_motion::toEigenVector; -using cmvr::device::cartesian_motion::toStdVector; - -namespace { - -double elapsedMs(const std::chrono::steady_clock::time_point start, - const std::chrono::steady_clock::time_point end) -{ - return std::chrono::duration(end - start).count(); -} - -} // namespace - -PinocchioCartesianMotionPlanner::PinocchioCartesianMotionPlanner( - std::shared_ptr solver) - : solver_(std::move(solver)) -{ -} - -bool PinocchioCartesianMotionPlanner::refreshJointAccelerationLimits_() -{ - joint_acceleration_limits_.resize(0); - if (!solver_) { - return false; - } - const auto& limits = solver_->jointLimitPolicy().limits(); - if (limits.source() != config::JOINT_LIMIT_SOURCE_CUSTOM) { - return true; - } - - std::vector joint_names; - if (!solver_->getChainJointNames(joint_names) || joint_names.empty()) { - return false; - } - - std::unordered_map custom_limits; - custom_limits.reserve(static_cast(limits.joints_size())); - for (const auto& item : limits.joints()) { - if (!item.joint_name().empty()) { - custom_limits[item.joint_name()] = item; - } - } - - joint_acceleration_limits_.resize(static_cast(joint_names.size())); - for (Eigen::Index i = 0; i < joint_acceleration_limits_.size(); ++i) { - const auto& joint_name = joint_names[static_cast(i)]; - const auto it = custom_limits.find(joint_name); - if (it == custom_limits.end() || !std::isfinite(it->second.qdd()) || it->second.qdd() < 0.0) { - CMVR_LOG(ERROR) << "[PinocchioCartesianMotionPlanner] invalid custom qdd for " - << joint_name; - return false; - } - joint_acceleration_limits_[i] = std::abs(it->second.qdd()); - } - return true; -} - -Eigen::VectorXd PinocchioCartesianMotionPlanner::applyJointAccelerationLimits_( - const Eigen::VectorXd& qdot, - const Eigen::VectorXd& reference, - const double dt) const -{ - if (reference.size() != qdot.size() || dt <= 0.0) { - return qdot; - } - - Eigen::VectorXd limited = qdot; - for (Eigen::Index i = 0; i < qdot.size(); ++i) { - double acc_limit = 8.0; - if (joint_acceleration_limits_.size() == qdot.size() && - joint_acceleration_limits_[i] > 0.0) { - acc_limit = joint_acceleration_limits_[i]; - } - - const double delta_max = acc_limit * dt; - const double delta = clamp(qdot[i] - reference[i], -delta_max, delta_max); - limited[i] = reference[i] + delta; - } - return limited; -} - -bool PinocchioCartesianMotionPlanner::configureSpeedL(const config::SpeedLPlannerConfig& config, - const std::size_t dof) -{ - if (!solver_ || dof == 0) { - return false; - } - const auto solver_dof = static_cast(std::max(0, solver_->chainVelocityDof())); - if (solver_dof != 0 && solver_dof != dof) { - return false; - } - speedl_config_ = config; - - if (!refreshJointAccelerationLimits_()) { - return false; - } - - cartesian_motion::configureTwistLimiterFromSpeedLConfig(twist_limiter_, speedl_config_); - speedl_applied_linear_jerk_ = -1.0; - - prev_qdot_command_.assign(dof, 0.0); - speedl_command_twist_base_.setZero(); - speedl_line_check_active_ = false; - speedl_line_deviation_warned_ = false; - speedl_line_direction_warned_ = false; - speedl_stop_active_ = false; - speedl_applied_acceleration_ = positiveOr(speedl_config_.linear_acceleration_max(), 5.0); - speedl_applied_angular_acceleration_ = positiveOr(speedl_config_.angular_acceleration_max(), 5.0); - speedl_configured_ = true; - return true; -} - -bool PinocchioCartesianMotionPlanner::configureMoveL( - const config::MoveLPlannerConfig& config) -{ - if (!std::isfinite(config.sample_period_s()) || - !std::isfinite(config.position_gain()) || - !std::isfinite(config.rotation_gain())) { - return false; - } - movel_config_ = config; - return true; -} - -bool PinocchioCartesianMotionPlanner::planMoveL(const CartesianPose& target, - const std::vector& q_start, - const std::vector& qd_max, - const double velocity, - const double acceleration, - const double jerk, - const FrameType frame, - CartesianJointTrajectory& trajectory) -{ - const auto plan_start_time = std::chrono::steady_clock::now(); - double validation_ms = 0.0; - double current_pose_jacobian_ms = 0.0; - double solve_velocity_ms = 0.0; - double next_pose_jacobian_ms = 0.0; - std::size_t loop_count = 0; - struct PlanMoveLTimingLog { - std::chrono::steady_clock::time_point start_time; - double& validation_ms; - double& current_pose_jacobian_ms; - double& solve_velocity_ms; - double& next_pose_jacobian_ms; - std::size_t& loop_count; - CartesianJointTrajectory& trajectory; - - ~PlanMoveLTimingLog() - { - const auto end_time = std::chrono::steady_clock::now(); - const double total_ms = elapsedMs(start_time, end_time); - const double kinematics_ms = current_pose_jacobian_ms + next_pose_jacobian_ms; - const double measured_planning_ms = kinematics_ms + solve_velocity_ms; - const double planning_ms = std::max(0.0, total_ms - validation_ms); - const double misc_ms = std::max(0.0, planning_ms - measured_planning_ms); - const double loop_count_d = static_cast(loop_count); - const double per_loop_ms = loop_count_d > 0.0 ? planning_ms / loop_count_d : 0.0; - std::ostringstream oss; - oss << "[PinocchioCartesianMotionPlanner][moveL][plan] timing: total_ms=" - << total_ms - << ", planning_ms=" << planning_ms - << ", validation_ms=" << validation_ms - << ", kinematics_ms=" << kinematics_ms - << ", ik_ms=" << solve_velocity_ms - << ", misc_ms=" << misc_ms - << ", loops=" << loop_count - << ", per_loop_ms=" << per_loop_ms - << ", points=" << trajectory.position.size() - << ", planned_path_m=" << trajectory.planned_path_length - << ", executable_path_m=" << trajectory.executable_path_length - << ", truncated=" << trajectory.truncated; - if (trajectory.truncated && !trajectory.truncation_reason.empty()) { - oss << ", reason=" << trajectory.truncation_reason; - } - CMVR_LOG(INFO) << oss.str(); - } - } timing_log{plan_start_time, - validation_ms, - current_pose_jacobian_ms, - solve_velocity_ms, - next_pose_jacobian_ms, - loop_count, - trajectory}; - auto measure_validation = [&validation_ms](auto&& validator) { - const auto start_time = std::chrono::steady_clock::now(); - const bool result = validator(); - validation_ms += elapsedMs(start_time, std::chrono::steady_clock::now()); - return result; - }; - auto measure_planning = [](double& accumulator_ms, auto&& operation) { - const auto start_time = std::chrono::steady_clock::now(); - const bool result = operation(); - accumulator_ms += elapsedMs(start_time, std::chrono::steady_clock::now()); - return result; - }; - - trajectory = {}; - const double dt = positiveOr(movel_config_.sample_period_s(), 0.001); - if (!solver_ || q_start.empty() || - velocity <= 0.0 || acceleration <= 0.0 || jerk <= 0.0) { - return false; - } - if (static_cast(q_start.size()) != solver_->chainDof()) { - return false; - } - if (!qd_max.empty() && qd_max.size() != q_start.size()) { - return false; - } - - Eigen::Matrix4d start_pose_base = Eigen::Matrix4d::Identity(); - if (!solver_->fk(q_start, start_pose_base, true)) { - return false; - } - - const Eigen::Matrix4d target_pose_input = common::math::poseToMatrix(target); - const Eigen::Matrix4d target_pose_base = - frame == FrameType::Tool ? start_pose_base * target_pose_input : target_pose_input; - - const Eigen::Vector3d p_start = start_pose_base.block<3, 1>(0, 3); - const Eigen::Vector3d p_target = target_pose_base.block<3, 1>(0, 3); - const Eigen::Vector3d dp = p_target - p_start; - const double linear_distance = dp.norm(); - - const Eigen::Matrix3d R_start = start_pose_base.block<3, 3>(0, 0); - const Eigen::Matrix3d R_target = target_pose_base.block<3, 3>(0, 0); - const Eigen::Vector3d total_rotation_vector = rotationVector(R_target * R_start.transpose()); - const double angular_distance = total_rotation_vector.norm(); - - const double path_length = linear_distance > 1e-9 ? linear_distance : angular_distance; - trajectory.planned_path_length = path_length; - trajectory.executable_path_length = 0.0; - trajectory.position.push_back(q_start); - trajectory.velocity.push_back(std::vector(q_start.size(), 0.0)); - trajectory.time.push_back(0.0); - if (path_length <= 1e-9) { - return true; - } - - cmvr::SCurve curve(velocity, acceleration, jerk); - const cmvr::SCurveProfile profile = curve.calculateProfile(0.0, path_length, 0.0, 0.0); - if (profile.total_time <= 0.0) { - return false; - } - const auto reserve_count = - static_cast(std::ceil(profile.total_time / dt)) + 2U; - trajectory.position.reserve(reserve_count); - trajectory.velocity.reserve(reserve_count); - trajectory.time.reserve(reserve_count); - - Eigen::VectorXd q_current = toEigenVector(q_start); - Eigen::Vector3d linear_direction = Eigen::Vector3d::Zero(); - if (linear_distance > 1e-9) { - linear_direction = dp / linear_distance; - } - const Eigen::Quaterniond q_start_rot(R_start); - const Eigen::Quaterniond q_target_rot(R_target); - const double position_gain = positiveOr(movel_config_.position_gain(), 4.0); - const double rotation_gain = positiveOr(movel_config_.rotation_gain(), 4.0); - bool line_deviation_warned = false; - bool line_direction_warned = false; - double executable_path_length = 0.0; - Eigen::VectorXd prev_qdot = Eigen::VectorXd::Zero(q_current.size()); - Eigen::Matrix4d cached_current_pose_base = Eigen::Matrix4d::Identity(); - Eigen::MatrixXd cached_current_jacobian_base; - Eigen::Matrix3d cached_current_base_R_tool = Eigen::Matrix3d::Identity(); - bool cached_current_pose_valid = false; - std::vector q_std(q_start.size(), 0.0); - std::vector q_next_std(q_start.size(), 0.0); - std::vector qdot_std(q_start.size(), 0.0); - Eigen::Matrix4d current_pose_base = Eigen::Matrix4d::Identity(); - Eigen::MatrixXd jacobian_base; - Eigen::Matrix3d base_R_tool = Eigen::Matrix3d::Identity(); - Eigen::Matrix4d next_pose_base = Eigen::Matrix4d::Identity(); - Eigen::Matrix3d next_base_R_tool = Eigen::Matrix3d::Identity(); - auto copyEigenToStdVector = [](const Eigen::VectorXd& src, std::vector& dst) { - dst.resize(static_cast(src.size())); - Eigen::Map(dst.data(), src.size()) = src; - }; - - double previous_time = 0.0; - for (double t = std::min(dt, profile.total_time); - t <= profile.total_time + 1e-9; - t = std::min(t + dt, profile.total_time)) { - ++loop_count; - const double step_dt = std::max(1e-6, t - previous_time); - previous_time = t; - - const double s = clamp(curve.getPositionAtTime(profile, t), 0.0, path_length); - const double sd = std::max(0.0, curve.getVelocityAtTime(profile, t)); - const double ratio = clamp(s / path_length, 0.0, 1.0); - - copyEigenToStdVector(q_current, q_std); - if (cached_current_pose_valid) { - current_pose_base = cached_current_pose_base; - jacobian_base.swap(cached_current_jacobian_base); - base_R_tool = cached_current_base_R_tool; - } else { - if (!measure_planning(current_pose_jacobian_ms, [&]() { - return solver_->computePoseAndJacobianBaseAtQ(q_std, - true, - current_pose_base, - jacobian_base, - base_R_tool); - })) { - return false; - } - } - - const Eigen::Vector3d p_current = current_pose_base.block<3, 1>(0, 3); - const Eigen::Vector3d p_desired = p_start + ratio * dp; - std::string stop_reason; - if (!measure_validation([&]() { - return checkMoveLPlanLineDeviation_(p_start, - linear_direction, - p_current, - (p_current - p_start).norm(), - line_deviation_warned, - line_direction_warned, - stop_reason); - })) { - trajectory.truncated = true; - trajectory.truncation_reason = std::move(stop_reason); - trajectory.executable_path_length = executable_path_length; - break; - } - Eigen::Matrix target_twist_base = Eigen::Matrix::Zero(); - target_twist_base.head<3>() = - linear_direction * sd + position_gain * (p_desired - p_current); - - if (angular_distance > 1e-9) { - const Eigen::Matrix3d R_current = current_pose_base.block<3, 3>(0, 0); - const Eigen::Matrix3d R_desired = - q_start_rot.slerp(ratio, q_target_rot).toRotationMatrix(); - const Eigen::Vector3d rotation_error = - rotationVector(R_desired * R_current.transpose()); - target_twist_base.tail<3>() = - (total_rotation_vector / path_length) * sd + rotation_gain * rotation_error; - } - - if (!measure_planning(solve_velocity_ms, [&]() { - return solver_->solveVelocityBase(jacobian_base, - target_twist_base, - q_std, - qdot_std, - std::numeric_limits::infinity()); - })) { - return false; - } - - Eigen::Map qdot(qdot_std.data(), - static_cast(qdot_std.size())); - Eigen::VectorXd qdot_limited = qdot; - if (!qd_max.empty()) { - double scale = 1.0; - for (Eigen::Index i = 0; i < qdot_limited.size(); ++i) { - const double limit = std::abs(qd_max[static_cast(i)]); - if (limit <= 0.0 || !std::isfinite(limit)) { - continue; - } - const double value = std::abs(qdot_limited[i]); - if (value > limit) { - scale = std::min(scale, limit / value); - } - } - qdot_limited *= scale; - } - const Eigen::Matrix achieved_twist_base = jacobian_base * qdot_limited; - if (!measure_validation([&]() { - return checkMoveLPlanCartesianStepFeasibility_(target_twist_base, - achieved_twist_base, - s, - stop_reason); - })) { - trajectory.truncated = true; - trajectory.truncation_reason = std::move(stop_reason); - trajectory.executable_path_length = executable_path_length; - break; - } - const Eigen::VectorXd q_next = q_current + qdot_limited * step_dt; - if (!measure_validation([&]() { - return checkMoveLPlanJointContinuity_(q_current, - q_next, - qdot_limited, - prev_qdot, - step_dt, - s, - stop_reason); - })) { - trajectory.truncated = true; - trajectory.truncation_reason = std::move(stop_reason); - trajectory.executable_path_length = executable_path_length; - break; - } - if (!measure_validation([&]() { - return checkMoveLPlanJointPositionLimits_(q_current, - q_next, - qdot_limited, - step_dt, - s, - stop_reason); - })) { - trajectory.truncated = true; - trajectory.truncation_reason = std::move(stop_reason); - trajectory.executable_path_length = executable_path_length; - break; - } - - copyEigenToStdVector(q_next, q_next_std); - if (!measure_planning(next_pose_jacobian_ms, [&]() { - return solver_->computePoseAndJacobianBaseAtQ(q_next_std, - true, - next_pose_base, - cached_current_jacobian_base, - next_base_R_tool); - })) { - return false; - } - const Eigen::Vector3d p_next = next_pose_base.block<3, 1>(0, 3); - if (!measure_validation([&]() { - return checkMoveLPlanLineDeviation_(p_start, - linear_direction, - p_next, - (p_next - p_start).norm(), - line_deviation_warned, - line_direction_warned, - stop_reason); - })) { - trajectory.truncated = true; - trajectory.truncation_reason = std::move(stop_reason); - trajectory.executable_path_length = executable_path_length; - break; - } - - q_current = q_next; - prev_qdot = qdot_limited; - cached_current_pose_base = next_pose_base; - cached_current_base_R_tool = next_base_R_tool; - cached_current_pose_valid = true; - - trajectory.position.push_back(toStdVector(q_current)); - trajectory.velocity.push_back(toStdVector(qdot_limited)); - trajectory.time.push_back(t); - executable_path_length = s; - trajectory.executable_path_length = executable_path_length; - - if (t >= profile.total_time - 1e-9) { - break; - } - } - if (!trajectory.truncated) { - trajectory.executable_path_length = path_length; - } - - return true; -} - -bool PinocchioCartesianMotionPlanner::checkMoveLPlanJointContinuity_( - const Eigen::VectorXd& q_current, - const Eigen::VectorXd& q_next, - const Eigen::VectorXd& qdot, - const Eigen::VectorXd& prev_qdot, - const double dt, - const double path_position, - std::string& stop_reason) const -{ - const auto& config = movel_config_.joint_continuity_check(); - if (!config.enable()) { - return true; - } - if (q_current.size() != q_next.size() || - q_current.size() != qdot.size() || - qdot.size() != prev_qdot.size() || - dt <= 0.0 || !std::isfinite(dt)) { - stop_reason = "joint continuity invalid state"; - CMVR_LOG(WARNING) << "[PinocchioCartesianMotionPlanner][moveL][plan] joint continuity invalid state"; - return false; - } - - for (Eigen::Index i = 0; i < q_next.size(); ++i) { - if (!std::isfinite(q_current[i]) || - !std::isfinite(q_next[i]) || - !std::isfinite(qdot[i]) || - !std::isfinite(prev_qdot[i])) { - std::ostringstream oss; - oss << "joint continuity non-finite value: joint_index=" << i - << ", path_position_m=" << path_position; - stop_reason = oss.str(); - CMVR_LOG(WARNING) << "[PinocchioCartesianMotionPlanner][moveL][plan] " - << stop_reason; - return false; - } - } - - const double max_delta = (q_next - q_current).cwiseAbs().maxCoeff(); - const double max_velocity = qdot.cwiseAbs().maxCoeff(); - const double max_acceleration = ((qdot - prev_qdot) / dt).cwiseAbs().maxCoeff(); - const double delta_limit = positiveOr(config.max_joint_delta_rad(), 0.05); - const double velocity_limit = positiveOr(config.max_joint_velocity_rad_s(), 10.0); - const double acceleration_limit = positiveOr(config.max_joint_acceleration_rad_s2(), 5000.0); - - if (max_delta > delta_limit || - max_velocity > velocity_limit || - max_acceleration > acceleration_limit) { - CMVR_LOG(WARNING) << "[PinocchioCartesianMotionPlanner][moveL][plan] joint continuity exceeds stop threshold: max_delta_rad=" - << max_delta << ", delta_limit_rad=" << delta_limit - << ", max_velocity_rad_s=" << max_velocity - << ", velocity_limit_rad_s=" << velocity_limit - << ", max_acceleration_rad_s2=" << max_acceleration - << ", acceleration_limit_rad_s2=" << acceleration_limit - << ", path_position_m=" << path_position; - std::ostringstream oss; - oss << "joint continuity too large: max_delta_rad=" << max_delta - << ", delta_limit_rad=" << delta_limit - << ", max_velocity_rad_s=" << max_velocity - << ", velocity_limit_rad_s=" << velocity_limit - << ", max_acceleration_rad_s2=" << max_acceleration - << ", acceleration_limit_rad_s2=" << acceleration_limit - << ", path_position_m=" << path_position; - stop_reason = oss.str(); - return false; - } - return true; -} - -bool PinocchioCartesianMotionPlanner::checkMoveLPlanJointPositionLimits_( - const Eigen::VectorXd& q_current, - const Eigen::VectorXd& q_next, - const Eigen::VectorXd& qdot, - const double dt, - const double path_position, - std::string& stop_reason) const -{ - if (!solver_ || !solver_->jointLimitPolicy().limits().enable()) { - return true; - } - if (q_current.size() != q_next.size() || - q_current.size() != qdot.size()) { - stop_reason = "joint position limit check size mismatch"; - CMVR_LOG(WARNING) << "[PinocchioCartesianMotionPlanner][moveL][plan] " - << stop_reason; - return false; - } - - Eigen::VectorXd lower; - Eigen::VectorXd upper; - if (!solver_->getJointPositionLimits(lower, upper) || - lower.size() != q_next.size() || - upper.size() != q_next.size()) { - return true; - } - - std::vector joint_names; - (void)solver_->getChainJointNames(joint_names); - constexpr double kLimitEps = 1e-6; - for (Eigen::Index i = 0; i < q_next.size(); ++i) { - const double q = q_current[i]; - const double qn = q_next[i]; - const double lo = lower[i]; - const double hi = upper[i]; - if (!std::isfinite(q) || !std::isfinite(qn) || - !std::isfinite(lo) || !std::isfinite(hi) || hi <= lo) { - continue; - } - - const bool violates_lower = qn < lo - kLimitEps; - const bool violates_upper = qn > hi + kLimitEps; - const bool moves_out_lower = q <= lo + kLimitEps && qdot[i] < -kLimitEps; - const bool moves_out_upper = q >= hi - kLimitEps && qdot[i] > kLimitEps; - if (violates_lower || violates_upper || moves_out_lower || moves_out_upper) { - const std::string joint_name = - static_cast(i) < joint_names.size() - ? joint_names[static_cast(i)] - : std::to_string(i); - CMVR_LOG(WARNING) << "[PinocchioCartesianMotionPlanner][moveL][plan] predicted joint position limit exceeded: joint=" - << joint_name << ", q=" << q - << ", q_next=" << qn - << ", lower=" << lo - << ", upper=" << hi - << ", qdot=" << qdot[i] - << ", dt=" << dt - << ", path_position_m=" << path_position; - std::ostringstream oss; - oss << "joint position limit exceeded: joint=" << joint_name - << ", q=" << q - << ", q_next=" << qn - << ", lower=" << lo - << ", upper=" << hi - << ", qdot=" << qdot[i] - << ", dt=" << dt - << ", path_position_m=" << path_position; - stop_reason = oss.str(); - return false; - } - } - return true; -} - -bool PinocchioCartesianMotionPlanner::checkMoveLPlanCartesianStepFeasibility_( - const Eigen::Matrix& desired_twist, - const Eigen::Matrix& achieved_twist, - const double path_position, - std::string& stop_reason) const -{ - const auto& config = movel_config_.cartesian_step_feasibility_check(); - if (!config.enable()) { - return true; - } - - const Eigen::Vector3d desired_linear = desired_twist.head<3>(); - const Eigen::Vector3d achieved_linear = achieved_twist.head<3>(); - const double desired_linear_norm = desired_linear.norm(); - const double achieved_linear_norm = achieved_linear.norm(); - const double min_desired_linear_speed = - positiveOr(config.min_desired_linear_speed(), 1e-4); - if (desired_linear_norm >= min_desired_linear_speed) { - const double speed_ratio = achieved_linear_norm / desired_linear_norm; - const double min_ratio = positiveOr(config.min_linear_speed_ratio(), 0.2); - const double deviation_deg = - achieved_linear_norm > 1e-9 - ? directionDeviationDeg(desired_linear, achieved_linear) - : 180.0; - const double max_deviation_deg = - positiveOr(config.max_linear_direction_deviation_deg(), 45.0); - if (speed_ratio < min_ratio || deviation_deg > max_deviation_deg) { - CMVR_LOG(WARNING) << "[PinocchioCartesianMotionPlanner][moveL][plan] cartesian step infeasible after joint limits: desired_linear=[" - << desired_linear.transpose() << "], achieved_linear=[" - << achieved_linear.transpose() << "], speed_ratio=" - << speed_ratio << ", min_ratio=" << min_ratio - << ", deviation_deg=" << deviation_deg - << ", max_deviation_deg=" << max_deviation_deg - << ", path_position_m=" << path_position; - std::ostringstream oss; - oss << "cartesian step infeasible after joint limits: linear_speed_ratio=" - << speed_ratio << ", min_ratio=" << min_ratio - << ", linear_deviation_deg=" << deviation_deg - << ", max_deviation_deg=" << max_deviation_deg - << ", path_position_m=" << path_position; - stop_reason = oss.str(); - return false; - } - } - - const Eigen::Vector3d desired_angular = desired_twist.tail<3>(); - const Eigen::Vector3d achieved_angular = achieved_twist.tail<3>(); - const double desired_angular_norm = desired_angular.norm(); - const double achieved_angular_norm = achieved_angular.norm(); - const double min_desired_angular_speed = - positiveOr(config.min_desired_angular_speed(), 1e-4); - if (desired_angular_norm >= min_desired_angular_speed) { - const double speed_ratio = achieved_angular_norm / desired_angular_norm; - const double min_ratio = positiveOr(config.min_angular_speed_ratio(), 0.2); - const double deviation_deg = - achieved_angular_norm > 1e-9 - ? directionDeviationDeg(desired_angular, achieved_angular) - : 180.0; - const double max_deviation_deg = - positiveOr(config.max_angular_direction_deviation_deg(), 45.0); - if (speed_ratio < min_ratio || deviation_deg > max_deviation_deg) { - CMVR_LOG(WARNING) << "[PinocchioCartesianMotionPlanner][moveL][plan] cartesian angular step infeasible after joint limits: desired_angular=[" - << desired_angular.transpose() << "], achieved_angular=[" - << achieved_angular.transpose() << "], speed_ratio=" - << speed_ratio << ", min_ratio=" << min_ratio - << ", deviation_deg=" << deviation_deg - << ", max_deviation_deg=" << max_deviation_deg - << ", path_position_m=" << path_position; - std::ostringstream oss; - oss << "cartesian angular step infeasible after joint limits: angular_speed_ratio=" - << speed_ratio << ", min_ratio=" << min_ratio - << ", angular_deviation_deg=" << deviation_deg - << ", max_deviation_deg=" << max_deviation_deg - << ", path_position_m=" << path_position; - stop_reason = oss.str(); - return false; - } - } - - return true; -} - -bool PinocchioCartesianMotionPlanner::checkMoveLPlanLineDeviation_( - const Eigen::Vector3d& p_start, - const Eigen::Vector3d& line_direction, - const Eigen::Vector3d& p_current, - const double traveled, - bool& deviation_warned, - bool& direction_warned, - std::string& stop_reason) const -{ - const auto& config = movel_config_.line_deviation_check(); - if (!config.enable() || line_direction.squaredNorm() <= 1e-12) { - return true; - } - - const double min_distance = positiveOr(config.line_check_min_distance_m(), 0.01); - if (traveled < min_distance) { - return true; - } - - const double lateral_error = lateralDistanceToLine(p_start, line_direction, p_current); - const double stop_m = positiveOr(config.line_deviation_stop_m(), 0.03); - if (lateral_error >= stop_m) { - CMVR_LOG(WARNING) << "[PinocchioCartesianMotionPlanner][moveL][plan] line deviation exceeds stop threshold: lateral_error_m=" - << lateral_error << ", stop_m=" << stop_m - << ", traveled_m=" << traveled; - deviation_warned = true; - std::ostringstream oss; - oss << "line deviation too large: lateral_error_m=" << lateral_error - << ", stop_m=" << stop_m - << ", traveled_m=" << traveled; - stop_reason = oss.str(); - return false; - } - - const double warn_m = positiveOr(config.line_deviation_warn_m(), 0.01); - if (!deviation_warned && lateral_error >= warn_m) { - CMVR_LOG(WARNING) << "[PinocchioCartesianMotionPlanner][moveL][plan] line deviation warning: lateral_error_m=" - << lateral_error << ", warn_m=" << warn_m - << ", traveled_m=" << traveled; - deviation_warned = true; - } - - const Eigen::Vector3d actual_direction = (p_current - p_start) / traveled; - const double deviation_deg = directionDeviationDeg(line_direction, actual_direction); - const double stop_deg = positiveOr(config.line_direction_stop_deg(), 45.0); - if (deviation_deg >= stop_deg) { - CMVR_LOG(WARNING) << "[PinocchioCartesianMotionPlanner][moveL][plan] line direction deviation exceeds stop threshold: deviation_deg=" - << deviation_deg << ", stop_deg=" << stop_deg - << ", traveled_m=" << traveled; - direction_warned = true; - std::ostringstream oss; - oss << "line direction deviation too large: deviation_deg=" << deviation_deg - << ", stop_deg=" << stop_deg - << ", traveled_m=" << traveled; - stop_reason = oss.str(); - return false; - } - - const double warn_deg = positiveOr(config.line_direction_warn_deg(), 20.0); - if (!direction_warned && deviation_deg >= warn_deg) { - CMVR_LOG(WARNING) << "[PinocchioCartesianMotionPlanner][moveL][plan] line direction deviation warning: deviation_deg=" - << deviation_deg << ", warn_deg=" << warn_deg - << ", traveled_m=" << traveled; - direction_warned = true; - } - return true; -} - -bool PinocchioCartesianMotionPlanner::updateAndValidateSpeedLLineDeviation_( - const std::vector& q_measured, - const bool is_stop_command, - const Eigen::Vector3d& command_linear_base) -{ - const auto& config = speedl_config_.line_deviation_check(); - if (!config.enable()) { - return true; - } - - const double command_norm = command_linear_base.norm(); - if (is_stop_command || command_norm <= 1e-9) { - speedl_line_check_active_ = false; - speedl_line_deviation_warned_ = false; - speedl_line_direction_warned_ = false; - return true; - } - - Eigen::Matrix4d tcp_pose_base = Eigen::Matrix4d::Identity(); - if (!solver_->fk(q_measured, tcp_pose_base, true)) { - CMVR_LOG(ERROR) << "[PinocchioCartesianMotionPlanner][speedL] line check FK failed"; - return false; - } - const Eigen::Vector3d tcp_position = tcp_pose_base.block<3, 1>(0, 3); - const Eigen::Vector3d command_direction = command_linear_base / command_norm; - - bool reset_line = !speedl_line_check_active_; - if (!reset_line && speedl_line_direction_base_.squaredNorm() > 1e-12) { - const double reset_deg = positiveOr(config.line_direction_reset_deg(), 10.0); - const double command_change_deg = - directionDeviationDeg(speedl_line_direction_base_, command_direction); - reset_line = command_change_deg >= reset_deg; - } - - if (reset_line) { - speedl_line_start_tcp_base_ = tcp_position; - speedl_line_direction_base_ = command_direction; - speedl_line_check_active_ = true; - speedl_line_deviation_warned_ = false; - speedl_line_direction_warned_ = false; - return true; - } - - const Eigen::Vector3d delta = tcp_position - speedl_line_start_tcp_base_; - const double traveled = delta.norm(); - const double min_distance = positiveOr(config.line_check_min_distance_m(), 0.01); - if (traveled < min_distance) { - return true; - } - - const double lateral_error = - lateralDistanceToLine(speedl_line_start_tcp_base_, speedl_line_direction_base_, tcp_position); - const double stop_m = positiveOr(config.line_deviation_stop_m(), 0.03); - if (lateral_error >= stop_m) { - CMVR_LOG(ERROR) << "[PinocchioCartesianMotionPlanner][speedL] line deviation too large: lateral_error_m=" - << lateral_error << ", stop_m=" << stop_m - << ", traveled_m=" << traveled; - return false; - } - - const double warn_m = positiveOr(config.line_deviation_warn_m(), 0.01); - if (!speedl_line_deviation_warned_ && lateral_error >= warn_m) { - CMVR_LOG(WARNING) << "[PinocchioCartesianMotionPlanner][speedL] line deviation warning: lateral_error_m=" - << lateral_error << ", warn_m=" << warn_m - << ", traveled_m=" << traveled; - speedl_line_deviation_warned_ = true; - } - - const Eigen::Vector3d actual_direction = delta / traveled; - const double deviation_deg = - directionDeviationDeg(speedl_line_direction_base_, actual_direction); - const double stop_deg = positiveOr(config.line_direction_stop_deg(), 45.0); - if (deviation_deg >= stop_deg) { - CMVR_LOG(ERROR) << "[PinocchioCartesianMotionPlanner][speedL] line direction deviation too large: deviation_deg=" - << deviation_deg << ", stop_deg=" << stop_deg - << ", traveled_m=" << traveled; - return false; - } - - const double warn_deg = positiveOr(config.line_direction_warn_deg(), 20.0); - if (!speedl_line_direction_warned_ && deviation_deg >= warn_deg) { - CMVR_LOG(WARNING) << "[PinocchioCartesianMotionPlanner][speedL] line direction deviation warning: deviation_deg=" - << deviation_deg << ", warn_deg=" << warn_deg - << ", traveled_m=" << traveled; - speedl_line_direction_warned_ = true; - } - - return true; -} - -bool PinocchioCartesianMotionPlanner::speedLStep(const CartesianVelocity& target_velocity, - const double dt, - const std::vector& q_measured, - const std::vector& qd_measured, - std::vector& qd_command, - const FrameType frame) -{ - qd_command.clear(); - if (!solver_ || !speedl_configured_ || dt <= 0.0) { - CMVR_LOG(ERROR) << "[PinocchioCartesianMotionPlanner][speedL] invalid state: solver=" - << (solver_ ? 1 : 0) - << ", configured=" << (speedl_configured_ ? 1 : 0) - << ", dt=" << dt; - return false; - } - if (static_cast(q_measured.size()) != solver_->chainDof() || - static_cast(qd_measured.size()) != solver_->chainVelocityDof()) { - CMVR_LOG(ERROR) << "[PinocchioCartesianMotionPlanner][speedL] state size mismatch: q=" - << q_measured.size() << "/" << solver_->chainDof() - << ", qd=" << qd_measured.size() << "/" << solver_->chainVelocityDof(); - return false; - } - - Eigen::Matrix measured_twist_base = Eigen::Matrix::Zero(); - Eigen::MatrixXd jacobian_base; - Eigen::Matrix3d base_R_tool = Eigen::Matrix3d::Identity(); - if (!solver_->computeTwistBaseAtQ(q_measured, - qd_measured, - true, - measured_twist_base, - &jacobian_base, - &base_R_tool)) { - CMVR_LOG(ERROR) << "[PinocchioCartesianMotionPlanner][speedL] computeTwistBaseAtQ failed"; - return false; - } - - const Eigen::Matrix target_twist = - common::math::velocityToVector(target_velocity); - - const bool is_stop_command = - target_twist.squaredNorm() <= 1e-12; - - if (is_stop_command) { - if (!speedl_stop_active_) { - // 只在 stop 边沿执行一次。 - // - // 非常重要: - // 不再调用 - // twist_limiter_.synchronize(measured_twist_base, dt, true); - // - // 停止应当从“上一拍已经发送出去的 command twist” - // 连续规划到 0,而不是每 1 ms 被 measured twist 重新点燃。 - speedl_stop_active_ = true; - - twist_limiter_.stop(); - } - } else { - // 收到新的非零 speedL,退出停止状态。 - speedl_stop_active_ = false; - - // 从静止开始一个新的 speedL command。 - if (speedl_command_twist_base_.squaredNorm() <= 1e-12 && - (!twist_limiter_.continuousLinearReversalEnabled() || !twist_limiter_.isMoving())) { - twist_limiter_.initialize( - Eigen::Matrix::Zero()); - } - - twist_limiter_.setTargetTwist( - target_twist, - common::math::toPlannerFrame(frame)); - } - - speedl_command_twist_base_ = - twist_limiter_.update(dt, base_R_tool); - if (!updateAndValidateSpeedLLineDeviation_(q_measured, - is_stop_command, - speedl_command_twist_base_.head<3>())) { - CMVR_LOG(ERROR) << "[PinocchioCartesianMotionPlanner][speedL] line deviation check failed"; - return false; - } - - Eigen::VectorXd reference = toEigenVector(qd_measured); - if (prev_qdot_command_.size() == q_measured.size()) { - reference = toEigenVector(prev_qdot_command_); - } - - const bool enforce_acceleration_limits = - !speedl_config_.has_enforce_joint_acceleration_limits() || - speedl_config_.enforce_joint_acceleration_limits(); - std::vector qdot_std; - if (!solver_->solveVelocityBase(jacobian_base, - speedl_command_twist_base_, - q_measured, - qdot_std, - std::numeric_limits::infinity())) { - CMVR_LOG(ERROR) << "[PinocchioCartesianMotionPlanner][speedL] solveVelocityBase failed"; - return false; - } - Eigen::VectorXd qdot = toEigenVector(qdot_std); - if (enforce_acceleration_limits) { - qdot = applyJointAccelerationLimits_(qdot, reference, dt); - } - const Eigen::Matrix achieved_twist_base = jacobian_base * qdot; - // During a stop, the limiter intentionally commands a near-zero residual - // twist while the measured arm can still be moving in a different direction. - // Direction and speed-ratio checks are not meaningful for that transient. - if (!is_stop_command && - !validateSpeedLCartesianVelocityFeasibility_(speedl_command_twist_base_, - achieved_twist_base, - toEigenVector(q_measured), - qdot)) { - CMVR_LOG(ERROR) << "[PinocchioCartesianMotionPlanner][speedL] cartesian velocity feasibility check failed"; - return false; - } - if (!validateSpeedLJointVelocityCommand_(qdot, reference, dt)) { - CMVR_LOG(ERROR) << "[PinocchioCartesianMotionPlanner][speedL] joint velocity check failed"; - return false; - } - if (!validateSpeedLPredictedJointPositionLimits_(q_measured, qdot, dt)) { - CMVR_LOG(ERROR) << "[PinocchioCartesianMotionPlanner][speedL] predicted joint position limit check failed"; - return false; - } - const Eigen::VectorXd q_predicted = toEigenVector(q_measured) + qdot * dt; - if (!updateAndValidateSpeedLLineDeviation_(toStdVector(q_predicted), - is_stop_command, - speedl_command_twist_base_.head<3>())) { - CMVR_LOG(ERROR) << "[PinocchioCartesianMotionPlanner][speedL] predicted line deviation check failed"; - return false; - } - - qd_command = toStdVector(qdot); - prev_qdot_command_ = qd_command; - return true; -} - -bool PinocchioCartesianMotionPlanner::validateSpeedLJointVelocityCommand_( - const Eigen::VectorXd& qdot, - const Eigen::VectorXd& reference, - const double dt) const -{ - const auto& config = speedl_config_.joint_velocity_check(); - if (!config.enable()) { - return true; - } - if (qdot.size() <= 0 || qdot.size() != reference.size() || - dt <= 0.0 || !std::isfinite(dt)) { - CMVR_LOG(ERROR) << "[PinocchioCartesianMotionPlanner][speedL] joint velocity check invalid state: qdot_size=" - << qdot.size() << ", reference_size=" << reference.size() - << ", dt=" << dt; - return false; - } - - for (Eigen::Index i = 0; i < qdot.size(); ++i) { - if (!std::isfinite(qdot[i]) || !std::isfinite(reference[i])) { - CMVR_LOG(ERROR) << "[PinocchioCartesianMotionPlanner][speedL] joint velocity command non-finite: joint_index=" - << i << ", qdot=" << qdot[i] - << ", reference=" << reference[i]; - return false; - } - } - - const double max_velocity = qdot.cwiseAbs().maxCoeff(); - const double max_acceleration = ((qdot - reference) / dt).cwiseAbs().maxCoeff(); - const double velocity_limit = positiveOr(config.max_joint_velocity_rad_s(), 30.0); - const double acceleration_limit = positiveOr(config.max_joint_acceleration_rad_s2(), 10000.0); - if (max_velocity > velocity_limit || max_acceleration > acceleration_limit) { - CMVR_LOG(ERROR) << "[PinocchioCartesianMotionPlanner][speedL] joint velocity command exceeds threshold: max_joint_velocity_rad_s=" - << max_velocity << ", velocity_limit_rad_s=" << velocity_limit - << ", max_joint_acceleration_rad_s2=" << max_acceleration - << ", acceleration_limit_rad_s2=" << acceleration_limit - << ", dt=" << dt; - return false; - } - return true; -} - -bool PinocchioCartesianMotionPlanner::validateSpeedLPredictedJointPositionLimits_( - const std::vector& q_measured, - const Eigen::VectorXd& qdot, - const double dt) const -{ - if (!solver_ || !solver_->jointLimitPolicy().limits().enable()) { - return true; - } - if (static_cast(q_measured.size()) != qdot.size()) { - CMVR_LOG(ERROR) << "[PinocchioCartesianMotionPlanner][speedL] joint position limit check size mismatch: q=" - << q_measured.size() << ", qdot=" << qdot.size(); - return false; - } - - Eigen::VectorXd lower; - Eigen::VectorXd upper; - if (!solver_->getJointPositionLimits(lower, upper) || - lower.size() != qdot.size() || - upper.size() != qdot.size()) { - return true; - } - - std::vector joint_names; - (void)solver_->getChainJointNames(joint_names); - constexpr double kLimitEps = 1e-6; - for (Eigen::Index i = 0; i < qdot.size(); ++i) { - const double q = q_measured[static_cast(i)]; - const double q_next = q + qdot[i] * dt; - const double lo = lower[i]; - const double hi = upper[i]; - if (!std::isfinite(q) || !std::isfinite(q_next) || - !std::isfinite(lo) || !std::isfinite(hi) || hi <= lo) { - continue; - } - - const bool violates_lower = q_next < lo - kLimitEps; - const bool violates_upper = q_next > hi + kLimitEps; - const bool moves_out_lower = q <= lo + kLimitEps && qdot[i] < -kLimitEps; - const bool moves_out_upper = q >= hi - kLimitEps && qdot[i] > kLimitEps; - if (violates_lower || violates_upper || moves_out_lower || moves_out_upper) { - const std::string joint_name = - static_cast(i) < joint_names.size() - ? joint_names[static_cast(i)] - : std::to_string(i); - CMVR_LOG(ERROR) << "[PinocchioCartesianMotionPlanner][speedL] predicted joint position limit exceeded: joint=" - << joint_name << ", q=" << q - << ", q_next=" << q_next - << ", lower=" << lo - << ", upper=" << hi - << ", qdot=" << qdot[i] - << ", dt=" << dt; - return false; - } - } - return true; -} - -bool PinocchioCartesianMotionPlanner::validateSpeedLCartesianVelocityFeasibility_( - const Eigen::Matrix& desired_twist, - const Eigen::Matrix& achieved_twist, - const Eigen::VectorXd& q_current, - const Eigen::VectorXd& qdot) const -{ - const auto& config = speedl_config_.cartesian_velocity_feasibility_check(); - if (!config.enable()) { - return true; - } - - const Eigen::Vector3d desired_linear = desired_twist.head<3>(); - const Eigen::Vector3d achieved_linear = achieved_twist.head<3>(); - const double desired_linear_norm = desired_linear.norm(); - const double achieved_linear_norm = achieved_linear.norm(); - const double min_desired_linear_speed = - positiveOr(config.min_desired_linear_speed(), 1e-4); - if (desired_linear_norm >= min_desired_linear_speed) { - const double speed_ratio = achieved_linear_norm / desired_linear_norm; - const double min_ratio = positiveOr(config.min_linear_speed_ratio(), 0.2); - const double deviation_deg = - achieved_linear_norm > 1e-9 - ? directionDeviationDeg(desired_linear, achieved_linear) - : 180.0; - const double max_deviation_deg = - positiveOr(config.max_linear_direction_deviation_deg(), 45.0); - if (speed_ratio < min_ratio || deviation_deg > max_deviation_deg) { - CMVR_LOG(ERROR) << "[PinocchioCartesianMotionPlanner][speedL] cartesian velocity infeasible after joint limits " << "limit_candidates=[" - << describeJointLimitCandidates_(q_current, qdot) << "]: desired_linear=[" - << desired_linear.transpose() << "], achieved_linear=[" - << achieved_linear.transpose() << "], speed_ratio=" - << speed_ratio << ", min_ratio=" << min_ratio - << ", deviation_deg=" << deviation_deg - << ", max_deviation_deg=" << max_deviation_deg - ; - return false; - } - } - - const Eigen::Vector3d desired_angular = desired_twist.tail<3>(); - const Eigen::Vector3d achieved_angular = achieved_twist.tail<3>(); - const double desired_angular_norm = desired_angular.norm(); - const double achieved_angular_norm = achieved_angular.norm(); - const double min_desired_angular_speed = - positiveOr(config.min_desired_angular_speed(), 1e-4); - if (desired_angular_norm >= min_desired_angular_speed) { - const double speed_ratio = achieved_angular_norm / desired_angular_norm; - const double min_ratio = positiveOr(config.min_angular_speed_ratio(), 0.2); - const double deviation_deg = - achieved_angular_norm > 1e-9 - ? directionDeviationDeg(desired_angular, achieved_angular) - : 180.0; - const double max_deviation_deg = - positiveOr(config.max_angular_direction_deviation_deg(), 45.0); - if (speed_ratio < min_ratio || deviation_deg > max_deviation_deg) { - CMVR_LOG(ERROR) << "[PinocchioCartesianMotionPlanner][speedL] cartesian angular velocity infeasible after joint limits: desired_angular=[" - << desired_angular.transpose() << "], achieved_angular=[" - << achieved_angular.transpose() << "], speed_ratio=" - << speed_ratio << ", min_ratio=" << min_ratio - << ", deviation_deg=" << deviation_deg - << ", max_deviation_deg=" << max_deviation_deg - << ", limit_candidates=[" - << describeJointLimitCandidates_(q_current, qdot) << "]"; - return false; - } - } - - return true; -} - -std::string PinocchioCartesianMotionPlanner::describeJointLimitCandidates_( - const Eigen::VectorXd& q_current, - const Eigen::VectorXd& qdot) const -{ - if (!solver_ || q_current.size() != qdot.size()) { - return "none"; - } - - std::vector joint_names; - (void)solver_->getChainJointNames(joint_names); - - Eigen::VectorXd qd_limits; - const bool has_qd_limits = - solver_->getJointVelocityLimits(qd_limits) && qd_limits.size() == qdot.size(); - Eigen::VectorXd lower; - Eigen::VectorXd upper; - const bool has_q_limits = - solver_->getJointPositionLimits(lower, upper) && - lower.size() == q_current.size() && - upper.size() == q_current.size(); - - std::vector candidates; - constexpr double kVelocityRatio = 0.98; - for (Eigen::Index i = 0; i < qdot.size(); ++i) { - const std::string joint_name = - static_cast(i) < joint_names.size() - ? joint_names[static_cast(i)] - : std::to_string(i); - - std::vector reasons; - if (has_qd_limits) { - const double qd_limit = std::abs(qd_limits[i]); - if (std::isfinite(qd_limit) && qd_limit > 0.0 && - std::abs(qdot[i]) >= kVelocityRatio * qd_limit) { - std::ostringstream oss; - oss << "qd=" << qdot[i] << "/" << qd_limit; - reasons.push_back(oss.str()); - } - } - - if (has_q_limits) { - const double q = q_current[i]; - const double lo = lower[i]; - const double hi = upper[i]; - if (std::isfinite(q) && std::isfinite(lo) && std::isfinite(hi) && hi > lo) { - const double margin = std::max(0.02, 0.02 * (hi - lo)); - if (q <= lo + margin) { - std::ostringstream oss; - oss << "near_lower q=" << q << "/" << lo; - reasons.push_back(oss.str()); - } - if (q >= hi - margin) { - std::ostringstream oss; - oss << "near_upper q=" << q << "/" << hi; - reasons.push_back(oss.str()); - } - } - } - - if (!reasons.empty()) { - std::ostringstream item; - item << joint_name << "("; - for (std::size_t j = 0; j < reasons.size(); ++j) { - if (j > 0) { - item << "; "; - } - item << reasons[j]; - } - item << ")"; - candidates.push_back(item.str()); - } - } - - if (candidates.empty()) { - return "none"; - } - std::ostringstream oss; - for (std::size_t i = 0; i < candidates.size(); ++i) { - if (i > 0) { - oss << ", "; - } - oss << candidates[i]; - } - return oss.str(); -} - -bool PinocchioCartesianMotionPlanner::updateSpeedLAcceleration(const double acceleration) -{ - SpeedLOptions options; - options.acceleration = acceleration; - return updateSpeedLLimits(options); -} - -bool PinocchioCartesianMotionPlanner::updateSpeedLLimits(const SpeedLOptions& options) -{ - const double jerk_max = positiveOr(speedl_config_.linear_jerk_max(), 10.0); - const double requested_jerk = options.linear_jerk.value_or(jerk_max); - // Validate before clamping: invalid requests must not become valid limits. - if (!speedl_configured_ || !std::isfinite(options.acceleration) || options.acceleration <= 0.0 || - !std::isfinite(requested_jerk) || requested_jerk <= 0.0) { - return false; - } - const double acceleration = std::min(options.acceleration, - positiveOr(speedl_config_.linear_acceleration_max(), 5.0)); - const double angular_acceleration = std::min(options.acceleration, - positiveOr(speedl_config_.angular_acceleration_max(), 5.0)); - const double jerk = std::min(requested_jerk, jerk_max); - // Apply the command's motion policy even when acceleration/jerk are - // unchanged. PBVS streams directions; contact retraction locks an axis. - twist_limiter_.setContinuousLinearReversal(options.continuous_linear_reversal.value_or( - !speedl_config_.has_continuous_linear_reversal() || speedl_config_.continuous_linear_reversal())); - if (std::abs(speedl_applied_acceleration_ - acceleration) <= 1e-9 && - std::abs(speedl_applied_angular_acceleration_ - angular_acceleration) <= 1e-9 && - std::abs(speedl_applied_linear_jerk_ - jerk) <= 1e-9) { - return true; - } - - twist_limiter_.setLinearConstraints( - positiveOr(speedl_config_.linear_velocity_max(), .55), - acceleration, jerk); - twist_limiter_.setAngularConstraints( - positiveOr(speedl_config_.angular_velocity_max(), 1.0), - angular_acceleration, positiveOr(speedl_config_.angular_jerk_max(), 12.0)); - speedl_applied_acceleration_ = acceleration; - speedl_applied_angular_acceleration_ = angular_acceleration; - speedl_applied_linear_jerk_ = jerk; - return true; -} - -bool PinocchioCartesianMotionPlanner::captureSpeedLReference( - const std::vector& q, const CartesianVelocity& target, - const FrameType frame, SpeedLReference& reference) -{ - Eigen::Matrix4d pose; - if (!solver_ || !solver_->fk(q, pose, true) || !pose.allFinite()) return false; - auto twist = common::math::velocityToVector(target); - if (frame == FrameType::Tool) { - const Eigen::Matrix3d rotation = pose.block<3, 3>(0, 0); - twist.head<3>() = rotation * twist.head<3>().eval(); - twist.tail<3>() = rotation * twist.tail<3>().eval(); - } else if (frame != FrameType::Base) { - return false; - } - reference.tcp_pose_base = common::math::matrixToPose(pose); - reference.target_base = common::math::vectorToVelocity(twist); - reference.valid = true; - return true; -} - -CartesianVelocity PinocchioCartesianMotionPlanner::getSpeedLCommandTwistBase() const -{ - return common::math::vectorToVelocity(speedl_command_twist_base_); -} - -} // namespace cmvr::device diff --git a/cmvr-es/algorithms/motion_planner/arm_motion/cartesian_motion/pinocchio/test/pinocchio_speedl_limits_test.cpp b/cmvr-es/algorithms/motion_planner/arm_motion/cartesian_motion/pinocchio/test/pinocchio_speedl_limits_test.cpp deleted file mode 100644 index 2454b6c6..00000000 --- a/cmvr-es/algorithms/motion_planner/arm_motion/cartesian_motion/pinocchio/test/pinocchio_speedl_limits_test.cpp +++ /dev/null @@ -1,213 +0,0 @@ -#include - -#include -#include -#include -#include - -#include "algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_dls_ik_solver.h" -#include "algorithms/motion_planner/arm_motion/cartesian_motion/pinocchio/include/pinocchio_cartesian_motion_planner.h" -#include "common/io/proto_file_io.h" -#include "common/math/transform_math.h" - -namespace cmvr::device { -namespace { -constexpr double kDt = .001; -using Twist = Eigen::Matrix; - -// Exercise the production planner and real URDF kinematics, without motor I/O. -class PinocchioSpeedLLimits : public ::testing::Test { -protected: - void SetUp() override { - const auto root = std::filesystem::path(CMVR_TEST_SOURCE_DIR); - config::ArmRootConfig arms; - ASSERT_TRUE(ProtoMessageIo::getProtoFromAsciiFile( - (root / "cmvr-es/config/devices/arm/arm.pb.txt").string(), &arms)); - ASSERT_GT(arms.arm().robot_arms_size(), 0); - auto ik = arms.arm().robot_arms(0).kinematics().pinocchio_dls_ik_solver(); - ik.set_urdf_path((root / "model/xiaoyan_description/dual_arm.urdf").string()); - solver_ = std::make_shared(ik); - ASSERT_TRUE(solver_->init()); - planner_ = std::make_unique(solver_); - limits_.set_linear_velocity_max(.2); - limits_.set_linear_acceleration_max(.4); - limits_.set_linear_jerk_max(2); - limits_.set_angular_velocity_max(1); - limits_.set_angular_acceleration_max(.8); - limits_.set_angular_jerk_max(4); - limits_.set_enforce_joint_acceleration_limits(false); - ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size())); - } - - struct Peaks { double velocity{0}, acceleration{0}, jerk{0}; }; - Peaks sample(const CartesianVelocity& target, const SpeedLOptions& options, - bool angular = false, int steps = 2200, bool legacy_api = false) { - Peaks peaks; - Twist previous = common::math::velocityToVector(planner_->getSpeedLCommandTwistBase()); - Twist previous_acceleration = Twist::Zero(); - for (int i = 0; i < steps; ++i) { - const bool updated = legacy_api - ? planner_->updateSpeedLAcceleration(options.acceleration) - : planner_->updateSpeedLLimits(options); - if (!updated || !planner_->speedLStep(target, kDt, q_, qd_, command_, FrameType::Base)) { - ADD_FAILURE() << "Planning failed at sample " << i; - break; - } - const Twist velocity = common::math::velocityToVector(planner_->getSpeedLCommandTwistBase()); - const Twist acceleration = (velocity - previous) / kDt; - const Twist jerk = (acceleration - previous_acceleration) / kDt; - const int offset = angular ? 3 : 0; - peaks.velocity = std::max(peaks.velocity, velocity.segment<3>(offset).norm()); - peaks.acceleration = std::max(peaks.acceleration, acceleration.segment<3>(offset).norm()); - peaks.jerk = std::max(peaks.jerk, jerk.segment<3>(offset).norm()); - previous = velocity; - previous_acceleration = acceleration; - } - return peaks; - } - - void expectPeaks(const Peaks& p, double velocity, double acceleration, double jerk) { - // These trajectories contain plateaus: limits must be reached, as well - // as obeyed, so an unintended smaller cap cannot pass the test. - EXPECT_NEAR(p.velocity, velocity, 1e-8); - EXPECT_NEAR(p.acceleration, acceleration, 1e-8); - EXPECT_NEAR(p.jerk, jerk, 1e-6); - } - - std::shared_ptr solver_; - std::unique_ptr planner_; - config::SpeedLPlannerConfig limits_; - const std::vector q_{.25, 1, M_PI / 2, M_PI / 2, -M_PI / 2, 0, 0}; - const std::vector qd_ = std::vector(7, 0); - std::vector command_; -}; - -TEST_F(PinocchioSpeedLLimits, ExcessiveRequestsRespectAllLinearLimits) { - SpeedLOptions options; - options.acceleration = 60; - options.linear_jerk = 60; - CartesianVelocity target; - target.vx = .6; - target.vy = .8; - expectPeaks(sample(target, options), .2, .4, 2); -} - -TEST_F(PinocchioSpeedLLimits, LowerRequestsRemainEffective) { - SpeedLOptions options; - options.acceleration = .15; - options.linear_jerk = .8; - CartesianVelocity target; - target.vy = 1; - expectPeaks(sample(target, options), .2, .15, .8); -} - -TEST_F(PinocchioSpeedLLimits, OmittedJerkRestoresArmLimit) { - SpeedLOptions options; - options.acceleration = .4; - options.linear_jerk = .3; - ASSERT_TRUE(planner_->updateSpeedLLimits(options)); - options.linear_jerk.reset(); - CartesianVelocity target; - target.vy = 1; - expectPeaks(sample(target, options), .2, .4, 2); -} - -TEST_F(PinocchioSpeedLLimits, LegacyAccelerationAndStopAreCapped) { - SpeedLOptions options; - options.acceleration = 60; - CartesianVelocity target; - target.vy = 1; - expectPeaks(sample(target, options, false, 1200, true), .2, .4, 2); - const auto stop = sample({}, options, false, 1200, true); - EXPECT_LE(stop.velocity, .2); - EXPECT_NEAR(stop.acceleration, .4, 1e-8); - EXPECT_NEAR(stop.jerk, 2, 1e-6); - EXPECT_NEAR(planner_->getSpeedLCommandTwistBase().vy, 0, 1e-12); -} - -TEST_F(PinocchioSpeedLLimits, AngularAccelerationHasItsOwnCapAndCache) { - limits_.set_linear_acceleration_max(.2); - ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size())); - SpeedLOptions options; - options.acceleration = .3; - ASSERT_TRUE(planner_->updateSpeedLLimits(options)); - // Linear effective acceleration stays at .2, but angular must change. - options.acceleration = .6; - CartesianVelocity target; - target.wy = 2; - expectPeaks(sample(target, options, true), 1, .6, 4); - ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size())); - options.acceleration = 60; - expectPeaks(sample(target, options, true), 1, .8, 4); -} - -TEST_F(PinocchioSpeedLLimits, InvalidRequestsAreRejectedBeforeClamping) { - for (double invalid : {0.0, -1.0, std::numeric_limits::infinity(), - std::numeric_limits::quiet_NaN()}) { - SpeedLOptions options; - options.acceleration = invalid; - EXPECT_FALSE(planner_->updateSpeedLLimits(options)); - EXPECT_FALSE(planner_->updateSpeedLAcceleration(invalid)); - options.acceleration = .3; - options.linear_jerk = invalid; - EXPECT_FALSE(planner_->updateSpeedLLimits(options)); - } -} - -TEST_F(PinocchioSpeedLLimits, StreamingAlignmentOverridesGlobalReversalPolicy) { - for (const double jerk : {10.0, 30.0}) { - SCOPED_TRACE(jerk); - limits_.set_continuous_linear_reversal(true); - limits_.set_linear_acceleration_max(5); - limits_.set_linear_jerk_max(jerk); - ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size())); - SpeedLOptions options; - options.acceleration = .5; - CartesianVelocity target; - target.vy = .02; - sample(target, options, false, 300); - ASSERT_NEAR(planner_->getSpeedLCommandTwistBase().vy, .02, 1e-10); - - // Same acceleration/jerk: the policy override must bypass their cache. - options.continuous_linear_reversal = false; - double min_speed = .02; - double max_error = 0; - for (int i = 0; i < 2000; ++i) { - const double angle = (i / 20) * .01; - target.vx = .02 * std::sin(angle); - target.vy = .02 * std::cos(angle); - ASSERT_TRUE(planner_->updateSpeedLLimits(options)); - ASSERT_TRUE(planner_->speedLStep(target, kDt, q_, qd_, command_, FrameType::Base)); - const Twist actual = common::math::velocityToVector(planner_->getSpeedLCommandTwistBase()); - min_speed = std::min(min_speed, actual.head<3>().norm()); - max_error = std::max(max_error, (actual - common::math::velocityToVector(target)).norm()); - } - EXPECT_NEAR(min_speed, .02, 1e-10); - EXPECT_LT(max_error, 1e-10); - } -} - -TEST_F(PinocchioSpeedLLimits, ContactReversalStillCrossesZeroAfterStreamingAlignment) { - limits_.set_linear_acceleration_max(1); - limits_.set_linear_jerk_max(4); - ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size())); - SpeedLOptions options; - options.acceleration = 1; - options.continuous_linear_reversal = false; - CartesianVelocity target; - target.vy = .02; - sample(target, options, false, 300); - ASSERT_NEAR(planner_->getSpeedLCommandTwistBase().vy, .02, 1e-10); - - options.continuous_linear_reversal = true; - target.vy = -.02; - for (int i = 0; i < 100; ++i) { - ASSERT_TRUE(planner_->updateSpeedLLimits(options)); - ASSERT_TRUE(planner_->speedLStep(target, kDt, q_, qd_, command_, FrameType::Base)); - } - EXPECT_NEAR(planner_->getSpeedLCommandTwistBase().vy, 0, 1e-10); - ASSERT_TRUE(planner_->speedLStep(target, kDt, q_, qd_, command_, FrameType::Base)); - EXPECT_LT(planner_->getSpeedLCommandTwistBase().vy, -.0003); -} -} // namespace -} // namespace cmvr::device diff --git a/cmvr-es/algorithms/motion_planner/arm_motion/common/include/twist_limiter_config.h b/cmvr-es/algorithms/motion_planner/arm_motion/common/include/twist_limiter_config.h deleted file mode 100644 index 97dde369..00000000 --- a/cmvr-es/algorithms/motion_planner/arm_motion/common/include/twist_limiter_config.h +++ /dev/null @@ -1,55 +0,0 @@ -#ifndef CMVR_ES_TWIST_LIMITER_CONFIG_H -#define CMVR_ES_TWIST_LIMITER_CONFIG_H - -#include - -#include "algorithms/motion_planner/base_motion/cartesian_velocity/twist_limiter/include/cartesian_twist_limiter.h" -#include "cmvr/config/arm_config/arm_config.pb.h" -#include "common/config/config_files.h" - -namespace cmvr::device::cartesian_motion { - -inline void configureTwistLimiterFromSpeedLConfig( - cmvr::CartesianTwistLimiter& limiter, - const config::SpeedLPlannerConfig& config) -{ - using cmvr::common::config::positiveOr; - - limiter.setLinearConstraints(positiveOr(config.linear_velocity_max(), 0.55), - positiveOr(config.linear_acceleration_max(), 5.0), - positiveOr(config.linear_jerk_max(), 10.0)); - limiter.setAngularConstraints(positiveOr(config.angular_velocity_max(), 1.0), - positiveOr(config.angular_acceleration_max(), 5.0), - positiveOr(config.angular_jerk_max(), 12.0)); - limiter.setLinearTargetReplanThreshold( - positiveOr(config.linear_target_replan_threshold(), 1e-4)); - limiter.setAngularTargetReplanThreshold( - positiveOr(config.angular_target_replan_threshold(), 1e-4)); - limiter.setLinearReverseSwitchPolicy( - config.linear_reverse_cos_threshold() != 0.0 - ? config.linear_reverse_cos_threshold() - : -0.8660254037844386, - positiveOr(config.linear_reverse_switch_speed_threshold(), 1e-3)); - limiter.setContinuousLinearReversal(!config.has_continuous_linear_reversal() || - config.continuous_linear_reversal()); - limiter.initialize(Eigen::Matrix::Zero()); -} - -inline void updateTwistLimiterAcceleration( - cmvr::CartesianTwistLimiter& limiter, - const config::SpeedLPlannerConfig& config, - const double acceleration) -{ - using cmvr::common::config::positiveOr; - - limiter.setLinearConstraints(positiveOr(config.linear_velocity_max(), 0.55), - std::min(acceleration, positiveOr(config.linear_acceleration_max(), 5.0)), - positiveOr(config.linear_jerk_max(), 10.0)); - limiter.setAngularConstraints(positiveOr(config.angular_velocity_max(), 1.0), - std::min(acceleration, positiveOr(config.angular_acceleration_max(), 5.0)), - positiveOr(config.angular_jerk_max(), 12.0)); -} - -} // namespace cmvr::device::cartesian_motion - -#endif // CMVR_ES_TWIST_LIMITER_CONFIG_H diff --git a/cmvr-es/algorithms/motion_planner/arm_motion/joint_motion/joint_motion_planner_factory.h b/cmvr-es/algorithms/motion_planner/arm_motion/joint_motion/joint_motion_planner_factory.h deleted file mode 100644 index c9211cd1..00000000 --- a/cmvr-es/algorithms/motion_planner/arm_motion/joint_motion/joint_motion_planner_factory.h +++ /dev/null @@ -1,55 +0,0 @@ -#ifndef CMVR_ES_JOINT_MOTION_PLANNER_FACTORY_H -#define CMVR_ES_JOINT_MOTION_PLANNER_FACTORY_H - -#include - -#include "algorithms/motion_planner/arm_motion/joint_motion/joint_motion_planner.h" -#include "algorithms/motion_planner/arm_motion/joint_motion/toppra/include/toppra_joint_motion_planner.h" -#include "cmvr/config/arm_config/arm_config.pb.h" - -namespace cmvr::device { - -class JointMotionPlannerFactory { -public: - static std::shared_ptr create( - const config::MoveJConfig& cfg) - { - if (!cfg.has_toppra_joint_motion_planner()) { - return nullptr; - } - - cmvr::PathType path_type; - switch (cfg.toppra_joint_motion_planner().path_type()) { - case config::TOPPRA_PATH_TYPE_LINEAR: - path_type = cmvr::PathType::Linear; - break; - case config::TOPPRA_PATH_TYPE_CUBIC_HERMITE: - path_type = cmvr::PathType::CubicHermite; - break; - case config::TOPPRA_PATH_TYPE_QUINTIC: - path_type = cmvr::PathType::Quintic; - break; - case config::TOPPRA_PATH_TYPE_NATURAL: - path_type = cmvr::PathType::Natural; - break; - case config::TOPPRA_PATH_TYPE_UNKNOWN: - default: - return nullptr; - } - - const auto& toppra = cfg.toppra_joint_motion_planner(); - auto planner = std::make_shared( - path_type, - toppra.sample_period_s(), - toppra.grid_size(), - toppra.high_grid_size()); - if (!planner->init()) { - return nullptr; - } - return planner; - } -}; - -} // namespace cmvr::device - -#endif // CMVR_ES_JOINT_MOTION_PLANNER_FACTORY_H diff --git a/cmvr-es/algorithms/motion_planner/arm_motion/joint_motion/toppra/include/toppra_joint_motion_planner.h b/cmvr-es/algorithms/motion_planner/arm_motion/joint_motion/toppra/include/toppra_joint_motion_planner.h deleted file mode 100644 index 7aadd085..00000000 --- a/cmvr-es/algorithms/motion_planner/arm_motion/joint_motion/toppra/include/toppra_joint_motion_planner.h +++ /dev/null @@ -1,46 +0,0 @@ -#ifndef CMVR_ES_TOPPRA_JOINT_MOTION_PLANNER_H -#define CMVR_ES_TOPPRA_JOINT_MOTION_PLANNER_H - -#include - -#include "../../joint_motion_planner.h" -#include "../../../../base_motion/joint_trajectory/joint_trajectory_planner.h" - -namespace cmvr::device { - -class ToppraJointMotionPlanner final : public JointMotionPlanner { -public: - ToppraJointMotionPlanner(cmvr::PathType path_type, - double sample_period_s, - int grid_size, - int high_grid_size); - - bool init() override; - - bool planMoveJ(const std::vector& start, - const JointPositionCommand& target, - const MotionOptions& options, - double speed_scaling, - JointTrajectory& trajectory) override; - - bool planReplay(const std::vector& current_position, - const JointTrajectory& recorded_trajectory, - const MotionOptions& options, - JointTrajectory& replay_trajectory) override; - -private: - bool sampleTrajectory_( - const std::shared_ptr& planner, - const cmvr::TrajPtr& raw_trajectory, - JointTrajectory& trajectory) const; - - std::shared_ptr planner_; - cmvr::PathType path_type_{cmvr::PathType::Quintic}; - double sample_period_s_{0.001}; - int grid_size_{150}; - int high_grid_size_{300}; -}; - -} // namespace cmvr::device - -#endif // CMVR_ES_TOPPRA_JOINT_MOTION_PLANNER_H diff --git a/cmvr-es/algorithms/motion_planner/arm_motion/joint_motion/toppra/src/toppra_joint_motion_planner.cpp b/cmvr-es/algorithms/motion_planner/arm_motion/joint_motion/toppra/src/toppra_joint_motion_planner.cpp deleted file mode 100644 index 1fe882fa..00000000 --- a/cmvr-es/algorithms/motion_planner/arm_motion/joint_motion/toppra/src/toppra_joint_motion_planner.cpp +++ /dev/null @@ -1,258 +0,0 @@ -#include "algorithms/motion_planner/arm_motion/joint_motion/toppra/include/toppra_joint_motion_planner.h" - -#include - -#include "algorithms/motion_planner/base_motion/joint_trajectory/toppra/include/toppra_joint_trajectory_planner.h" -#include "common/base/logging/logger.h" - -namespace cmvr::device { - -namespace { - -std::vector toStdVector(const Eigen::VectorXd& value) -{ - std::vector result; - result.reserve(static_cast(value.size())); - for (int i = 0; i < value.size(); ++i) { - result.push_back(value[i]); - } - return result; -} - -} // namespace - -ToppraJointMotionPlanner::ToppraJointMotionPlanner(const cmvr::PathType path_type, - const double sample_period_s, - const int grid_size, - const int high_grid_size) - : path_type_(path_type) - , sample_period_s_(sample_period_s) - , grid_size_(grid_size) - , high_grid_size_(high_grid_size) -{ -} - -bool ToppraJointMotionPlanner::init() -{ - if (sample_period_s_ <= 0.0 || grid_size_ <= 0 || high_grid_size_ < grid_size_) { - return false; - } - planner_ = std::make_shared(path_type_); - planner_->setGridSizes(grid_size_, high_grid_size_); - return true; -} - -bool ToppraJointMotionPlanner::sampleTrajectory_( - const std::shared_ptr& planner, - const cmvr::TrajPtr& raw_trajectory, - JointTrajectory& trajectory) const -{ - const auto raw_samples = planner->sampleTrajectory( - raw_trajectory, sample_period_s_); - if (raw_samples.size() < 2) { - CMVR_LOG(ERROR) << "[ToppraJointMotionPlanner] trajectory sampling returned fewer than " - "two points: count=" - << raw_samples.size(); - return false; - } - trajectory.clear(); - trajectory.reserve(raw_samples.size()); - for (std::size_t i = 0; i < raw_samples.size(); ++i) { - const auto& sample = raw_samples[i]; - if (!std::isfinite(sample.t) || !sample.q.allFinite() || - !sample.qd.allFinite()) { - CMVR_LOG(ERROR) << "[ToppraJointMotionPlanner] sampled trajectory contains " - "a non-finite value at point=" - << i; - trajectory.clear(); - return false; - } - JointTrajectoryPoint point; - point.time_s = sample.t; - point.position = toStdVector(sample.q); - point.velocity = toStdVector(sample.qd); - trajectory.push_back(std::move(point)); - } - return true; -} - -bool ToppraJointMotionPlanner::planMoveJ(const std::vector& start, - const JointPositionCommand& target, - const MotionOptions& options, - const double speed_scaling, - JointTrajectory& trajectory) -{ - trajectory.clear(); - if (!planner_ || start.empty() || start.size() != target.position.size() || - options.velocity <= 0.0 || options.acceleration <= 0.0) { - return false; - } - - cmvr::TrajPtr raw_trajectory; - planner_->setPathType(path_type_); - planner_->setGridSizes(grid_size_, high_grid_size_); - planner_->setSymmetricLimits( - std::vector(start.size(), options.velocity * speed_scaling), - std::vector(start.size(), options.acceleration)); - if (!planner_->plan(start, target.position, raw_trajectory)) { - return false; - } - - return sampleTrajectory_(planner_, raw_trajectory, trajectory); -} - -bool ToppraJointMotionPlanner::planReplay( - const std::vector& current_position, - const JointTrajectory& recorded_trajectory, - const MotionOptions& options, - JointTrajectory& replay_trajectory) -{ - replay_trajectory.clear(); - if (current_position.empty() || recorded_trajectory.size() < 2 || - options.velocity <= 0.0 || - options.acceleration <= 0.0 || !std::isfinite(options.velocity) || - !std::isfinite(options.acceleration)) { - CMVR_LOG(ERROR) << "[ToppraJointMotionPlanner][planReplay] invalid trajectory or options"; - return false; - } - - const std::size_t dof = current_position.size(); - if (!options.joint_velocity_limits.empty() && - options.joint_velocity_limits.size() != dof) { - CMVR_LOG(ERROR) << "[ToppraJointMotionPlanner][planReplay] invalid DOF or joint limits"; - return false; - } - for (const double position : current_position) { - if (!std::isfinite(position)) { - CMVR_LOG(ERROR) << "[ToppraJointMotionPlanner][planReplay] non-finite current position"; - return false; - } - } - for (std::size_t i = 0; i < recorded_trajectory.size(); ++i) { - const auto& point = recorded_trajectory[i]; - if (!std::isfinite(point.time_s) || point.position.size() != dof || - (i > 0 && point.time_s <= recorded_trajectory[i - 1].time_s)) { - CMVR_LOG(ERROR) << "[ToppraJointMotionPlanner][planReplay] invalid recorded point: " - << i; - return false; - } - for (std::size_t joint = 0; joint < dof; ++joint) { - if (!std::isfinite(point.position[joint])) { - CMVR_LOG(ERROR) << "[ToppraJointMotionPlanner][planReplay] non-finite recorded point: " - << i; - return false; - } - } - } - - std::vector velocity_limits = options.joint_velocity_limits; - if (velocity_limits.empty()) { - velocity_limits.assign(dof, options.velocity); - } - for (std::size_t joint = 0; joint < velocity_limits.size(); ++joint) { - const double limit = velocity_limits[joint]; - if (!std::isfinite(limit) || limit <= 0.0) { - CMVR_LOG(ERROR) << "[ToppraJointMotionPlanner][planReplay] invalid joint velocity limit"; - return false; - } - } - - const double ramp_duration_s = std::max( - sample_period_s_, options.velocity / options.acceleration); - replay_trajectory.reserve(recorded_trajectory.size() + 2); - replay_trajectory.push_back(JointTrajectoryPoint{ - 0.0, current_position, std::vector(dof, 0.0)}); - - double replay_time_s = ramp_duration_s; - replay_trajectory.push_back(JointTrajectoryPoint{ - replay_time_s, - recorded_trajectory.back().position, - std::vector(dof, 0.0)}); - for (std::size_t i = recorded_trajectory.size() - 1; i > 0; --i) { - replay_time_s += recorded_trajectory[i].time_s - - recorded_trajectory[i - 1].time_s; - replay_trajectory.push_back(JointTrajectoryPoint{ - replay_time_s, - recorded_trajectory[i - 1].position, - std::vector(dof, 0.0)}); - } - replay_time_s += ramp_duration_s; - replay_trajectory.push_back(JointTrajectoryPoint{ - replay_time_s, - recorded_trajectory.front().position, - std::vector(dof, 0.0)}); - - const auto update_velocities = [&] { - for (auto& point : replay_trajectory) { - std::fill(point.velocity.begin(), point.velocity.end(), 0.0); - } - for (std::size_t i = 1; i + 1 < replay_trajectory.size(); ++i) { - const double dt = replay_trajectory[i + 1].time_s - - replay_trajectory[i - 1].time_s; - for (std::size_t joint = 0; joint < dof; ++joint) { - replay_trajectory[i].velocity[joint] = - (replay_trajectory[i + 1].position[joint] - - replay_trajectory[i - 1].position[joint]) / dt; - } - } - }; - - for (int iteration = 0; iteration < 3; ++iteration) { - update_velocities(); - double required_scale = 1.0; - std::vector previous_position_velocity(dof, 0.0); - for (std::size_t i = 0; i < replay_trajectory.size(); ++i) { - const auto& point = replay_trajectory[i]; - for (std::size_t joint = 0; joint < dof; ++joint) { - required_scale = std::max( - required_scale, - std::abs(point.velocity[joint]) / velocity_limits[joint]); - if (i == 0) { - continue; - } - - const double dt = point.time_s - - replay_trajectory[i - 1].time_s; - const double position_velocity = - (point.position[joint] - - replay_trajectory[i - 1].position[joint]) / dt; - const double acceleration = - (point.velocity[joint] - - replay_trajectory[i - 1].velocity[joint]) / dt; - required_scale = std::max( - required_scale, - std::abs(position_velocity) / velocity_limits[joint]); - required_scale = std::max( - required_scale, - std::sqrt(std::abs(acceleration) / - options.acceleration)); - if (i > 1) { - const double position_acceleration = - (position_velocity - - previous_position_velocity[joint]) / dt; - required_scale = std::max( - required_scale, - std::sqrt(std::abs(position_acceleration) / - options.acceleration)); - } - previous_position_velocity[joint] = position_velocity; - } - } - - if (required_scale <= 1.0 + 1e-9) { - break; - } - required_scale *= 1.001; - for (auto& point : replay_trajectory) { - point.time_s *= required_scale; - } - } - update_velocities(); - if (!validateJointTrajectory(replay_trajectory, dof, options)) { - replay_trajectory.clear(); - return false; - } - return true; -} - -} // namespace cmvr::device diff --git a/cmvr-es/algorithms/motion_planner/arm_motion/joint_motion/toppra/test/toppra_joint_motion_planner_test.cpp b/cmvr-es/algorithms/motion_planner/arm_motion/joint_motion/toppra/test/toppra_joint_motion_planner_test.cpp deleted file mode 100644 index 40ad8414..00000000 --- a/cmvr-es/algorithms/motion_planner/arm_motion/joint_motion/toppra/test/toppra_joint_motion_planner_test.cpp +++ /dev/null @@ -1,139 +0,0 @@ -#include -#include -#include -#include -#include - -#include - -#include "joint_motion/toppra/include/toppra_joint_motion_planner.h" - -namespace cmvr::device { -namespace { - -constexpr std::size_t kDof = 7; - -JointTrajectory makeRecordedTrajectory(const std::size_t point_count) -{ - JointTrajectory trajectory; - trajectory.reserve(point_count); - for (std::size_t i = 0; i < point_count; ++i) { - const double s = static_cast(i) / - static_cast(point_count - 1); - JointTrajectoryPoint point; - point.time_s = static_cast(i) * 0.002; - point.position = { - 0.40 * s, - -0.25 * s + 0.03 * std::sin(3.141592653589793 * s), - 0.20 * s * s, - 0.30 * std::sin(1.5707963267948966 * s), - -0.12 * s, - 0.15 * s, - -0.08 * std::sin(3.141592653589793 * s), - }; - point.velocity.assign(kDof, 0.0); - trajectory.push_back(std::move(point)); - } - return trajectory; -} - -double maximumPositionError(const std::vector& lhs, - const std::vector& rhs) -{ - if (lhs.size() != rhs.size()) { - return std::numeric_limits::infinity(); - } - double maximum = 0.0; - for (std::size_t i = 0; i < lhs.size(); ++i) { - maximum = std::max(maximum, std::abs(lhs[i] - rhs[i])); - } - return maximum; -} - -TEST(ToppraJointMotionPlannerTest, PlansBoundedReverseReplay) -{ - ToppraJointMotionPlanner planner( - cmvr::PathType::Quintic, 0.001, 150, 300); - ASSERT_TRUE(planner.init()); - - const JointTrajectory recorded = makeRecordedTrajectory(300); - MotionOptions options; - options.velocity = 0.15; - options.acceleration = 5.0; - - JointTrajectory replay; - ASSERT_TRUE(planner.planReplay( - recorded.back().position, recorded, options, replay)); - ASSERT_EQ(replay.size(), recorded.size() + 2); - EXPECT_LT(maximumPositionError( - replay.front().position, recorded.back().position), - 1e-9); - EXPECT_LT(maximumPositionError( - replay.back().position, recorded.front().position), - 1e-9); - for (std::size_t i = 0; i < recorded.size(); ++i) { - EXPECT_LT(maximumPositionError( - replay[i + 1].position, - recorded[recorded.size() - 1 - i].position), - 1e-9); - } - - double maximum_velocity = 0.0; - double maximum_acceleration = 0.0; - for (std::size_t i = 0; i < replay.size(); ++i) { - ASSERT_EQ(replay[i].position.size(), kDof); - ASSERT_EQ(replay[i].velocity.size(), kDof); - for (std::size_t joint = 0; joint < kDof; ++joint) { - maximum_velocity = std::max( - maximum_velocity, std::abs(replay[i].velocity[joint])); - if (i > 0) { - const double dt = replay[i].time_s - replay[i - 1].time_s; - ASSERT_GT(dt, 0.0); - maximum_acceleration = std::max( - maximum_acceleration, - std::abs(replay[i].velocity[joint] - - replay[i - 1].velocity[joint]) / dt); - } - } - } - EXPECT_LE(maximum_velocity, options.velocity + 1e-6); - EXPECT_LE(maximum_acceleration, options.acceleration + 1e-3); -} - -TEST(ToppraJointMotionPlannerTest, RejectsNonIncreasingRecordedTime) -{ - ToppraJointMotionPlanner planner( - cmvr::PathType::Quintic, 0.001, 150, 300); - ASSERT_TRUE(planner.init()); - - JointTrajectory recorded = makeRecordedTrajectory(10); - recorded[5].time_s = recorded[4].time_s; - MotionOptions options; - options.velocity = 0.15; - options.acceleration = 5.0; - - JointTrajectory replay; - EXPECT_FALSE(planner.planReplay( - recorded.back().position, recorded, options, replay)); - EXPECT_TRUE(replay.empty()); -} - -TEST(ToppraJointMotionPlannerTest, ValidationRejectsInvalidOutputTrajectory) -{ - ToppraJointMotionPlanner planner( - cmvr::PathType::Quintic, 0.001, 150, 300); - MotionOptions options; - options.velocity = 0.15; - options.acceleration = 5.0; - - JointTrajectory trajectory = makeRecordedTrajectory(10); - trajectory[5].velocity[2] = options.velocity + 0.01; - EXPECT_FALSE(planner.validateJointTrajectory(trajectory, kDof, options)); - - trajectory[5].velocity[2] = 0.0; - trajectory[5].time_s = trajectory[4].time_s; - EXPECT_FALSE(planner.validateJointTrajectory(trajectory, kDof, options)); -} - -} // namespace -} // namespace cmvr::device diff --git a/cmvr-es/algorithms/motion_planner/base_motion/CMakeLists.txt b/cmvr-es/algorithms/motion_planner/base_motion/CMakeLists.txt deleted file mode 100644 index d815332b..00000000 --- a/cmvr-es/algorithms/motion_planner/base_motion/CMakeLists.txt +++ /dev/null @@ -1,49 +0,0 @@ - - -add_library(base_motion SHARED - joint_trajectory/toppra/src/toppra_joint_trajectory_planner.cpp - - motion_profile/s_curve/src/s_curve.cpp - motion_profile/s_curve/src/s_curve_position_planner.cpp - motion_profile/s_curve/src/s_curve_velocity_planner.cpp - cartesian_velocity/twist_limiter/src/cartesian_twist_limiter.cpp -) - -target_include_directories(base_motion PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) - -target_link_libraries(base_motion PUBLIC - OsqpEigen - tinyxml2 - fcl - toppra - cmvr_es::common -) - -add_library(cmvr_es::base_motion ALIAS base_motion) -add_executable(cartesian_twist_limiter_reversal_test - cartesian_velocity/twist_limiter/test/cartesian_twist_limiter_reversal_test.cpp) -target_link_libraries(cartesian_twist_limiter_reversal_test PRIVATE - cmvr_es::base_motion gtest gtest_main) -install(TARGETS base_motion LIBRARY DESTINATION lib) - -add_executable(toppra_multi_waypoint_test - joint_trajectory/toppra/test/toppra_multi_waypoint_test.cpp -) - -target_link_libraries(toppra_multi_waypoint_test - PRIVATE - cmvr_es::base_motion - gtest - gtest_main -) - -add_executable(s_curve_velocity_planner_stop_test - motion_profile/s_curve/test/s_curve_velocity_planner_stop_test.cpp -) - -target_link_libraries(s_curve_velocity_planner_stop_test - PRIVATE - cmvr_es::base_motion - gtest - gtest_main -) diff --git a/cmvr-es/algorithms/motion_planner/base_motion/cartesian_velocity/twist_limiter/include/cartesian_twist_limiter.h b/cmvr-es/algorithms/motion_planner/base_motion/cartesian_velocity/twist_limiter/include/cartesian_twist_limiter.h deleted file mode 100644 index 864f1902..00000000 --- a/cmvr-es/algorithms/motion_planner/base_motion/cartesian_velocity/twist_limiter/include/cartesian_twist_limiter.h +++ /dev/null @@ -1,249 +0,0 @@ -#pragma once - -#include -#include -#include "algorithms/motion_planner/base_motion/motion_profile/s_curve/include/s_curve_velocity_planner.h" -namespace cmvr -{ - -enum class CartesianFrame -{ - Base = 0, - Tool = 1 -}; - -/** - * @brief 6维末端 twist 在线限幅器(基于 SCurveVelocityPlanner1D) - * - * 线速度部分: - * - 固定轴上的有符号速度使用 SCurveVelocityPlanner1D 做 jerk-limited 规划 - * - 同轴反向连续过零,保留加速度;可显式选择旧的停止后换向策略 - * - 运动中锁定当前方向,不做方向插值 - * - 若目标方向与当前方向不共线,则采用“先减速到0,再切方向”的 switch policy - * - * 角速度部分: - * - 与线速度独立 - * - 模长使用 SCurveVelocityPlanner1D 做 jerk-limited 速度规划 - * - 运动中锁定当前旋转轴,不做方向插值 - * - * 接口语义: - * - setTargetTwist(...):设置目标 twist - * - synchronizeToMeasuredTwistBase(...):用测量 twist 同步当前状态 - * - update(dt, base_R_tool):根据当前目标与当前状态生成下一拍命令 twist - */ -class CartesianTwistLimiter -{ -public: - using Twist = Eigen::Matrix; - - CartesianTwistLimiter(); - - void setLinearConstraints(double max_velocity, - double max_acceleration, - double max_jerk); - - void setAngularConstraints(double max_velocity, - double max_acceleration, - double max_jerk); - - void setLinearTargetReplanThreshold(double threshold); - void setAngularTargetReplanThreshold(double threshold); - - /** - * @brief 设置线速度方向最大转动角速度(rad/s) - */ - void setLinearDirectionRateLimit(double max_rate_rad_s); - - /** - * @brief 设置角速度方向最大转动角速度(rad/s) - */ - void setAngularDirectionRateLimit(double max_rate_rad_s); - - /** - * @brief 设置线速度反向切换策略 - * - * @param cos_threshold 近反向判定阈值,范围 [-1, 1] - * @param switch_speed_threshold 线速度模长低于该阈值后,允许切到目标方向 - */ - void setLinearReverseSwitchPolicy(double cos_threshold, - double switch_speed_threshold); - - // Same-axis reversal uses a signed velocity without resetting acceleration - // at zero. Disable for streaming direction tracking (e.g. visual alignment). - void setContinuousLinearReversal(bool enabled); - bool continuousLinearReversalEnabled() const { return continuous_linear_reversal_; } - - /** - * @brief 初始化当前 twist 状态 - * - * 注意: - * - 初始 twist 视为 base 坐标系下 - */ - void initialize(const Twist& initial_twist = Twist::Zero()); - - void reset(); - - /** - * @brief 设置目标 twist - * - * @param target_twist 目标 twist - * @param frame 输入目标的坐标系(Base 或 Tool) - */ - void setTargetTwist(const Twist& target_twist, CartesianFrame frame); - - /** - * @brief 平滑停下 - */ - void stop(); - - /** - * @brief 急停 - * - * 使用更大的减速度/jerk 约束把当前线速度/角速度平滑拉回 0。 - * 当前运动停止后,会自动恢复到常规约束。 - * - * @param emergency_acceleration 急停减速度幅值 - * @param emergency_jerk 急停 jerk 幅值 - */ - void emergencyStop(double emergency_acceleration, - double emergency_jerk); - - /** - * @brief 急停(分别指定线速度/角速度减速度与 jerk) - * - * @param emergency_linear_acceleration 线速度急停减速度幅值 - * @param emergency_linear_jerk 线速度急停 jerk 幅值 - * @param emergency_angular_acceleration 角速度急停减速度幅值 - * @param emergency_angular_jerk 角速度急停 jerk 幅值 - */ - void emergencyStop(double emergency_linear_acceleration, - double emergency_linear_jerk, - double emergency_angular_acceleration, - double emergency_angular_jerk); - - /** - * @brief 用测得的 base-frame twist 同步当前状态 - * - * 作用: - * - 更新当前执行方向 - * - 线速度使用固定轴投影(保留正负号),角速度使用模长 - * - keep_target=true 时: - * - 若测量状态仍贴着当前 profile,则保持当前 profile - * - 否则由 planner 内部从测量状态重规划到当前目标 - * - keep_target=false 时: - * - 清掉旧 profile,仅覆盖状态 - * - * @param measured_twist_base 当前测得实际 twist(base 系) - * @param dt 与上一次测量同步的时间间隔 - * @param keep_target 是否保留当前目标模长 - */ - void synchronize(const Twist& measured_twist_base, - double dt, - bool keep_target = true); - - /** - * @brief 更新一步,返回 base 坐标系下的执行 twist 命令 - */ - Twist update(double dt, const Eigen::Matrix3d& base_R_tool); - - const Twist& getTwistBase() const { return twist_base_; } - const Twist& getCommandedTwistBase() const { return twist_base_; } - const Twist& getTargetTwistBase() const { return target_twist_base_; } - const Twist& getAccelerationBase() const { return acceleration_base_; } - const Twist& getJerkBase() const { return jerk_base_; } - - bool isMoving() const; - -private: - static constexpr double EPSILON = 1e-12; - static constexpr double DEFAULT_LINEAR_DIR_RATE_LIMIT = 3.14159265358979323846; // 180 deg/s - static constexpr double DEFAULT_ANGULAR_DIR_RATE_LIMIT = 3.14159265358979323846; // 180 deg/s - static constexpr double DEFAULT_LINEAR_REVERSE_COS_THRESHOLD = -0.8660254037844386; // cos(150 deg) - static constexpr double DEFAULT_LINEAR_REVERSE_SWITCH_SPEED_THRESHOLD = 1e-3; - static constexpr double AXIS_LOCK_COS_THRESHOLD = 0.999; - static constexpr double DEFAULT_ANGULAR_SWITCH_SPEED_THRESHOLD = 1e-3; - - // 模长 planner - SCurveVelocityPlanner1D linear_norm_planner_; - SCurveVelocityPlanner1D angular_norm_planner_; - - // 常规约束缓存。急停结束后恢复到这里。 - double linear_max_velocity_; - double linear_max_acceleration_; - double linear_max_jerk_; - double angular_max_velocity_; - double angular_max_acceleration_; - double angular_max_jerk_; - - // 方向变化率限制(rad/s) - double linear_direction_rate_limit_; - double angular_direction_rate_limit_; - - // 线速度 reverse policy - double linear_reverse_cos_threshold_; - double linear_reverse_switch_speed_threshold_; - double angular_switch_speed_threshold_; - bool emergency_stop_active_; - bool continuous_linear_reversal_{true}; - - // 目标/当前状态 - Twist target_twist_input_; - Twist target_twist_base_; - - Twist twist_base_; - Twist acceleration_base_; - Twist jerk_base_; - - Twist prev_twist_base_; - Twist prev_acceleration_base_; - - CartesianFrame input_frame_; - - // 当前执行方向 - Eigen::Vector3d current_linear_dir_base_; - Eigen::Vector3d current_angular_dir_base_; - - // 最近一次非零目标方向(目标变0时用于平滑停下) - Eigen::Vector3d last_target_linear_dir_base_; - Eigen::Vector3d last_target_angular_dir_base_; - - // 测量同步用缓存 - bool has_measured_sync_; - Twist last_measured_twist_base_; - Twist last_measured_acceleration_base_; - double prev_measured_linear_norm_; - double prev_measured_angular_norm_; - - static Twist transformTwistToolToBase(const Twist& twist_tool, - const Eigen::Matrix3d& base_R_tool); - - static Eigen::Vector3d chooseDirection(const Eigen::Vector3d& target_vec, - const Eigen::Vector3d& fallback); - - static Eigen::Vector3d rotateDirectionToward(const Eigen::Vector3d& current_dir, - const Eigen::Vector3d& target_dir, - double max_rate_rad_s, - double dt); - - static Eigen::Vector3d rotateAroundAxis(const Eigen::Vector3d& v, - const Eigen::Vector3d& axis_unit, - double angle_rad); - - static Eigen::Vector3d chooseOrthogonalUnit(const Eigen::Vector3d& v); - - void applyLinearConstraints(double max_velocity, - double max_acceleration, - double max_jerk); - void applyAngularConstraints(double max_velocity, - double max_acceleration, - double max_jerk); - void restoreNominalConstraints(); - static bool isZeroTwist(const Twist& twist); - - static double clamp(double value, double lo, double hi) - { - return std::max(lo, std::min(hi, value)); - } -}; - -} // namespace cmvr diff --git a/cmvr-es/algorithms/motion_planner/base_motion/cartesian_velocity/twist_limiter/src/cartesian_twist_limiter.cpp b/cmvr-es/algorithms/motion_planner/base_motion/cartesian_velocity/twist_limiter/src/cartesian_twist_limiter.cpp deleted file mode 100644 index 8167c59a..00000000 --- a/cmvr-es/algorithms/motion_planner/base_motion/cartesian_velocity/twist_limiter/src/cartesian_twist_limiter.cpp +++ /dev/null @@ -1,573 +0,0 @@ -#include "../include/cartesian_twist_limiter.h" - -#include -#include - -namespace cmvr -{ - -CartesianTwistLimiter::CartesianTwistLimiter() - : linear_norm_planner_(1.0, 1.0, 5.0) - , angular_norm_planner_(1.0, 1.0, 5.0) - , linear_max_velocity_(1.0) - , linear_max_acceleration_(1.0) - , linear_max_jerk_(5.0) - , angular_max_velocity_(1.0) - , angular_max_acceleration_(1.0) - , angular_max_jerk_(5.0) - , linear_direction_rate_limit_(DEFAULT_LINEAR_DIR_RATE_LIMIT) - , angular_direction_rate_limit_(DEFAULT_ANGULAR_DIR_RATE_LIMIT) - , linear_reverse_cos_threshold_(DEFAULT_LINEAR_REVERSE_COS_THRESHOLD) - , linear_reverse_switch_speed_threshold_(DEFAULT_LINEAR_REVERSE_SWITCH_SPEED_THRESHOLD) - , angular_switch_speed_threshold_(DEFAULT_ANGULAR_SWITCH_SPEED_THRESHOLD) - , emergency_stop_active_(false) - , target_twist_input_(Twist::Zero()) - , target_twist_base_(Twist::Zero()) - , twist_base_(Twist::Zero()) - , acceleration_base_(Twist::Zero()) - , jerk_base_(Twist::Zero()) - , prev_twist_base_(Twist::Zero()) - , prev_acceleration_base_(Twist::Zero()) - , input_frame_(CartesianFrame::Base) - , current_linear_dir_base_(Eigen::Vector3d::Zero()) - , current_angular_dir_base_(Eigen::Vector3d::Zero()) - , last_target_linear_dir_base_(Eigen::Vector3d::Zero()) - , last_target_angular_dir_base_(Eigen::Vector3d::Zero()) - , has_measured_sync_(false) - , last_measured_twist_base_(Twist::Zero()) - , last_measured_acceleration_base_(Twist::Zero()) - , prev_measured_linear_norm_(0.0) - , prev_measured_angular_norm_(0.0) -{ -} - -void CartesianTwistLimiter::applyLinearConstraints(double max_velocity, - double max_acceleration, - double max_jerk) -{ - linear_norm_planner_.setConstraints(max_velocity, max_acceleration, max_jerk); -} - -void CartesianTwistLimiter::applyAngularConstraints(double max_velocity, - double max_acceleration, - double max_jerk) -{ - angular_norm_planner_.setConstraints(max_velocity, max_acceleration, max_jerk); -} - -void CartesianTwistLimiter::setLinearConstraints(double max_velocity, - double max_acceleration, - double max_jerk) -{ - linear_max_velocity_ = std::abs(max_velocity); - linear_max_acceleration_ = std::abs(max_acceleration); - linear_max_jerk_ = std::abs(max_jerk); - - if (!emergency_stop_active_) { - applyLinearConstraints(linear_max_velocity_, linear_max_acceleration_, linear_max_jerk_); - } -} - -void CartesianTwistLimiter::setAngularConstraints(double max_velocity, - double max_acceleration, - double max_jerk) -{ - angular_max_velocity_ = std::abs(max_velocity); - angular_max_acceleration_ = std::abs(max_acceleration); - angular_max_jerk_ = std::abs(max_jerk); - - if (!emergency_stop_active_) { - applyAngularConstraints(angular_max_velocity_, angular_max_acceleration_, angular_max_jerk_); - } -} - -void CartesianTwistLimiter::setLinearTargetReplanThreshold(double threshold) -{ - linear_norm_planner_.setTargetReplanThreshold(threshold); -} - -void CartesianTwistLimiter::setAngularTargetReplanThreshold(double threshold) -{ - angular_norm_planner_.setTargetReplanThreshold(threshold); -} - -void CartesianTwistLimiter::setLinearDirectionRateLimit(double max_rate_rad_s) -{ - linear_direction_rate_limit_ = std::max(0.0, max_rate_rad_s); -} - -void CartesianTwistLimiter::setAngularDirectionRateLimit(double max_rate_rad_s) -{ - angular_direction_rate_limit_ = std::max(0.0, max_rate_rad_s); -} - -void CartesianTwistLimiter::setLinearReverseSwitchPolicy(double cos_threshold, - double switch_speed_threshold) -{ - linear_reverse_cos_threshold_ = clamp(cos_threshold, -1.0, 1.0); - linear_reverse_switch_speed_threshold_ = std::max(0.0, switch_speed_threshold); -} - -void CartesianTwistLimiter::setContinuousLinearReversal(bool enabled) -{ - if (continuous_linear_reversal_ == enabled) return; - - if (!enabled) { - const double velocity = linear_norm_planner_.getVelocity(); - const double acceleration = linear_norm_planner_.getAcceleration(); - // The streaming policy stores a speed magnitude and a physical direction. - // Convert a negative signed state without reversing its physical motion or - // dropping its acceleration when a command changes policy mid-retraction. - if (velocity < 0.0 || (std::abs(velocity) <= EPSILON && acceleration < 0.0)) { - current_linear_dir_base_ = -current_linear_dir_base_; - linear_norm_planner_.overwriteState(-velocity, -acceleration, false); - prev_measured_linear_norm_ = -prev_measured_linear_norm_; - } - } - continuous_linear_reversal_ = enabled; -} - -void CartesianTwistLimiter::initialize(const Twist& initial_twist) -{ - restoreNominalConstraints(); - emergency_stop_active_ = false; - - const Eigen::Vector3d v0 = initial_twist.head<3>(); - const Eigen::Vector3d w0 = initial_twist.tail<3>(); - - const double v0_norm = v0.norm(); - const double w0_norm = w0.norm(); - - linear_norm_planner_.initialize(v0_norm, 0.0); - angular_norm_planner_.initialize(w0_norm, 0.0); - - target_twist_input_ = initial_twist; - target_twist_base_ = initial_twist; - twist_base_ = initial_twist; - acceleration_base_.setZero(); - jerk_base_.setZero(); - prev_twist_base_ = initial_twist; - prev_acceleration_base_.setZero(); - - // current_linear_dir_base_ = - // (v0_norm > EPSILON) ? (v0 / v0_norm) : Eigen::Vector3d::Zero(); - // current_angular_dir_base_ = - // (w0_norm > EPSILON) ? (w0 / w0_norm) : Eigen::Vector3d::Zero(); - current_linear_dir_base_.setZero(); - current_angular_dir_base_.setZero(); - if (v0_norm > EPSILON) { - current_linear_dir_base_ = v0 / v0_norm; - } else { - - } - - if (w0_norm > EPSILON) { - current_angular_dir_base_ = w0 / w0_norm; - } else { - - } - - last_target_linear_dir_base_ = current_linear_dir_base_; - last_target_angular_dir_base_ = current_angular_dir_base_; - - has_measured_sync_ = false; - last_measured_twist_base_ = initial_twist; - last_measured_acceleration_base_.setZero(); - prev_measured_linear_norm_ = v0_norm; - prev_measured_angular_norm_ = w0_norm; -} - -void CartesianTwistLimiter::reset() -{ - restoreNominalConstraints(); - emergency_stop_active_ = false; - - linear_norm_planner_.reset(); - angular_norm_planner_.reset(); - - target_twist_input_.setZero(); - target_twist_base_.setZero(); - twist_base_.setZero(); - acceleration_base_.setZero(); - jerk_base_.setZero(); - prev_twist_base_.setZero(); - prev_acceleration_base_.setZero(); - - input_frame_ = CartesianFrame::Base; - - current_linear_dir_base_.setZero(); - current_angular_dir_base_.setZero(); - last_target_linear_dir_base_.setZero(); - last_target_angular_dir_base_.setZero(); - - has_measured_sync_ = false; - last_measured_twist_base_.setZero(); - last_measured_acceleration_base_.setZero(); - prev_measured_linear_norm_ = 0.0; - prev_measured_angular_norm_ = 0.0; -} - -void CartesianTwistLimiter::setTargetTwist(const Twist& target_twist, CartesianFrame frame) -{ - if (emergency_stop_active_ && !isZeroTwist(target_twist)) { - restoreNominalConstraints(); - emergency_stop_active_ = false; - } - - target_twist_input_ = target_twist; - input_frame_ = frame; -} - -void CartesianTwistLimiter::stop() -{ - // target_twist_input_.setZero(); - target_twist_input_.setZero(); - target_twist_base_.setZero(); - - linear_norm_planner_.setTargetVelocity(0.0); - angular_norm_planner_.setTargetVelocity(0.0); -} - -void CartesianTwistLimiter::emergencyStop(double emergency_acceleration, - double emergency_jerk) -{ - emergencyStop(emergency_acceleration, - emergency_jerk, - emergency_acceleration, - emergency_jerk); -} - -void CartesianTwistLimiter::emergencyStop(double emergency_linear_acceleration, - double emergency_linear_jerk, - double emergency_angular_acceleration, - double emergency_angular_jerk) -{ - const double linear_stop_acceleration = - std::max(std::abs(emergency_linear_acceleration), linear_max_acceleration_); - const double linear_stop_jerk = - std::max(std::abs(emergency_linear_jerk), linear_max_jerk_); - const double angular_stop_acceleration = - std::max(std::abs(emergency_angular_acceleration), angular_max_acceleration_); - const double angular_stop_jerk = - std::max(std::abs(emergency_angular_jerk), angular_max_jerk_); - - applyLinearConstraints(linear_max_velocity_, linear_stop_acceleration, linear_stop_jerk); - applyAngularConstraints(angular_max_velocity_, angular_stop_acceleration, angular_stop_jerk); - - emergency_stop_active_ = true; - target_twist_input_.setZero(); - target_twist_base_.setZero(); - linear_norm_planner_.setTargetVelocity(0.0); - angular_norm_planner_.setTargetVelocity(0.0); -} - -void CartesianTwistLimiter::synchronize(const Twist& measured_twist_base, - double dt, - bool keep_target) -{ - const Eigen::Vector3d v_meas = measured_twist_base.head<3>(); - const Eigen::Vector3d w_meas = measured_twist_base.tail<3>(); - - const bool signed_linear = continuous_linear_reversal_ && current_linear_dir_base_.norm() > EPSILON; - const double v_norm = signed_linear ? v_meas.dot(current_linear_dir_base_) : v_meas.norm(); - const double w_norm = w_meas.norm(); - - double v_acc = 0.0; - double w_acc = 0.0; - - if (dt > EPSILON && has_measured_sync_) { - v_acc = (v_norm - prev_measured_linear_norm_) / dt; - w_acc = (w_norm - prev_measured_angular_norm_) / dt; - - acceleration_base_ = (measured_twist_base - last_measured_twist_base_) / dt; - jerk_base_ = (acceleration_base_ - last_measured_acceleration_base_) / dt; - last_measured_acceleration_base_ = acceleration_base_; - } else { - acceleration_base_.setZero(); - jerk_base_.setZero(); - last_measured_acceleration_base_.setZero(); - } - - prev_measured_linear_norm_ = v_norm; - prev_measured_angular_norm_ = w_norm; - last_measured_twist_base_ = measured_twist_base; - has_measured_sync_ = true; - - // 线速度按固定轴投影保留正负号;角速度仍按模长同步 planner。 - // keep_target=true: - // - 若测量值仍贴着当前 profile,则继续沿旧 profile 走 - // - 否则从测量状态重规划到当前目标 - // keep_target=false: - // - 仅覆盖状态并清掉旧 profile,不保留当前目标 - if (keep_target) { - linear_norm_planner_.synchronizeAndReplan(v_norm, v_acc); - angular_norm_planner_.synchronizeAndReplan(w_norm, w_acc); - } else { - linear_norm_planner_.overwriteState(v_norm, v_acc, false); - angular_norm_planner_.overwriteState(w_norm, w_acc, false); - target_twist_input_.setZero(); - target_twist_base_.setZero(); - } - - if (!signed_linear && v_norm > EPSILON) { - current_linear_dir_base_ = v_meas / v_norm; - last_target_linear_dir_base_ = current_linear_dir_base_; - } - - if (w_norm > EPSILON) { - current_angular_dir_base_ = w_meas / w_norm; - last_target_angular_dir_base_ = current_angular_dir_base_; - } - - twist_base_ = measured_twist_base; - prev_twist_base_ = measured_twist_base; - prev_acceleration_base_ = acceleration_base_; -} - -CartesianTwistLimiter::Twist -CartesianTwistLimiter::transformTwistToolToBase(const Twist& twist_tool, - const Eigen::Matrix3d& base_R_tool) -{ - Twist twist_base; - twist_base.head<3>() = base_R_tool * twist_tool.head<3>(); - twist_base.tail<3>() = base_R_tool * twist_tool.tail<3>(); - return twist_base; -} - -Eigen::Vector3d CartesianTwistLimiter::chooseDirection(const Eigen::Vector3d& target_vec, - const Eigen::Vector3d& fallback) -{ - const double n = target_vec.norm(); - if (n > EPSILON) { - return target_vec / n; - } - return fallback; -} - -Eigen::Vector3d CartesianTwistLimiter::rotateAroundAxis(const Eigen::Vector3d& v, - const Eigen::Vector3d& axis_unit, - double angle_rad) -{ - const double c = std::cos(angle_rad); - const double s = std::sin(angle_rad); - return c * v + s * (axis_unit.cross(v)) + (1.0 - c) * axis_unit.dot(v) * axis_unit; -} - -Eigen::Vector3d CartesianTwistLimiter::chooseOrthogonalUnit(const Eigen::Vector3d& v) -{ - Eigen::Vector3d ref; - if (std::abs(v.x()) < 0.8) { - ref = Eigen::Vector3d::UnitX(); - } else if (std::abs(v.y()) < 0.8) { - ref = Eigen::Vector3d::UnitY(); - } else { - ref = Eigen::Vector3d::UnitZ(); - } - - Eigen::Vector3d ortho = ref - ref.dot(v) * v; - const double n = ortho.norm(); - if (n > EPSILON) { - return ortho / n; - } - return Eigen::Vector3d::UnitX(); -} - -void CartesianTwistLimiter::restoreNominalConstraints() -{ - applyLinearConstraints(linear_max_velocity_, linear_max_acceleration_, linear_max_jerk_); - applyAngularConstraints(angular_max_velocity_, angular_max_acceleration_, angular_max_jerk_); -} - -bool CartesianTwistLimiter::isZeroTwist(const Twist& twist) -{ - return twist.head<3>().squaredNorm() <= EPSILON && twist.tail<3>().squaredNorm() <= EPSILON; -} - -Eigen::Vector3d CartesianTwistLimiter::rotateDirectionToward(const Eigen::Vector3d& current_dir, - const Eigen::Vector3d& target_dir, - double max_rate_rad_s, - double dt) -{ - if (dt <= 0.0) { - return current_dir; - } - - const double cur_n = current_dir.norm(); - const double tgt_n = target_dir.norm(); - - if (tgt_n <= EPSILON) { - return current_dir; - } - if (cur_n <= EPSILON) { - return target_dir; - } - - const Eigen::Vector3d u = current_dir / cur_n; - const Eigen::Vector3d v = target_dir / tgt_n; - - const double dot_uv = clamp(u.dot(v), -1.0, 1.0); - const double angle = std::acos(dot_uv); - - if (angle <= 1e-9) { - return v; - } - - const double max_step = std::max(0.0, max_rate_rad_s) * dt; - if (max_step <= 0.0) { - return u; - } - if (angle <= max_step) { - return v; - } - - Eigen::Vector3d axis = u.cross(v); - const double axis_n = axis.norm(); - - if (axis_n > EPSILON) { - axis /= axis_n; - return rotateAroundAxis(u, axis, max_step).normalized(); - } - - if (dot_uv > 0.0) { - return v; - } - - const Eigen::Vector3d ortho_axis = chooseOrthogonalUnit(u); - return rotateAroundAxis(u, ortho_axis, max_step).normalized(); -} - -CartesianTwistLimiter::Twist -CartesianTwistLimiter::update(double dt, const Eigen::Matrix3d& base_R_tool) -{ - if (emergency_stop_active_ && isZeroTwist(target_twist_input_) && - !linear_norm_planner_.isMoving() && !angular_norm_planner_.isMoving()) { - restoreNominalConstraints(); - emergency_stop_active_ = false; - } - - if (input_frame_ == CartesianFrame::Base) { - target_twist_base_ = target_twist_input_; - } else { - target_twist_base_ = transformTwistToolToBase(target_twist_input_, base_R_tool); - } - - // ==================== 线速度:方向锁定 + 标量 planner ==================== - const Eigen::Vector3d v_des = target_twist_base_.head<3>(); - const double v_des_norm = v_des.norm(); - const Eigen::Vector3d v_target_dir = - chooseDirection(v_des, - current_linear_dir_base_.norm() > EPSILON - ? current_linear_dir_base_ - : last_target_linear_dir_base_); - - if (v_des_norm > EPSILON) { - last_target_linear_dir_base_ = v_target_dir; - } - - const double v_cur_norm = linear_norm_planner_.getVelocity(); - const bool has_current_linear_dir = current_linear_dir_base_.norm() > EPSILON; - if (!has_current_linear_dir) { - if (v_des_norm > EPSILON) { - current_linear_dir_base_ = v_target_dir; - linear_norm_planner_.setTargetVelocity(v_des_norm); - } else { - linear_norm_planner_.setTargetVelocity(0.0); - } - } else if (v_des_norm <= EPSILON) { - linear_norm_planner_.setTargetVelocity(0.0); - } else { - const double dir_dot = - clamp(current_linear_dir_base_.dot(v_target_dir), -1.0, 1.0); - const bool axis_aligned = dir_dot >= AXIS_LOCK_COS_THRESHOLD; - const bool reverse_aligned = dir_dot <= -AXIS_LOCK_COS_THRESHOLD; - const bool same_axis = axis_aligned || reverse_aligned; - const bool must_switch_axis = - !same_axis || dir_dot < linear_reverse_cos_threshold_; - - if (continuous_linear_reversal_ && same_axis) { - // Keep the axis fixed: the scalar profile carries the direction sign. - // Crossing zero is an interior point, with continuous acceleration. - linear_norm_planner_.setTargetVelocity(v_des.dot(current_linear_dir_base_)); - } else if (continuous_linear_reversal_ && - (std::abs(v_cur_norm) > EPSILON || - std::abs(linear_norm_planner_.getAcceleration()) > EPSILON || - linear_norm_planner_.hasActiveProfile())) { - // A different axis may only be adopted after the old profile settles. - linear_norm_planner_.setTargetVelocity(0.0); - } else if (!continuous_linear_reversal_ && must_switch_axis && - v_cur_norm > linear_reverse_switch_speed_threshold_) { - linear_norm_planner_.setTargetVelocity(0.0); - } else { - current_linear_dir_base_ = v_target_dir; - linear_norm_planner_.setTargetVelocity(v_des_norm); - } - } - - const double v_exec_norm = linear_norm_planner_.update(dt); - twist_base_.head<3>() = current_linear_dir_base_ * v_exec_norm; - - // ==================== 角速度:方向锁定 + 标量 planner ==================== - const Eigen::Vector3d w_des = target_twist_base_.tail<3>(); - const double w_des_norm = w_des.norm(); - const Eigen::Vector3d w_target_dir = - chooseDirection(w_des, - current_angular_dir_base_.norm() > EPSILON - ? current_angular_dir_base_ - : last_target_angular_dir_base_); - - if (w_des_norm > EPSILON) { - last_target_angular_dir_base_ = w_target_dir; - } - - const double w_cur_norm = angular_norm_planner_.getVelocity(); - const bool has_current_angular_dir = current_angular_dir_base_.norm() > EPSILON; - if (!has_current_angular_dir) { - if (w_des_norm > EPSILON) { - current_angular_dir_base_ = w_target_dir; - angular_norm_planner_.setTargetVelocity(w_des_norm); - } else { - angular_norm_planner_.setTargetVelocity(0.0); - } - } else if (w_des_norm <= EPSILON) { - angular_norm_planner_.setTargetVelocity(0.0); - } else { - const double dir_dot = - clamp(current_angular_dir_base_.dot(w_target_dir), -1.0, 1.0); - const bool axis_aligned = dir_dot >= AXIS_LOCK_COS_THRESHOLD; - const bool reverse_aligned = dir_dot <= -AXIS_LOCK_COS_THRESHOLD; - const bool same_axis = axis_aligned || reverse_aligned; - // 角速度与线速度一致:反向同轴也必须先减速到 0,再切方向。 - const bool must_switch_axis = !same_axis || reverse_aligned; - - if (must_switch_axis && w_cur_norm > angular_switch_speed_threshold_) { - angular_norm_planner_.setTargetVelocity(0.0); - } else { - current_angular_dir_base_ = w_target_dir; - angular_norm_planner_.setTargetVelocity(w_des_norm); - } - } - - const double w_exec_norm = angular_norm_planner_.update(dt); - twist_base_.tail<3>() = current_angular_dir_base_ * w_exec_norm; - - // ==================== 对最终 twist 做差分得到 acc / jerk ==================== - if (dt > EPSILON) { - acceleration_base_ = (twist_base_ - prev_twist_base_) / dt; - jerk_base_ = (acceleration_base_ - prev_acceleration_base_) / dt; - } else { - acceleration_base_.setZero(); - jerk_base_.setZero(); - } - - prev_twist_base_ = twist_base_; - prev_acceleration_base_ = acceleration_base_; - - return twist_base_; -} - -bool CartesianTwistLimiter::isMoving() const -{ - return linear_norm_planner_.isMoving() || angular_norm_planner_.isMoving(); -} - -} // namespace cmvr diff --git a/cmvr-es/algorithms/motion_planner/base_motion/cartesian_velocity/twist_limiter/test/cartesian_twist_limiter_reversal_test.cpp b/cmvr-es/algorithms/motion_planner/base_motion/cartesian_velocity/twist_limiter/test/cartesian_twist_limiter_reversal_test.cpp deleted file mode 100644 index 18ba446f..00000000 --- a/cmvr-es/algorithms/motion_planner/base_motion/cartesian_velocity/twist_limiter/test/cartesian_twist_limiter_reversal_test.cpp +++ /dev/null @@ -1,118 +0,0 @@ -#include -#include "algorithms/motion_planner/base_motion/cartesian_velocity/twist_limiter/include/cartesian_twist_limiter.h" - -namespace cmvr { -namespace { -using Twist = CartesianTwistLimiter::Twist; -constexpr double dt = .001; -Twist y(double v) { Twist t = Twist::Zero(); t.y() = v; return t; } -struct Motion { double peak{0}, reverse_time{-1}, return_time{-1}; }; -Motion reverse(bool continuous, int approach_ticks) { - CartesianTwistLimiter limiter; - limiter.setLinearConstraints(.55, 5, 10); - limiter.setContinuousLinearReversal(continuous); - limiter.initialize(approach_ticks == 0 ? y(.08) : Twist::Zero()); - limiter.setTargetTwist(y(.08), CartesianFrame::Base); - for (int i = 0; i < approach_ticks; ++i) limiter.update(dt, Eigen::Matrix3d::Identity()); - limiter.setLinearConstraints(.55, 3, 10); - limiter.setTargetTwist(y(-.08), CartesianFrame::Base); - Motion result; - double position = 0; - for (int i = 1; i <= 1500; ++i) { - const auto v = limiter.update(dt, Eigen::Matrix3d::Identity()); - position += v.y() * dt; - result.peak = std::max(result.peak, position); - if (v.y() < 0 && result.reverse_time < 0) result.reverse_time = i * dt; - if (result.reverse_time > 0 && position <= 0 && result.return_time < 0) result.return_time = i * dt; - if (continuous) { - EXPECT_LE(limiter.getAccelerationBase().norm(), 3.0 + 1e-7); - EXPECT_LE(limiter.getJerkBase().norm(), 10.0 + 1e-6); - EXPECT_NEAR(v.x(), 0, 1e-12); - EXPECT_NEAR(v.z(), 0, 1e-12); - } - } - EXPECT_NEAR(limiter.getTwistBase().y(), -.08, 1e-9); - return result; -} -TEST(CartesianTwistReversal, ContinuousReversalReducesTimeAndForwardTravel) { - for (const int ticks : {0, 80, 120}) { - SCOPED_TRACE(ticks); - const auto legacy = reverse(false, ticks); - const auto continuous = reverse(true, ticks); - EXPECT_GT(continuous.reverse_time, 0); - EXPECT_LT(continuous.reverse_time, legacy.reverse_time); - EXPECT_LT(continuous.return_time, legacy.return_time); - EXPECT_LT(continuous.peak, legacy.peak); - } -} -TEST(CartesianTwistReversal, ExactZeroCrossingIsStillMovingAndKeepsAcceleration) { - CartesianTwistLimiter limiter; - limiter.setLinearConstraints(1, 1, 4); - limiter.initialize(y(.02)); - limiter.setTargetTwist(y(-.02), CartesianFrame::Base); - for (int i = 0; i < 100; ++i) limiter.update(dt, Eigen::Matrix3d::Identity()); - EXPECT_NEAR(limiter.getTwistBase().y(), 0, 1e-12); - EXPECT_TRUE(limiter.isMoving()); - EXPECT_LT(limiter.getAccelerationBase().y(), -.39); - EXPECT_LT(limiter.update(dt, Eigen::Matrix3d::Identity()).y(), -.0003); -} -TEST(CartesianTwistReversal, StopFromEitherDirectionSettlesWithoutReversing) { - for (double v : {.08, -.08}) { - CartesianTwistLimiter limiter; - limiter.setLinearConstraints(1, 3, 10); - limiter.initialize(y(v)); - limiter.stop(); - for (int i = 0; i < 1000; ++i) { - EXPECT_GE(limiter.update(dt, Eigen::Matrix3d::Identity()).y() * v, -1e-12); - } - EXPECT_FALSE(limiter.isMoving()); - EXPECT_NEAR(limiter.getTwistBase().norm(), 0, 1e-12); - } -} -TEST(CartesianTwistReversal, FeedbackPreservesNegativeVelocityOnLockedAxis) { - CartesianTwistLimiter limiter; - limiter.setLinearConstraints(1, 3, 10); - limiter.initialize(y(.08)); - limiter.setTargetTwist(y(-.08), CartesianFrame::Base); - for (int i = 0; i < 400; ++i) limiter.update(dt, Eigen::Matrix3d::Identity()); - for (int i = 0; i < 10; ++i) { - limiter.synchronize(y(-.08), dt, true); - EXPECT_NEAR(limiter.update(dt, Eigen::Matrix3d::Identity()).y(), -.08, 1e-9); - } -} -TEST(CartesianTwistReversal, NonCollinearChangeStopsBeforeSwitchingAxis) { - CartesianTwistLimiter limiter; - limiter.setLinearConstraints(1, 3, 10); - limiter.initialize(y(.08)); - Twist x = Twist::Zero(); x.x() = .08; - limiter.setTargetTwist(x, CartesianFrame::Base); - for (int i = 0; i < 1000; ++i) { - const auto v = limiter.update(dt, Eigen::Matrix3d::Identity()); - EXPECT_FALSE(v.x() > 1e-9 && std::abs(v.y()) > 1e-9); - EXPECT_LE(limiter.getJerkBase().norm(), 10 + 1e-6); - } - EXPECT_NEAR(limiter.getTwistBase().x(), .08, 1e-9); -} - -TEST(CartesianTwistReversal, SwitchingToStreamingPreservesNegativePhysicalVelocity) { - for (const int reverse_ticks : {150, 250, 500}) { - SCOPED_TRACE(reverse_ticks); - CartesianTwistLimiter reference; - reference.setLinearConstraints(1, 3, 10); - reference.initialize(y(.08)); - reference.setTargetTwist(y(-.08), CartesianFrame::Base); - for (int i = 0; i < reverse_ticks; ++i) reference.update(dt, Eigen::Matrix3d::Identity()); - ASSERT_LT(reference.getTwistBase().y(), 0); - auto streaming = reference; - streaming.setContinuousLinearReversal(false); - EXPECT_NEAR((streaming.getTwistBase() - reference.getTwistBase()).norm(), 0, 1e-12); - for (int i = 0; i < 500; ++i) { - const auto expected = reference.update(dt, Eigen::Matrix3d::Identity()); - const auto actual = streaming.update(dt, Eigen::Matrix3d::Identity()); - EXPECT_NEAR((actual - expected).norm(), 0, 1e-9); - EXPECT_LE(streaming.getJerkBase().norm(), 10 + 1e-6); - } - } -} -} -} diff --git a/cmvr-es/algorithms/motion_planner/base_motion/joint_trajectory/joint_trajectory_planner.h b/cmvr-es/algorithms/motion_planner/base_motion/joint_trajectory/joint_trajectory_planner.h deleted file mode 100644 index fcb64bb7..00000000 --- a/cmvr-es/algorithms/motion_planner/base_motion/joint_trajectory/joint_trajectory_planner.h +++ /dev/null @@ -1,90 +0,0 @@ -// -// Created by lgv on 11/7/25. -// - -#pragma once - -#include -#include -#include - -#include -#include -#include -#include - -namespace cmvr { - // 统一轨迹接口 - struct ITrajectory { - virtual ~ITrajectory() = default; - virtual toppra::Bound timeInterval() const = 0; - virtual Eigen::VectorXd q(double t) const = 0; - virtual Eigen::VectorXd qd(double t) const = 0; - virtual Eigen::VectorXd qdd(double t) const = 0; - }; - using TrajPtr = std::shared_ptr; - - struct TrajSample { - double t{}; - Eigen::VectorXd q; // DoF x 1 - Eigen::VectorXd qd; // DoF x 1 - Eigen::VectorXd qdd; // DoF x 1 - }; - - // 三种几何路径 - enum class PathType { Linear, - CubicHermite, - Quintic, - // 三次B样条 - Natural }; - class JointTrajectoryPlanner { - public: - - explicit JointTrajectoryPlanner(PathType p):path_type_(p){}; - JointTrajectoryPlanner()=default; - virtual ~JointTrajectoryPlanner() = default; - - virtual bool plan(const std::vector& start_joints, - const std::vector& goal_joints, - TrajPtr& traj) { - return false; - } - - virtual bool plan(const std::vector>& waypoints, TrajPtr& traj){ - return false; - } - - // 采样函数:从 ITrajectory 生成采样序列 dt(s) - virtual std::vector sampleTrajectory(const TrajPtr& traj, double dt) { - - return {}; - } - - virtual bool writeTrajectoryCsv(const std::string& filename,const std::vector& samples) { - - return false; - } - - // 对称限:[-v_max, v_max]、[-a_max, a_max] - virtual void setSymmetricLimits(const std::vector &v_max,const std::vector &a_max){ - v_max_ = v_max; - a_max_ = a_max; - } - - // 可调网格密度(默认 150/300) - virtual void setGridSizes(int N, int N_high) - { - N_grid_ = N; - N_grid_high_ = N_high; - } - - // 切换几何路径类型 - virtual void setPathType(PathType p){path_type_ = p;} - protected: - PathType path_type_{PathType::Quintic}; - int N_grid_ = 150; - int N_grid_high_ = 300; - std::vector v_max_, a_max_; - - }; -} diff --git a/cmvr-es/algorithms/motion_planner/base_motion/joint_trajectory/toppra/include/toppra_joint_trajectory_planner.h b/cmvr-es/algorithms/motion_planner/base_motion/joint_trajectory/toppra/include/toppra_joint_trajectory_planner.h deleted file mode 100644 index f344fc1e..00000000 --- a/cmvr-es/algorithms/motion_planner/base_motion/joint_trajectory/toppra/include/toppra_joint_trajectory_planner.h +++ /dev/null @@ -1,209 +0,0 @@ -#pragma once - -#include -#include -#include - -#include "../../joint_trajectory_planner.h" -#include -#include -#include - -namespace cmvr { - // 适配器:ConstAccel - class ConstAccelTraj : public ITrajectory { - public: - explicit ConstAccelTraj(std::shared_ptr p); - - toppra::Bound timeInterval() const override; - - Eigen::VectorXd q(double t) const override; - - Eigen::VectorXd qd(double t) const override; - - Eigen::VectorXd qdd(double t) const override; - - private: - std::shared_ptr impl_; - }; - - // 适配器:Spline - class SplineTraj : public ITrajectory { - public: - SplineTraj(const std::shared_ptr &path, - const toppra::Vector &grid, - const toppra::Vector &vsq); - - toppra::Bound timeInterval() const override; - - Eigen::VectorXd q(double t) const override; - - Eigen::VectorXd qd(double t) const override; - - Eigen::VectorXd qdd(double t) const override; - - private: - toppra::parametrizer::Spline impl_; - }; - - // 具体规划器:一次/三次/五次可切换;ConstAccel 校验失败自动回退 Spline - class ToppraJointTrajectoryPlanner : public JointTrajectoryPlanner { - public: - explicit ToppraJointTrajectoryPlanner(PathType type = PathType::Quintic); - - - // 统一入口:两点/多点皆可 - bool plan(const std::vector > &waypoints, TrajPtr &traj_out) override; - - // 兼容旧 API(可选):转发为两点的统一入口 - bool plan(const std::vector &start_joints, - const std::vector &goal_joints, - TrajPtr &traj_out) override; - - std::vector sampleTrajectory(const TrajPtr &traj, double dt) override; - - bool writeTrajectoryCsv(const std::string &filename, const std::vector &samples) override; - - private: - // —— 几何路径统一分发 —— - std::shared_ptr - buildPathUnified(const std::vector &q, - const std::vector &S); - - // 二点专用 - std::shared_ptr - buildTwoPointPath(const Eigen::VectorXd &q0, const Eigen::VectorXd &q1); - - std::shared_ptr - buildLinearTwo(const Eigen::VectorXd &q0, const Eigen::VectorXd &q1); - - std::shared_ptr - buildCubicHermiteTwo(const Eigen::VectorXd &q0, const Eigen::VectorXd &q1); - - std::shared_ptr - buildQuinticRestToRestTwo(const Eigen::VectorXd &q0, const Eigen::VectorXd &q1); - - std::shared_ptr - buildNaturalTwo(const Eigen::VectorXd &q0, const Eigen::VectorXd &q1); - - // 多点 - std::shared_ptr - buildLinearMulti(const std::vector &q, - const std::vector &S); - - std::shared_ptr - buildCubicHermiteMulti(const std::vector &q, - const std::vector &S); - - std::shared_ptr - buildQuinticC2Multi(const std::vector &q, - const std::vector &S); - - std::shared_ptr - buildNaturalMulti(const std::vector &q, - const std::vector &S); - - // —— 工具:限幅/参数/估计 —— - bool ensureLimitsSized(std::size_t DoF); - - static void sanitizeVsq(toppra::Vector &v); - - - // Joint-space chord length keeps the parameterization independent of - // how densely the same geometric path is sampled. - static std::vector - makeSChordLength(const std::vector &q) { - const size_t M = q.size(); - std::vector S(M, 0.0); - for (size_t i = 1; i < M; ++i) { - S[i] = S[i - 1] + (q[i] - q[i - 1]).norm(); - } - return S; - } - - // Catmull–Rom(centripetal)估计结点几何速度 v(端点=0) - static std::vector - estimateVelsCatmull(const std::vector &q, - const std::vector &S) { - const size_t M = q.size(); - const int DoF = static_cast(q[0].size()); - std::vector v(M, Eigen::VectorXd::Zero(DoF)); - if (M <= 2) return v; - for (size_t i = 1; i + 1 < M; ++i) { - double ds0 = std::max(S[i] - S[i - 1], 1e-12); - double ds1 = std::max(S[i + 1] - S[i], 1e-12); - v[i] = ((q[i + 1] - q[i]) / ds1 * ds0 + (q[i] - q[i - 1]) / ds0 * ds1) / (ds0 + ds1); - } - return v; - } - - // 对内点几何速度限幅,抑制过冲(k∈[0.5,1.0]) - static void clampNodeVels(std::vector &v, - const std::vector &q, - const std::vector &S, - double k = 1.0) { - const size_t M = q.size(); - if (M <= 2) return; - for (size_t i = 1; i + 1 < M; ++i) { - const double ds0 = std::max(S[i] - S[i - 1], 1e-12); - const double ds1 = std::max(S[i + 1] - S[i], 1e-12); - const double slope0 = (q[i] - q[i - 1]).norm() / ds0; - const double slope1 = (q[i + 1] - q[i]).norm() / ds1; - const double vmax = k * std::min(slope0, slope1); - double n = v[i].norm(); - if (n > vmax) v[i] *= (vmax / n); - } - } - - // 估计结点几何加速度 a(端点=0;中点二阶差分,按 s 尺度) - static std::vector - estimateAccelsSecondDiff(const std::vector &q, - const std::vector &S) { - const size_t M = q.size(); - const int DoF = static_cast(q[0].size()); - std::vector a(M, Eigen::VectorXd::Zero(DoF)); - if (M <= 2) return a; - for (size_t i = 1; i + 1 < M; ++i) { - double h0 = std::max(S[i] - S[i - 1], 1e-12); // 左间距 - double h1 = std::max(S[i + 1] - S[i], 1e-12); // 右间距 - double denom = 0.5 * (h0 + h1); // 局部尺度 - // 非均匀中心二阶差分(更精确): - // a ≈ 2 * [ (q_{i+1}-q_i)/h1 - (q_i - q_{i-1})/h0 ] / (h0 + h1) - a[i] = 2.0 * ((q[i + 1] - q[i]) / h1 - (q[i] - q[i - 1]) / h0) / (h0 + h1); - } - return a; - } - - - // τ→s 变元:把局部 Quintic(τ) 的系数 c_tau[0..5](τ^0..τ^5) - // 变成全局 s 的系数 alpha[0..5](s^0..s^5),其中 τ = (s - S_k) / ds - static inline void localQuinticToGlobalCoeffs( - const std::array &c_tau, // c0..c5(DoF维向量) - double Sk, double ds, - std::array &alpha // α0..α5(DoF维向量) - ) { - static const double C[6][6] = { - // binomial(n,m) - {1, 0, 0, 0, 0, 0}, - {1, 1, 0, 0, 0, 0}, - {1, 2, 1, 0, 0, 0}, - {1, 3, 3, 1, 0, 0}, - {1, 4, 6, 4, 1, 0}, - {1, 5, 10, 10, 5, 1} - }; - const double eps = 1e-12; - ds = std::max(ds, eps); - - for (int m = 0; m <= 5; ++m) alpha[m].setZero(c_tau[0].size()); - - // α_m = Σ_{n=m..5} c_n * C(n,m) * (-S_k)^{n-m} / ds^{n} - for (int n = 0; n <= 5; ++n) { - double invdsn = std::pow(ds, -n); - for (int m = 0; m <= n; ++m) { - double factor = C[n][m] * std::pow(-Sk, n - m) * invdsn; - alpha[m].noalias() += factor * c_tau[n]; - } - } - } - }; -} // namespace cmvr diff --git a/cmvr-es/algorithms/motion_planner/base_motion/joint_trajectory/toppra/src/toppra_joint_trajectory_planner.cpp b/cmvr-es/algorithms/motion_planner/base_motion/joint_trajectory/toppra/src/toppra_joint_trajectory_planner.cpp deleted file mode 100644 index 040b59e1..00000000 --- a/cmvr-es/algorithms/motion_planner/base_motion/joint_trajectory/toppra/src/toppra_joint_trajectory_planner.cpp +++ /dev/null @@ -1,527 +0,0 @@ -#include -#include -#include -#include -#include -#include "algorithms/motion_planner/base_motion/joint_trajectory/toppra/include/toppra_joint_trajectory_planner.h" - -#include -#include -#include -#include - -namespace cmvr { - namespace { - - class TimeScaledTrajectory final : public ITrajectory { - public: - TimeScaledTrajectory(TrajPtr source, const double scale) - : source_(std::move(source)), scale_(scale), source_interval_(source_->timeInterval()) - { - } - - toppra::Bound timeInterval() const override - { - toppra::Bound interval; - interval << source_interval_[0], - source_interval_[0] + - (source_interval_[1] - source_interval_[0]) * scale_; - return interval; - } - - Eigen::VectorXd q(const double t) const override - { - return source_->q(sourceTime_(t)); - } - - Eigen::VectorXd qd(const double t) const override - { - return source_->qd(sourceTime_(t)) / scale_; - } - - Eigen::VectorXd qdd(const double t) const override - { - return source_->qdd(sourceTime_(t)) / (scale_ * scale_); - } - - private: - double sourceTime_(const double output_time) const - { - return std::clamp( - source_interval_[0] + - (output_time - source_interval_[0]) / scale_, - source_interval_[0], - source_interval_[1]); - } - - TrajPtr source_; - double scale_{1.0}; - toppra::Bound source_interval_; - }; - - bool enforceSampledLimits(const TrajPtr& source, - const std::vector& velocity_limits, - const std::vector& acceleration_limits, - const std::size_t waypoint_count, - TrajPtr& output) - { - if (!source || velocity_limits.empty() || - velocity_limits.size() != acceleration_limits.size()) { - return false; - } - const auto interval = source->timeInterval(); - const double duration = interval[1] - interval[0]; - if (!std::isfinite(duration) || duration <= 0.0) { - return false; - } - - const std::size_t time_samples = static_cast( - std::ceil(duration / 0.001)) + 1; - const std::size_t path_samples = waypoint_count * 20; - const std::size_t sample_count = std::clamp( - std::max({std::size_t{1000}, time_samples, path_samples}), - std::size_t{1000}, - std::size_t{200000}); - - double required_scale = 1.0; - for (std::size_t sample = 0; sample < sample_count; ++sample) { - const double ratio = static_cast(sample) / - static_cast(sample_count - 1); - const double time = interval[0] + duration * ratio; - const Eigen::VectorXd velocity = source->qd(time); - const Eigen::VectorXd acceleration = source->qdd(time); - if (!velocity.allFinite() || !acceleration.allFinite() || - velocity.size() != static_cast(velocity_limits.size()) || - acceleration.size() != - static_cast(acceleration_limits.size())) { - return false; - } - for (Eigen::Index joint = 0; joint < velocity.size(); ++joint) { - const std::size_t index = static_cast(joint); - required_scale = std::max( - required_scale, - std::abs(velocity[joint]) / velocity_limits[index]); - required_scale = std::max( - required_scale, - std::sqrt(std::abs(acceleration[joint]) / - acceleration_limits[index])); - } - } - - constexpr double kNumericalMargin = 1.001; - output = std::make_shared( - source, required_scale * kNumericalMargin); - return true; - } - - } // namespace - - // ===== ConstAccelTraj ===== - ConstAccelTraj::ConstAccelTraj(std::shared_ptr p) - : impl_(std::move(p)) { - } - - toppra::Bound ConstAccelTraj::timeInterval() const { return impl_->pathInterval(); } - Eigen::VectorXd ConstAccelTraj::q(double t) const { return impl_->eval_single(t, 0); } - Eigen::VectorXd ConstAccelTraj::qd(double t) const { return impl_->eval_single(t, 1); } - Eigen::VectorXd ConstAccelTraj::qdd(double t) const { return impl_->eval_single(t, 2); } - - // ===== SplineTraj ===== - SplineTraj::SplineTraj(const std::shared_ptr &path, - const toppra::Vector &grid, - const toppra::Vector &vsq) - : impl_(path, grid, vsq) { - } - - toppra::Bound SplineTraj::timeInterval() const { return impl_.pathInterval(); } - Eigen::VectorXd SplineTraj::q(double t) const { return impl_.eval_single(t, 0); } - Eigen::VectorXd SplineTraj::qd(double t) const { return impl_.eval_single(t, 1); } - Eigen::VectorXd SplineTraj::qdd(double t) const { return impl_.eval_single(t, 2); } - - // ===== ToppraJointTrajectoryPlanner ===== - ToppraJointTrajectoryPlanner::ToppraJointTrajectoryPlanner(PathType type) :JointTrajectoryPlanner(type) { - } - - - - bool ToppraJointTrajectoryPlanner::ensureLimitsSized(std::size_t DoF) { - if (v_max_.size() != DoF) v_max_.assign(DoF, 1.5); - if (a_max_.size() != DoF) a_max_.assign(DoF, 3.0); - return true; - } - - void ToppraJointTrajectoryPlanner::sanitizeVsq(toppra::Vector &v) { - for (int i = 0; i < v.size(); ++i) if (v[i] < 0 && v[i] > -1e-10) v[i] = 0; - if (v.size() > 0) { - v[0] = 0; - v[v.size() - 1] = 0; - } - } - // ===== 统一入口:两点/多点 ===== - bool ToppraJointTrajectoryPlanner::plan(const std::vector>& waypoints, - TrajPtr& traj_out) { - traj_out.reset(); - if (waypoints.size() < 2) return false; - const size_t DoF = waypoints.front().size(); - if (DoF == 0) return false; - for (const auto& w : waypoints) { - if (w.size() != DoF) return false; - for (const double value : w) { - if (!std::isfinite(value)) return false; - } - } - if (!ensureLimitsSized(DoF)) return false; - for (size_t joint = 0; joint < DoF; ++joint) { - if (!std::isfinite(v_max_[joint]) || v_max_[joint] <= 0.0 || - !std::isfinite(a_max_[joint]) || a_max_[joint] <= 0.0) { - return false; - } - } - - std::vector q; - q.reserve(waypoints.size()); - constexpr double kDuplicateDistance = 1e-10; - for (const auto& waypoint : waypoints) { - Eigen::VectorXd value = Eigen::Map( - waypoint.data(), static_cast(DoF)); - if (q.empty() || (value - q.back()).norm() > kDuplicateDistance) { - q.push_back(std::move(value)); - } - } - if (q.size() < 2) return false; - const size_t M = q.size(); - - const std::vector S = M == 2 - ? std::vector{0.0, 1.0} - : makeSChordLength(q); - - // 几何路径 - auto path = buildPathUnified(q, S); - if (!path) return false; - - // 约束 - Eigen::VectorXd vmax(DoF), amax(DoF); - for (size_t i=0;i(-vmax, vmax); - auto acc = std::make_shared(-amax, amax); - vel->discretizationType(toppra::DiscretizationType::Collocation); - acc->discretizationType(toppra::DiscretizationType::Interpolation); - toppra::LinearConstraintPtrs constraints{vel, acc}; - - // TOPPRA - toppra::algorithm::TOPPRA algo{constraints, path}; - auto solve_once = [&](const int requested_intervals)->bool{ - const int segment_count = static_cast(M - 1); - const int subdivisions = std::max( - 1, (requested_intervals + segment_count - 1) / segment_count); - toppra::Vector grid(segment_count * subdivisions + 1); - Eigen::Index index = 0; - for (int segment = 0; segment < segment_count; ++segment) { - const double start = S[static_cast(segment)]; - const double length = S[static_cast(segment + 1)] - start; - for (int subdivision = 0; subdivision < subdivisions; ++subdivision) { - grid[index++] = start + length * - static_cast(subdivision) / - static_cast(subdivisions); - } - } - grid[index] = S.back(); - algo.setGridpoints(grid); - algo.solver(std::make_shared()); - return algo.computePathParametrization(0.0, 0.0) == toppra::ReturnCode::OK; - }; - if (!solve_once(N_grid_)) { - if (!solve_once(N_grid_high_)) return false; - } - - const auto data = algo.getParameterizationData(); - toppra::Vector grid = data.gridpoints; - toppra::Vector vsq = data.parametrization; - - TrajPtr candidate; - auto ca = std::make_shared(path, grid, vsq); - if (ca->validate()) { - candidate = std::make_shared(std::move(ca)); - } else { - sanitizeVsq(vsq); - try { - candidate = std::make_shared(path, grid, vsq); - (void) candidate->timeInterval(); - } catch (...) { - return false; - } - } - return enforceSampledLimits(candidate, v_max_, a_max_, M, traj_out); - } - - - bool ToppraJointTrajectoryPlanner::plan(const std::vector& start_joints, - const std::vector& goal_joints, - TrajPtr& traj_out) { - if (start_joints.empty() || start_joints.size()!=goal_joints.size()) return false; - std::vector> wpts{start_joints, goal_joints}; - return plan(wpts, traj_out); - } - - - std::shared_ptr - ToppraJointTrajectoryPlanner::buildPathUnified(const std::vector& q, - const std::vector& S) { - const size_t M = q.size(); - if (M == 2) return buildTwoPointPath(q[0], q[1]); - switch (path_type_) { - case PathType::Linear: return buildLinearMulti(q, S); - case PathType::CubicHermite: return buildCubicHermiteMulti(q, S); - case PathType::Natural: return buildNaturalMulti(q, S); - case PathType::Quintic: - default: return buildQuinticC2Multi(q, S); - } - } - - - std::shared_ptr - ToppraJointTrajectoryPlanner::buildTwoPointPath(const Eigen::VectorXd& q0, const Eigen::VectorXd& q1) { - switch (path_type_) { - case PathType::Linear: return buildLinearTwo(q0, q1); - case PathType::CubicHermite: return buildCubicHermiteTwo(q0, q1); - case PathType::Natural: return buildNaturalTwo(q0, q1); - case PathType::Quintic: - default: return buildQuinticRestToRestTwo(q0, q1); - } - } - - // 二点:Linear —— - std::shared_ptr - ToppraJointTrajectoryPlanner::buildLinearTwo(const Eigen::VectorXd& q0, const Eigen::VectorXd& q1) { - const size_t DoF = static_cast(q0.size()); - toppra::Matrix seg(2, DoF); - seg.row(0) = (q1 - q0).transpose(); - seg.row(1) = q0.transpose(); - return std::make_shared( - toppra::Matrices{seg}, std::vector{0.0, 1.0}); - } - - // 二点:Cubic Hermite(端点速度 0) —— - std::shared_ptr - ToppraJointTrajectoryPlanner::buildCubicHermiteTwo(const Eigen::VectorXd& q0, const Eigen::VectorXd& q1) { - toppra::Vectors pos{q0, q1}; - toppra::Vectors vel{Eigen::VectorXd::Zero(q0.size()), - Eigen::VectorXd::Zero(q1.size())}; - std::vector s{0.0, 1.0}; - auto herm = toppra::PiecewisePolyPath::CubicHermiteSpline(pos, vel, s); - return std::make_shared(herm); - } - - // 二点:Quintic rest-to-rest —— - std::shared_ptr - ToppraJointTrajectoryPlanner::buildQuinticRestToRestTwo(const Eigen::VectorXd& q0, const Eigen::VectorXd& q1) { - const size_t DoF = static_cast(q0.size()); - const Eigen::VectorXd dq = q1 - q0; - toppra::Matrix seg(6, DoF); // x^5..x^0 - seg.row(0) = ( 6.0 * dq).transpose(); - seg.row(1) = (-15.0 * dq).transpose(); - seg.row(2) = (10.0 * dq).transpose(); - seg.row(3).setZero(); seg.row(4).setZero(); - seg.row(5) = q0.transpose(); - return std::make_shared( - toppra::Matrices{seg}, std::vector{0.0, 1.0}); - } - - std::shared_ptr - ToppraJointTrajectoryPlanner::buildNaturalTwo(const Eigen::VectorXd& q0, const Eigen::VectorXd& q1) { - using PWP = toppra::PiecewisePolyPath; - - // positions(两点) - toppra::Vectors pos{ q0, q1 }; - - // 自变量S:两点用等距最简单 - toppra::Vector S(2); - S[0] = 0.0; S[1] = 1.0; - - - toppra::BoundaryCondFull bcA = { toppra::BoundaryCond("clamped"), - toppra::BoundaryCond("clamped") }; - auto path = PWP::CubicSpline(pos, S, bcA); - return std::make_shared(path); - - // 手动指定二阶导为 0 - // const int DoF = static_cast(q0.size()); - // toppra::BoundaryCondFull bcB = { - // toppra::BoundaryCond(2, Eigen::VectorXd::Zero(DoF)), - // toppra::BoundaryCond(2, Eigen::VectorXd::Zero(DoF)) - // }; - // auto path2 = PWP::CubicSpline(pos, S, bcB); - // return std::make_shared(path2); - } - - - // —— 多点:Linear —— - std::shared_ptr - ToppraJointTrajectoryPlanner::buildLinearMulti(const std::vector& q, - const std::vector& S) { - const size_t M = q.size(), DoF = q[0].size(); - toppra::Matrices segs; segs.reserve(M-1); - for (size_t k=0;k+1(S[k+1]-S[k], 1e-12); - toppra::Matrix seg(2, DoF); - Eigen::RowVectorXd A1 = ((q[k+1]-q[k])/ds).transpose(); - Eigen::RowVectorXd A0 = q[k].transpose(); - seg.row(0)=A1; seg.row(1)=A0; - segs.emplace_back(std::move(seg)); - } - return std::make_shared(segs, std::vector(S.begin(), S.end())); - } - - // —— 多点:Cubic Hermite —— - std::shared_ptr - ToppraJointTrajectoryPlanner::buildCubicHermiteMulti(const std::vector& q, - const std::vector& S) { - auto v = estimateVelsCatmull(q, S); - clampNodeVels(v, q, S, /*k=*/1.0); - toppra::Vectors pos(q.begin(), q.end()); - toppra::Vectors vel(v.begin(), v.end()); - auto herm = toppra::PiecewisePolyPath::CubicHermiteSpline(pos, vel, S); - return std::make_shared(herm); - } - - - std::shared_ptr - ToppraJointTrajectoryPlanner::buildNaturalMulti(const std::vector& q, - const std::vector& S) { - using PWP = toppra::PiecewisePolyPath; - - const size_t M = q.size(); - if (M < 2 || M != S.size()) return nullptr; - - // positions - toppra::Vectors pos(q.begin(), q.end()); - - // times(全局自变量,需严格递增) - toppra::Vector times(static_cast(M)); - for (size_t i = 0; i < M; ++i) times[static_cast(i)] = S[i]; - - //Natural - toppra::BoundaryCondFull bcA = { toppra::BoundaryCond("clamped"), - toppra::BoundaryCond("clamped") }; - auto path = PWP::CubicSpline(pos, times, bcA); - return std::make_shared(path); - - // 手动指定二阶导为 0 —— - // const int DoF = static_cast(q[0].size()); - // toppra::BoundaryCondFull bcB = { - // toppra::BoundaryCond(2, Eigen::VectorXd::Zero(DoF)), - // toppra::BoundaryCond(2, Eigen::VectorXd::Zero(DoF)) - // }; - // auto path2 = PWP::CubicSpline(pos, times, bcB); - // return std::make_shared(path2); - } - - // —— 多点:Quintic C² —— - std::shared_ptr - ToppraJointTrajectoryPlanner::buildQuinticC2Multi(const std::vector& q, - const std::vector& S) { - const size_t M = q.size(), DoF = q[0].size(); - auto v = estimateVelsCatmull(q, S); - clampNodeVels(v, q, S, /*k=*/1.0); - auto a = estimateAccelsSecondDiff(q, S); - - toppra::Matrices segs; segs.reserve(M-1); - for (size_t k=0;k+1(S[k+1]-S[k], 1e-12); - const Eigen::VectorXd& q0=q[k]; const Eigen::VectorXd& q1=q[k+1]; - const Eigen::VectorXd& v0=v[k]; const Eigen::VectorXd& v1=v[k+1]; - const Eigen::VectorXd& a0=a[k]; const Eigen::VectorXd& a1=a[k+1]; - const Eigen::VectorXd dq = q1-q0; - - Eigen::VectorXd A0 = q0; - Eigen::VectorXd A1 = v0 * ds; - Eigen::VectorXd A2 = a0 * (ds*ds) / 2.0; - Eigen::VectorXd C3 = ( 10.0*dq - (6.0*A1 + 1.5*(a0*ds*ds)) - (4.0*(v1*ds) - 0.5*(a1*ds*ds)) ); - Eigen::VectorXd C4 = (-15.0*dq + (8.0*A1 + 1.5*(a0*ds*ds)) + (7.0*(v1*ds) - 1.0*(a1*ds*ds)) ); - Eigen::VectorXd C5 = ( 6.0*dq - (3.0*A1 + 0.5*(a0*ds*ds)) - (3.0*(v1*ds) - 0.5*(a1*ds*ds)) ); - - toppra::Matrix seg(6, DoF); - seg.row(0)=(C5 / std::pow(ds, 5)).transpose(); - seg.row(1)=(C4 / std::pow(ds, 4)).transpose(); - seg.row(2)=(C3 / std::pow(ds, 3)).transpose(); - seg.row(3)=(a0 / 2.0).transpose(); - seg.row(4)=v0.transpose(); - seg.row(5)=A0.transpose(); - segs.emplace_back(std::move(seg)); - } - return std::make_shared(segs, std::vector(S.begin(), S.end())); - } - - std::vector ToppraJointTrajectoryPlanner::sampleTrajectory(const TrajPtr &traj, double dt) { - std::vector out; - if (!traj) return out; - - auto I = traj->timeInterval(); - const double t0 = I[0]; - const double t1 = I[1]; - if (!(t1 > t0)) return out; - - // 2) 生成时间序列(含端点,考虑浮点误差) - constexpr double EPS = 1e-12; - std::vector ts; - ts.reserve(static_cast(std::max(2.0, std::ceil((t1 - t0) / dt) + 1.0))); - - // 起点 - ts.push_back(t0); - - // 中间等间隔点 - for (double t = t0 + dt; t <= t1 - EPS; t += dt) { - // 防守式:避免因累积误差越过 t1 - ts.push_back((t > t1) ? t1 : t); - } - - // 终点(若未加入) - if (ts.empty() || std::fabs(ts.back() - t1) > EPS) { - ts.push_back(t1); - } else { - // 若最后一个点因误差“很接近 t1”,直接覆盖为 t1 - ts.back() = t1; - } - - // 3) 采样 - out.reserve(ts.size()); - for (double t: ts) { - TrajSample s; - s.t = t; - s.q = traj->q(t); - s.qd = traj->qd(t); - s.qdd = traj->qdd(t); - out.emplace_back(std::move(s)); - } - return out; - } - - - bool ToppraJointTrajectoryPlanner::writeTrajectoryCsv(const std::string &filename, const std::vector &samples) { - if (samples.empty()) return false; - - const int dof = static_cast(samples.front().q.size()); - std::ofstream ofs(filename); - if (!ofs) return false; - - ofs.setf(std::ios::fixed); - ofs << std::setprecision(10); - - // 表头 - ofs << "t"; - for (int j=1;j<=dof;++j) ofs << ",q" << j; - for (int j=1;j<=dof;++j) ofs << ",qd" << j; - for (int j=1;j<=dof;++j) ofs << ",qdd" << j; - ofs << "\n"; - - // 内容 - for (const auto& s : samples) { - ofs << s.t; - for (int j=0;j -#include -#include -#include -#include -#include -#include - -#include - -#include "joint_trajectory/toppra/include/toppra_joint_trajectory_planner.h" - -namespace cmvr { -namespace { - -constexpr std::size_t kDof = 7; -constexpr double kVelocityLimit = 0.15; -constexpr double kAccelerationLimit = 0.3; -constexpr double kSamplePeriodS = 0.002; - -std::vector> makeSmoothWaypoints(const std::size_t count) -{ - constexpr double kPi = 3.14159265358979323846; - std::vector> waypoints; - waypoints.reserve(count); - for (std::size_t i = 0; i < count; ++i) { - const double s = static_cast(i) / - static_cast(count - 1); - std::vector q(kDof, 0.0); - q[0] = 0.40 * s + 0.03 * std::sin(2.0 * kPi * s); - q[1] = -0.25 * s + 0.04 * std::sin(kPi * s); - q[2] = 0.20 * s * s; - q[3] = 0.30 * std::sin(0.5 * kPi * s); - q[4] = -0.12 * s + 0.02 * std::sin(3.0 * kPi * s); - q[5] = 0.15 * s; - q[6] = -0.08 * std::sin(kPi * s); - waypoints.push_back(std::move(q)); - } - return waypoints; -} - -double maxAbs(const Eigen::VectorXd& value) -{ - double result = 0.0; - for (Eigen::Index i = 0; i < value.size(); ++i) { - result = std::max(result, std::abs(value[i])); - } - return result; -} - -double positionError(const Eigen::VectorXd& actual, - const std::vector& expected) -{ - if (actual.size() != static_cast(expected.size())) { - return std::numeric_limits::infinity(); - } - double squared_error = 0.0; - for (Eigen::Index i = 0; i < actual.size(); ++i) { - const double error = actual[i] - expected[static_cast(i)]; - squared_error += error * error; - } - return std::sqrt(squared_error); -} - -struct PlanMetrics { - bool success{false}; - double planning_ms{0.0}; - double duration_s{0.0}; - double max_velocity{0.0}; - double max_acceleration{0.0}; - double max_waypoint_error{0.0}; - double start_error{0.0}; - double end_error{0.0}; - std::size_t sample_count{0}; -}; - -PlanMetrics planAndMeasure(const std::vector>& waypoints, - const PathType path_type = PathType::Linear) -{ - PlanMetrics metrics; - ToppraJointTrajectoryPlanner planner(path_type); - planner.setSymmetricLimits( - std::vector(kDof, kVelocityLimit), - std::vector(kDof, kAccelerationLimit)); - planner.setGridSizes(150, 300); - - TrajPtr trajectory; - const auto start = std::chrono::steady_clock::now(); - metrics.success = planner.plan(waypoints, trajectory); - metrics.planning_ms = std::chrono::duration( - std::chrono::steady_clock::now() - start).count(); - if (!metrics.success || !trajectory) { - return metrics; - } - - const auto interval = trajectory->timeInterval(); - metrics.duration_s = interval[1] - interval[0]; - const auto samples = planner.sampleTrajectory(trajectory, kSamplePeriodS); - metrics.sample_count = samples.size(); - if (samples.empty()) { - metrics.success = false; - return metrics; - } - metrics.start_error = positionError(samples.front().q, waypoints.front()); - metrics.end_error = positionError(samples.back().q, waypoints.back()); - - for (const auto& sample : samples) { - if (!std::isfinite(sample.t) || !sample.q.allFinite() || - !sample.qd.allFinite() || !sample.qdd.allFinite()) { - metrics.success = false; - return metrics; - } - metrics.max_velocity = std::max(metrics.max_velocity, maxAbs(sample.qd)); - metrics.max_acceleration = std::max( - metrics.max_acceleration, maxAbs(sample.qdd)); - } - - std::size_t sample_index = 0; - for (const auto& waypoint : waypoints) { - while (sample_index + 1 < samples.size() && - positionError(samples[sample_index + 1].q, waypoint) <= - positionError(samples[sample_index].q, waypoint)) { - ++sample_index; - } - metrics.max_waypoint_error = std::max( - metrics.max_waypoint_error, - positionError(samples[sample_index].q, waypoint)); - } - return metrics; -} - -const char* pathTypeName(const PathType path_type) -{ - switch (path_type) { - case PathType::Linear: return "Linear"; - case PathType::CubicHermite: return "CubicHermite"; - case PathType::Quintic: return "Quintic"; - case PathType::Natural: return "Natural"; - } - return "Unknown"; -} - -void printMetrics(const std::size_t waypoint_count, const PlanMetrics& metrics) -{ - std::cout << "[ToppraMultiWaypointTest] waypoints=" << waypoint_count - << ", success=" << metrics.success - << ", planning_ms=" << metrics.planning_ms - << ", duration_s=" << metrics.duration_s - << ", samples=" << metrics.sample_count - << ", max_qd=" << metrics.max_velocity - << ", max_qdd=" << metrics.max_acceleration - << ", max_waypoint_error=" << metrics.max_waypoint_error - << ", start_error=" << metrics.start_error - << ", end_error=" << metrics.end_error - << std::endl; -} - -TEST(ToppraMultiWaypointTest, SmoothSevenDofPathScalesToThousandsOfWaypoints) -{ - double reference_duration_s = 0.0; - for (const std::size_t count : {10U, 100U, 300U, 1000U, 3000U}) { - const auto metrics = planAndMeasure(makeSmoothWaypoints(count)); - printMetrics(count, metrics); - ASSERT_TRUE(metrics.success) << "waypoint_count=" << count; - EXPECT_GT(metrics.duration_s, 0.0) << "waypoint_count=" << count; - EXPECT_LE(metrics.max_velocity, kVelocityLimit + 1e-6) - << "waypoint_count=" << count; - EXPECT_LE(metrics.max_acceleration, kAccelerationLimit + 1e-5) - << "waypoint_count=" << count; - EXPECT_LT(metrics.max_waypoint_error, 0.002) - << "waypoint_count=" << count; - if (reference_duration_s == 0.0) { - reference_duration_s = metrics.duration_s; - } else { - EXPECT_NEAR(metrics.duration_s, reference_duration_s, - reference_duration_s * 0.10) - << "waypoint_count=" << count; - } - } -} - -TEST(ToppraMultiWaypointTest, RepeatedWaypointsRemainPlannable) -{ - const auto smooth = makeSmoothWaypoints(300); - std::vector> repeated; - repeated.reserve(smooth.size() * 2); - for (const auto& waypoint : smooth) { - repeated.push_back(waypoint); - repeated.push_back(waypoint); - } - - const auto metrics = planAndMeasure(repeated); - printMetrics(repeated.size(), metrics); - EXPECT_TRUE(metrics.success); - if (metrics.success) { - EXPECT_LE(metrics.max_velocity, kVelocityLimit + 1e-6); - EXPECT_LE(metrics.max_acceleration, kAccelerationLimit + 1e-5); - EXPECT_LT(metrics.max_waypoint_error, 0.002); - } -} - -TEST(ToppraMultiWaypointTest, CompareInterpolationModesAtThreeHundredWaypoints) -{ - const auto waypoints = makeSmoothWaypoints(300); - for (const auto path_type : { - PathType::CubicHermite, - PathType::Quintic, - PathType::Natural}) { - const auto metrics = planAndMeasure(waypoints, path_type); - std::cout << "[ToppraMultiWaypointTest] path_type=" - << pathTypeName(path_type) << std::endl; - printMetrics(waypoints.size(), metrics); - EXPECT_TRUE(metrics.success) << pathTypeName(path_type); - if (metrics.success) { - EXPECT_LE(metrics.max_velocity, kVelocityLimit + 1e-6) - << pathTypeName(path_type); - EXPECT_LE(metrics.max_acceleration, kAccelerationLimit + 1e-5) - << pathTypeName(path_type); - EXPECT_LT(metrics.max_waypoint_error, 0.002) - << pathTypeName(path_type); - EXPECT_LT(metrics.start_error, 1e-9) << pathTypeName(path_type); - EXPECT_LT(metrics.end_error, 1e-9) << pathTypeName(path_type); - } - } -} - -} // namespace -} // namespace cmvr diff --git a/cmvr-es/algorithms/motion_planner/base_motion/motion_profile/s_curve/include/s_curve_position_planner.h b/cmvr-es/algorithms/motion_planner/base_motion/motion_profile/s_curve/include/s_curve_position_planner.h deleted file mode 100644 index 551abaa0..00000000 --- a/cmvr-es/algorithms/motion_planner/base_motion/motion_profile/s_curve/include/s_curve_position_planner.h +++ /dev/null @@ -1,100 +0,0 @@ -// -// Created by lgv on 2026/3/10. -// - -#pragma once - -#include "s_curve_velocity_planner.h" - -#include -#include - -namespace cmvr -{ - -struct SCurvePositionPlannerState -{ - double position; - double velocity; - double acceleration; - double jerk; - double target_position; - bool is_moving; - - SCurvePositionPlannerState() - : position(0.0) - , velocity(0.0) - , acceleration(0.0) - , jerk(0.0) - , target_position(0.0) - , is_moving(false) - {} -}; - -/** - * @brief 单轴位置跟踪规划器 - * - * 结构: - * - 外环:position_error -> desired_velocity - * - 内环:SCurveVelocityPlanner1D 负责 jerk-limited 速度规划 - * - * 这个类用于高频变化目标的位置跟踪,不承担严格点到点 profile 语义。 - */ -class SCurvePositionPlanner1D -{ -public: - SCurvePositionPlanner1D(double max_velocity = 3.0, - double max_acceleration = 10.0, - double max_jerk = 50.0); - - void setConstraints(double max_velocity, double max_acceleration, double max_jerk); - void getConstraints(double& max_velocity, double& max_acceleration, double& max_jerk) const; - - void setPositionGain(double position_gain); - double getPositionGain() const { return position_gain_; } - - void initialize(double position, double velocity = 0.0, double acceleration = 0.0); - void reset(); - - void setTarget(double target_position); - double update(double dt); - - const SCurvePositionPlannerState& getState() const { return state_; } - double getPosition() const { return state_.position; } - double getVelocity() const { return state_.velocity; } - double getAcceleration() const { return state_.acceleration; } - double getJerk() const { return state_.jerk; } - double getTargetPosition() const { return state_.target_position; } - bool isMoving() const { return state_.is_moving; } - -private: - double max_velocity_; - double max_acceleration_; - double max_jerk_; - - SCurvePositionPlannerState state_; - SCurveVelocityPlanner1D velocity_planner_; - double position_gain_; - - static constexpr double EPSILON = 1e-9; - static constexpr double VELOCITY_THRESHOLD = 1e-6; - static constexpr double ACCELERATION_THRESHOLD = 1e-6; - static constexpr double POSITION_THRESHOLD = 1e-7; - - double computeDesiredVelocity(double position_error) const; - double computePlannerStoppingDistance(double velocity, double acceleration) const; - - static double clamp(double value, double min_val, double max_val) - { - return std::max(min_val, std::min(max_val, value)); - } - - static double sign(double value) - { - if (value > EPSILON) return 1.0; - if (value < -EPSILON) return -1.0; - return 0.0; - } -}; - -} // namespace cmvr diff --git a/cmvr-es/algorithms/motion_planner/base_motion/motion_profile/s_curve/include/s_curve_velocity_planner.h b/cmvr-es/algorithms/motion_planner/base_motion/motion_profile/s_curve/include/s_curve_velocity_planner.h deleted file mode 100644 index f9e59774..00000000 --- a/cmvr-es/algorithms/motion_planner/base_motion/motion_profile/s_curve/include/s_curve_velocity_planner.h +++ /dev/null @@ -1,240 +0,0 @@ -// -// Created by lgv on 2026/3/9. -// - -#pragma once - -#include -#include -#include - -namespace cmvr -{ - -/** - * @brief 单次速度切换的 S 曲线剖面参数 - * - * 本类表示从任意 (v0, a0) 连续规划到 (vf, 0) 的 3 段 jerk-limited profile: - * - * seg1: jerk = j1, duration = t1 - * seg2: jerk = j2, duration = t2 (当前实现 j2 = 0) - * seg3: jerk = j3, duration = t3 - * - * 其中 j1/j3 为 ±j_max,j2 为 0。 - */ -struct SCurveVelocityProfile -{ - double t1; - double t2; - double t3; - - double total_time; - - double j1; - double j2; - double j3; - - double v0; - double a0; - double vf; - - bool valid; - - SCurveVelocityProfile() - : t1(0.0), t2(0.0), t3(0.0) - , total_time(0.0) - , j1(0.0), j2(0.0), j3(0.0) - , v0(0.0), a0(0.0), vf(0.0) - , valid(false) - {} -}; - -/** - * @brief S 曲线速度规划器状态 - */ -struct SCurveVelocityPlannerState -{ - double velocity; - double acceleration; - double jerk; - - double target_velocity; - - double elapsed_time; - bool has_active_profile; - bool is_moving; - - SCurveVelocityPlannerState() - : velocity(0.0) - , acceleration(0.0) - , jerk(0.0) - , target_velocity(0.0) - , elapsed_time(0.0) - , has_active_profile(false) - , is_moving(false) - {} -}; - -/** - * @brief 单轴速度型 S 曲线规划器 - * - * 语义: - * - setTargetVelocity(v): 设置新目标并重规划 - * - update(dt): 只采样当前 active profile - * - overwriteState(v,a): 仅覆盖当前状态并清掉旧 profile - * - synchronizeAndReplan(v,a): 用测量状态同步,并按当前目标重规划 - * - * 数学目标: - * - 从任意 (v0, a0) 连续规划到 (vf, 0) - * - 满足 |v| <= v_max, |a| <= a_max, |j| <= j_max - */ -class SCurveVelocityPlanner1D -{ -public: - SCurveVelocityPlanner1D(double max_velocity = 1.0, - double max_acceleration = 1.0, - double max_jerk = 5.0); - - void setConstraints(double max_velocity, double max_acceleration, double max_jerk); - void getConstraints(double& max_velocity, double& max_acceleration, double& max_jerk) const; - - /** - * @brief 设置目标变化阈值 - * - * 目标变化量小于该阈值时,不触发重规划。 - */ - void setTargetReplanThreshold(double threshold); - - /** - * @brief 设置同步反馈时的重规划阈值 - * - * 测量速度与当前 profile 采样状态的偏差小于该阈值时, - * synchronizeAndReplan() 只对齐当前状态,不打断现有 profile。 - */ - void setSynchronizeReplanThreshold(double threshold); - - void initialize(double velocity = 0.0, double acceleration = 0.0); - void reset(); - - /** - * @brief 仅覆盖当前状态,并清掉旧 profile - * - * 注意: - * - 这个接口不会自动重规划 - * - 用于初始化、调试、或显式中断旧轨迹 - */ - void overwriteState(double velocity, - double acceleration = 0.0, - bool keep_target_velocity = true); - - /** - * @brief 用测量状态同步,并按当前目标重新规划 - * - * 这是闭环场景真正该用的接口。 - */ - void synchronizeAndReplan(double velocity, - double acceleration = 0.0); - - /** - * @brief 设置目标速度,并立即重规划 - */ - void setTargetVelocity(double target_velocity); - - /** - * @brief 平滑停下 - */ - void stop() { setTargetVelocity(0.0); } - - /** - * @brief 更新一步(只采样) - * @param dt 时间步长 - * @return 当前采样后的速度 - */ - double update(double dt); - - /** - * @brief 计算单次速度切换剖面 - */ - SCurveVelocityProfile calculateProfile(double start_velocity, - double end_velocity, - double start_acceleration = 0.0) const; - - /** - * @brief 给定剖面下,获取时刻 t 的速度 - */ - double getVelocityAtTime(const SCurveVelocityProfile& profile, double t) const; - - /** - * @brief 给定剖面下,获取时刻 t 的加速度 - */ - double getAccelerationAtTime(const SCurveVelocityProfile& profile, double t) const; - - /** - * @brief 给定剖面下,获取时刻 t 的 jerk - */ - double getJerkAtTime(const SCurveVelocityProfile& profile, double t) const; - - /** - * @brief 按固定时间间隔生成轨迹点 - */ - void generateTrajectory(const SCurveVelocityProfile& profile, double dt, - std::vector& velocities, - std::vector& accelerations, - std::vector& jerks) const; - - const SCurveVelocityPlannerState& getState() const { return state_; } - const SCurveVelocityProfile& getActiveProfile() const { return active_profile_; } - - double getVelocity() const { return state_.velocity; } - double getAcceleration() const { return state_.acceleration; } - double getJerk() const { return state_.jerk; } - double getTargetVelocity() const { return state_.target_velocity; } - bool hasActiveProfile() const { return state_.has_active_profile; } - bool isMoving() const { return state_.is_moving; } - -private: - double max_velocity_; - double max_acceleration_; - double max_jerk_; - - double target_replan_threshold_; - double synchronize_replan_threshold_; - - SCurveVelocityPlannerState state_; - SCurveVelocityProfile active_profile_; - - static constexpr double EPSILON = 1e-9; - static constexpr double VELOCITY_THRESHOLD = 1e-6; - static constexpr double ACCELERATION_THRESHOLD = 1e-6; - static constexpr double DEFAULT_TARGET_REPLAN_THRESHOLD = 1e-9; - static constexpr double DEFAULT_SYNCHRONIZE_REPLAN_THRESHOLD = 5e-2; - -private: - void updateIsMovingFlag(); - - /** - * @brief 判断 profile 是否满足速度上限 - */ - bool isVelocityLimitSatisfied(const SCurveVelocityProfile& profile) const; - - /** - * @brief 计算完整剖面终点状态 - */ - void integrateWholeProfile(const SCurveVelocityProfile& profile, - double& v_end, - double& a_end) const; - - static double clamp(double value, double min_val, double max_val) - { - return std::max(min_val, std::min(max_val, value)); - } - - static double sign(double value) - { - if (value > EPSILON) return 1.0; - if (value < -EPSILON) return -1.0; - return 0.0; - } -}; - -} // namespace cmvr diff --git a/cmvr-es/algorithms/motion_planner/base_motion/motion_profile/s_curve/src/s_curve_position_planner.cpp b/cmvr-es/algorithms/motion_planner/base_motion/motion_profile/s_curve/src/s_curve_position_planner.cpp deleted file mode 100644 index b379f059..00000000 --- a/cmvr-es/algorithms/motion_planner/base_motion/motion_profile/s_curve/src/s_curve_position_planner.cpp +++ /dev/null @@ -1,191 +0,0 @@ -// -// Created by lgv on 2026/3/10. -// - -#include "../include/s_curve_position_planner.h" - -#include -#include - -namespace cmvr -{ - -SCurvePositionPlanner1D::SCurvePositionPlanner1D(double max_velocity, - double max_acceleration, - double max_jerk) - : max_velocity_(std::abs(max_velocity)) - , max_acceleration_(std::abs(max_acceleration)) - , max_jerk_(std::abs(max_jerk)) - , velocity_planner_(max_velocity_, max_acceleration_, max_jerk_) - , position_gain_(1.0) -{ - velocity_planner_.setTargetReplanThreshold(std::max(1e-3, 0.02 * max_velocity_)); - reset(); -} - -void SCurvePositionPlanner1D::setConstraints(double max_velocity, - double max_acceleration, - double max_jerk) -{ - max_velocity_ = std::abs(max_velocity); - max_acceleration_ = std::abs(max_acceleration); - max_jerk_ = std::abs(max_jerk); - velocity_planner_.setConstraints(max_velocity_, max_acceleration_, max_jerk_); - velocity_planner_.setTargetReplanThreshold(std::max(1e-3, 0.02 * max_velocity_)); -} - -void SCurvePositionPlanner1D::getConstraints(double& max_velocity, - double& max_acceleration, - double& max_jerk) const -{ - max_velocity = max_velocity_; - max_acceleration = max_acceleration_; - max_jerk = max_jerk_; -} - -void SCurvePositionPlanner1D::setPositionGain(double position_gain) -{ - position_gain_ = std::max(0.0, position_gain); -} - -void SCurvePositionPlanner1D::initialize(double position, double velocity, double acceleration) -{ - state_.position = position; - velocity_planner_.initialize(velocity, acceleration); - state_.velocity = velocity_planner_.getVelocity(); - state_.acceleration = velocity_planner_.getAcceleration(); - state_.jerk = 0.0; - state_.target_position = position; - state_.is_moving = false; -} - -void SCurvePositionPlanner1D::reset() -{ - state_ = SCurvePositionPlannerState(); - velocity_planner_.reset(); -} - -void SCurvePositionPlanner1D::setTarget(double target_position) -{ - state_.target_position = target_position; -} - -double SCurvePositionPlanner1D::update(double dt) -{ - if (dt <= 0.0 || dt > 0.1) { - return state_.position; - } - - const double position_error = state_.target_position - state_.position; - if (std::abs(position_error) < POSITION_THRESHOLD && - std::abs(velocity_planner_.getVelocity()) < VELOCITY_THRESHOLD && - std::abs(velocity_planner_.getAcceleration()) < ACCELERATION_THRESHOLD) { - velocity_planner_.overwriteState(0.0, 0.0, false); - state_.position = state_.target_position; - state_.velocity = 0.0; - state_.acceleration = 0.0; - state_.jerk = 0.0; - state_.is_moving = false; - return state_.position; - } - - velocity_planner_.setTargetVelocity(computeDesiredVelocity(position_error)); - - const double old_velocity = velocity_planner_.getVelocity(); - const double new_velocity = velocity_planner_.update(dt); - - state_.velocity = new_velocity; - state_.acceleration = velocity_planner_.getAcceleration(); - state_.jerk = velocity_planner_.getJerk(); - state_.position += 0.5 * (old_velocity + new_velocity) * dt; - - const double updated_error = state_.target_position - state_.position; - if (std::abs(updated_error) < POSITION_THRESHOLD && - std::abs(state_.velocity) < VELOCITY_THRESHOLD && - std::abs(state_.acceleration) < ACCELERATION_THRESHOLD) { - velocity_planner_.overwriteState(0.0, 0.0, false); - state_.position = state_.target_position; - state_.velocity = 0.0; - state_.acceleration = 0.0; - state_.jerk = 0.0; - state_.is_moving = false; - return state_.position; - } - - state_.is_moving = velocity_planner_.isMoving() || - std::abs(updated_error) > POSITION_THRESHOLD; - return state_.position; -} - -double SCurvePositionPlanner1D::computeDesiredVelocity(double position_error) const -{ - if (std::abs(position_error) <= POSITION_THRESHOLD) { - return 0.0; - } - - const double proportional_velocity = - clamp(position_gain_ * position_error, -max_velocity_, max_velocity_); - const double current_velocity = velocity_planner_.getVelocity(); - const double current_acceleration = velocity_planner_.getAcceleration(); - const double stopping_distance = - computePlannerStoppingDistance(current_velocity, current_acceleration); - - if (std::abs(current_velocity) > VELOCITY_THRESHOLD && - sign(current_velocity) != sign(position_error)) { - return 0.0; - } - - if (std::abs(current_velocity) > VELOCITY_THRESHOLD && - sign(current_velocity) == sign(position_error) && - std::abs(position_error) <= std::abs(stopping_distance) * 1.05) { - return 0.0; - } - - double low = 0.0; - double high = max_velocity_; - for (int i = 0; i < 40; ++i) { - const double mid = 0.5 * (low + high); - const double distance = - std::abs(computePlannerStoppingDistance(sign(position_error) * mid, 0.0)); - if (distance <= std::abs(position_error)) { - low = mid; - } else { - high = mid; - } - } - - return sign(position_error) * - std::min(std::abs(proportional_velocity), low); -} - -double SCurvePositionPlanner1D::computePlannerStoppingDistance(double velocity, - double acceleration) const -{ - if (std::abs(velocity) <= VELOCITY_THRESHOLD && - std::abs(acceleration) <= ACCELERATION_THRESHOLD) { - return 0.0; - } - - const auto profile = velocity_planner_.calculateProfile(velocity, 0.0, acceleration); - if (!profile.valid || profile.total_time <= EPSILON) { - return 0.0; - } - - const int steps = std::max(16, static_cast(std::ceil(profile.total_time / 0.002))); - const double dt = profile.total_time / static_cast(steps); - - double distance = 0.0; - double previous_time = 0.0; - double previous_velocity = velocity_planner_.getVelocityAtTime(profile, 0.0); - for (int i = 1; i <= steps; ++i) { - const double t = (i == steps) ? profile.total_time : i * dt; - const double current_velocity = velocity_planner_.getVelocityAtTime(profile, t); - distance += 0.5 * (previous_velocity + current_velocity) * (t - previous_time); - previous_time = t; - previous_velocity = current_velocity; - } - - return distance; -} - -} // namespace cmvr diff --git a/cmvr-es/algorithms/motion_planner/base_motion/motion_profile/s_curve/src/s_curve_velocity_planner.cpp b/cmvr-es/algorithms/motion_planner/base_motion/motion_profile/s_curve/src/s_curve_velocity_planner.cpp deleted file mode 100644 index c058e673..00000000 --- a/cmvr-es/algorithms/motion_planner/base_motion/motion_profile/s_curve/src/s_curve_velocity_planner.cpp +++ /dev/null @@ -1,578 +0,0 @@ -// -// Created by lgv on 2026/3/9. -// - -#include "../include/s_curve_velocity_planner.h" - -#include -#include - -namespace cmvr -{ - -SCurveVelocityPlanner1D::SCurveVelocityPlanner1D(double max_velocity, - double max_acceleration, - double max_jerk) - : max_velocity_(std::abs(max_velocity)) - , max_acceleration_(std::abs(max_acceleration)) - , max_jerk_(std::abs(max_jerk)) - , target_replan_threshold_(DEFAULT_TARGET_REPLAN_THRESHOLD) - , synchronize_replan_threshold_(DEFAULT_SYNCHRONIZE_REPLAN_THRESHOLD) -{ - reset(); -} - -void SCurveVelocityPlanner1D::setConstraints(double max_velocity, - double max_acceleration, - double max_jerk) -{ - max_velocity_ = std::abs(max_velocity); - max_acceleration_ = std::abs(max_acceleration); - max_jerk_ = std::abs(max_jerk); - - state_.velocity = clamp(state_.velocity, -max_velocity_, max_velocity_); - state_.acceleration = clamp(state_.acceleration, -max_acceleration_, max_acceleration_); - state_.target_velocity = clamp(state_.target_velocity, -max_velocity_, max_velocity_); - - if (state_.has_active_profile) { - active_profile_ = calculateProfile(state_.velocity, - state_.target_velocity, - state_.acceleration); - state_.elapsed_time = 0.0; - state_.has_active_profile = active_profile_.valid && active_profile_.total_time > EPSILON; - } - - updateIsMovingFlag(); -} - -void SCurveVelocityPlanner1D::getConstraints(double& max_velocity, - double& max_acceleration, - double& max_jerk) const -{ - max_velocity = max_velocity_; - max_acceleration = max_acceleration_; - max_jerk = max_jerk_; -} - -void SCurveVelocityPlanner1D::setTargetReplanThreshold(double threshold) -{ - target_replan_threshold_ = std::max(0.0, threshold); -} - -void SCurveVelocityPlanner1D::setSynchronizeReplanThreshold(double threshold) -{ - synchronize_replan_threshold_ = std::max(0.0, threshold); -} - -void SCurveVelocityPlanner1D::initialize(double velocity, double acceleration) -{ - state_ = SCurveVelocityPlannerState(); - state_.velocity = clamp(velocity, -max_velocity_, max_velocity_); - state_.acceleration = clamp(acceleration, -max_acceleration_, max_acceleration_); - state_.jerk = 0.0; - state_.target_velocity = state_.velocity; - state_.elapsed_time = 0.0; - state_.has_active_profile = false; - - active_profile_ = SCurveVelocityProfile(); - active_profile_.v0 = state_.velocity; - active_profile_.a0 = state_.acceleration; - active_profile_.vf = state_.velocity; - active_profile_.valid = false; - - updateIsMovingFlag(); -} - -void SCurveVelocityPlanner1D::reset() -{ - state_ = SCurveVelocityPlannerState(); - active_profile_ = SCurveVelocityProfile(); -} - -void SCurveVelocityPlanner1D::overwriteState(double velocity, - double acceleration, - bool keep_target_velocity) -{ - state_.velocity = clamp(velocity, -max_velocity_, max_velocity_); - state_.acceleration = clamp(acceleration, -max_acceleration_, max_acceleration_); - state_.jerk = 0.0; - state_.elapsed_time = 0.0; - state_.has_active_profile = false; - - if (!keep_target_velocity) { - state_.target_velocity = state_.velocity; - } else { - state_.target_velocity = clamp(state_.target_velocity, -max_velocity_, max_velocity_); - } - - active_profile_ = SCurveVelocityProfile(); - active_profile_.v0 = state_.velocity; - active_profile_.a0 = state_.acceleration; - active_profile_.vf = state_.target_velocity; - active_profile_.valid = false; - - updateIsMovingFlag(); -} - -void SCurveVelocityPlanner1D::synchronizeAndReplan(double velocity, - double acceleration) -{ - const double measured_velocity = clamp(velocity, -max_velocity_, max_velocity_); - double measured_acceleration = - clamp(acceleration, -max_acceleration_, max_acceleration_); - - // When the target is zero this planner is also used for Cartesian speed - // magnitudes. A magnitude is non-negative, while the finite-difference - // derivative of the measured magnitude is signed. Feeding a large negative - // measured acceleration into a signed 1-D velocity planner can generate a - // profile that crosses through zero and becomes negative before returning to - // zero. The twist limiter then multiplies that negative "norm" by the - // current direction, which reverses and amplifies the Cartesian command. - // - // For feedback resynchronization during a stop, synchronize the measured - // speed only and restart the stop profile with zero scalar acceleration. - // This avoids noise-sensitive stop replans and preserves a non-overshooting - // deceleration profile for speed-magnitude users. - if (std::abs(state_.target_velocity) <= VELOCITY_THRESHOLD) { - measured_acceleration = 0.0; - } - - if (!state_.has_active_profile && - std::abs(measured_velocity - state_.target_velocity) <= VELOCITY_THRESHOLD) { - state_.velocity = state_.target_velocity; - state_.acceleration = 0.0; - state_.jerk = 0.0; - updateIsMovingFlag(); - return; - } - - // 如果测量值已经基本落在当前采样状态上,就继续沿现有 profile 走。 - // 否则每拍都从同一目标重规划,会把已经进入的 jerk phase 反复打断。 - if (state_.has_active_profile && - std::abs(measured_velocity - state_.velocity) <= synchronize_replan_threshold_) { - state_.velocity = measured_velocity; - state_.acceleration = measured_acceleration; - state_.jerk = getJerkAtTime(active_profile_, state_.elapsed_time); - updateIsMovingFlag(); - return; - } - - state_.velocity = measured_velocity; - state_.acceleration = measured_acceleration; - state_.jerk = 0.0; - - active_profile_ = calculateProfile(state_.velocity, - state_.target_velocity, - state_.acceleration); - - state_.elapsed_time = 0.0; - state_.has_active_profile = active_profile_.total_time > EPSILON; - - updateIsMovingFlag(); -} - -void SCurveVelocityPlanner1D::setTargetVelocity(double target_velocity) -{ - const double new_target = clamp(target_velocity, -max_velocity_, max_velocity_); - - const bool same_target = - std::abs(new_target - state_.target_velocity) <= target_replan_threshold_; - - if (same_target && - state_.has_active_profile) { - return; - } - - if (same_target && - !state_.has_active_profile && - std::abs(state_.velocity - new_target) <= VELOCITY_THRESHOLD && - std::abs(state_.acceleration) <= ACCELERATION_THRESHOLD) { - return; - } - - state_.target_velocity = new_target; - - active_profile_ = calculateProfile(state_.velocity, - state_.target_velocity, - state_.acceleration); - - state_.elapsed_time = 0.0; - state_.has_active_profile = active_profile_.valid && active_profile_.total_time > EPSILON; - - updateIsMovingFlag(); -} - -double SCurveVelocityPlanner1D::getVelocityAtTime(const SCurveVelocityProfile& profile, double t) const -{ - if (!profile.valid) { - return profile.v0; - } - - if (t <= 0.0) { - return profile.v0; - } - if (t >= profile.total_time) { - return profile.vf; - } - - double v = profile.v0; - double a = profile.a0; - - auto process_segment = [&](double dt, double jerk) { - v += a * dt + 0.5 * jerk * dt * dt; - a += jerk * dt; - }; - - // seg1 - if (t <= profile.t1) { - process_segment(t, profile.j1); - return v; - } - process_segment(profile.t1, profile.j1); - - // seg2 - const double t_after_1 = t - profile.t1; - if (t_after_1 <= profile.t2) { - process_segment(t_after_1, profile.j2); - return v; - } - process_segment(profile.t2, profile.j2); - - // seg3 - const double t_after_2 = t_after_1 - profile.t2; - process_segment(t_after_2, profile.j3); - return v; -} - -double SCurveVelocityPlanner1D::getAccelerationAtTime(const SCurveVelocityProfile& profile, double t) const -{ - if (!profile.valid) { - return profile.a0; - } - - if (t <= 0.0) { - return profile.a0; - } - if (t >= profile.total_time) { - return 0.0; - } - - double a = profile.a0; - - auto process_segment = [&](double dt, double jerk) { - a += jerk * dt; - }; - - // seg1 - if (t <= profile.t1) { - process_segment(t, profile.j1); - return a; - } - process_segment(profile.t1, profile.j1); - - // seg2 - const double t_after_1 = t - profile.t1; - if (t_after_1 <= profile.t2) { - process_segment(t_after_1, profile.j2); - return a; - } - process_segment(profile.t2, profile.j2); - - // seg3 - const double t_after_2 = t_after_1 - profile.t2; - process_segment(t_after_2, profile.j3); - return a; -} - -double SCurveVelocityPlanner1D::getJerkAtTime(const SCurveVelocityProfile& profile, double t) const -{ - if (!profile.valid) { - return 0.0; - } - - if (t <= 0.0 || t >= profile.total_time) { - return 0.0; - } - - if (t <= profile.t1) { - return profile.j1; - } - if (t <= profile.t1 + profile.t2) { - return profile.j2; - } - return profile.j3; -} - -void SCurveVelocityPlanner1D::integrateWholeProfile(const SCurveVelocityProfile& profile, - double& v_end, - double& a_end) const -{ - double v = profile.v0; - double a = profile.a0; - - auto process_segment = [&](double dt, double jerk) { - v += a * dt + 0.5 * jerk * dt * dt; - a += jerk * dt; - }; - - process_segment(profile.t1, profile.j1); - process_segment(profile.t2, profile.j2); - process_segment(profile.t3, profile.j3); - - v_end = v; - a_end = a; -} - -bool SCurveVelocityPlanner1D::isVelocityLimitSatisfied(const SCurveVelocityProfile& profile) const -{ - if (!profile.valid) { - return true; - } - - std::vector check_times; - check_times.reserve(8); - - check_times.push_back(0.0); - check_times.push_back(profile.t1); - check_times.push_back(profile.t1 + profile.t2); - check_times.push_back(profile.total_time); - - // seg1 内部若 acceleration 过零,则 velocity 可能在段内出现极值 - if (std::abs(profile.j1) > EPSILON && profile.t1 > EPSILON) { - const double tz = -profile.a0 / profile.j1; - if (tz > EPSILON && tz < profile.t1 - EPSILON) { - check_times.push_back(tz); - } - } - - for (double t : check_times) { - const double v = getVelocityAtTime(profile, t); - if (std::abs(v) > max_velocity_ + 1e-7) { - return false; - } - } - - return true; -} - -SCurveVelocityProfile SCurveVelocityPlanner1D::calculateProfile(double start_velocity, - double end_velocity, - double start_acceleration) const -{ - SCurveVelocityProfile best; - best.v0 = clamp(start_velocity, -max_velocity_, max_velocity_); - best.a0 = clamp(start_acceleration, -max_acceleration_, max_acceleration_); - best.vf = clamp(end_velocity, -max_velocity_, max_velocity_); - - if (max_jerk_ <= EPSILON || max_acceleration_ <= EPSILON) { - // 退化情况:这里不做特殊退化规划,直接返回 invalid - return best; - } - - const double v0 = best.v0; - const double a0 = best.a0; - const double vf = best.vf; - - // 目标方向坐标:尽量统一到“signed frame 下 Δv >= 0” - double s = sign(vf - v0); - if (std::abs(vf - v0) <= VELOCITY_THRESHOLD) { - s = 1.0; - } - - const double dv = s * (vf - v0); // >= 0 - const double a0s = s * a0; // signed frame 下的初始 acceleration - const double j = max_jerk_; - const double amax = max_acceleration_; - - auto normalize_nonnegative = [](double x) { - return (x < 0.0 && x > -1e-10) ? 0.0 : x; - }; - - auto try_candidate = [&](double t1, double t2, double t3, - double j1s, double j2s, double j3s) { - t1 = normalize_nonnegative(t1); - t2 = normalize_nonnegative(t2); - t3 = normalize_nonnegative(t3); - - if (t1 < 0.0 || t2 < 0.0 || t3 < 0.0) { - return; - } - - SCurveVelocityProfile cand; - cand.t1 = t1; - cand.t2 = t2; - cand.t3 = t3; - cand.total_time = t1 + t2 + t3; - - cand.j1 = s * j1s; - cand.j2 = s * j2s; - cand.j3 = s * j3s; - - cand.v0 = v0; - cand.a0 = a0; - cand.vf = vf; - cand.valid = true; - - double vend = 0.0; - double aend = 0.0; - integrateWholeProfile(cand, vend, aend); - - if (std::abs(vend - vf) > 1e-5) { - return; - } - if (std::abs(aend) > 1e-5) { - return; - } - if (!isVelocityLimitSatisfied(cand)) { - return; - } - - if (!best.valid || cand.total_time < best.total_time) { - best = cand; - } - }; - - // ---------------- UDU 三角形(无平台) ---------------- - { - // Δv = (2A^2 - a0^2)/(2j) - const double A2 = 0.5 * (2.0 * j * dv + a0s * a0s); - if (A2 >= -1e-10) { - const double A = std::sqrt(std::max(0.0, A2)); - if (A <= amax + 1e-10 && A >= a0s - 1e-10) { - const double t1 = (A - a0s) / j; - const double t2 = 0.0; - const double t3 = A / j; - try_candidate(t1, t2, t3, +j, 0.0, -j); - } - } - } - - // ---------------- UDU 梯形(有平台) ---------------- - { - const double A = amax; - if (A > EPSILON && A >= a0s - 1e-10) { - const double base = (2.0 * A * A - a0s * a0s) / (2.0 * j); - const double t1 = (A - a0s) / j; - const double t2 = (dv - base) / A; - const double t3 = A / j; - try_candidate(t1, t2, t3, +j, 0.0, -j); - } - } - - // ---------------- DUD 三角形(无平台) ---------------- - { - // Δv = (a0^2 - 2B^2)/(2j) - const double B2 = 0.5 * (a0s * a0s - 2.0 * j * dv); - if (B2 >= -1e-10) { - const double B = std::sqrt(std::max(0.0, B2)); - if (B <= amax + 1e-10 && B >= -a0s - 1e-10) { - const double t1 = (a0s + B) / j; - const double t2 = 0.0; - const double t3 = B / j; - try_candidate(t1, t2, t3, -j, 0.0, +j); - } - } - } - - // ---------------- DUD 梯形(有平台) ---------------- - { - const double B = amax; - if (B > EPSILON && B >= -a0s - 1e-10) { - const double base = (a0s * a0s - 2.0 * B * B) / (2.0 * j); - const double t1 = (a0s + B) / j; - const double t2 = (base - dv) / B; - const double t3 = B / j; - try_candidate(t1, t2, t3, -j, 0.0, +j); - } - } - - // 已到终点附近 - if (!best.valid && - std::abs(vf - v0) <= VELOCITY_THRESHOLD && - std::abs(a0) <= ACCELERATION_THRESHOLD) { - best.valid = false; - best.total_time = 0.0; - best.v0 = v0; - best.a0 = a0; - best.vf = vf; - } - - return best; -} - -void SCurveVelocityPlanner1D::generateTrajectory(const SCurveVelocityProfile& profile, double dt, - std::vector& velocities, - std::vector& accelerations, - std::vector& jerks) const -{ - velocities.clear(); - accelerations.clear(); - jerks.clear(); - - if (!profile.valid || profile.total_time <= 0.0 || dt <= 0.0) { - velocities.push_back(profile.v0); - accelerations.push_back(profile.a0); - jerks.push_back(0.0); - return; - } - - const int num_points = static_cast(std::ceil(profile.total_time / dt)) + 1; - velocities.reserve(num_points); - accelerations.reserve(num_points); - jerks.reserve(num_points); - - for (double t = 0.0; t <= profile.total_time; t += dt) { - velocities.push_back(getVelocityAtTime(profile, t)); - accelerations.push_back(getAccelerationAtTime(profile, t)); - jerks.push_back(getJerkAtTime(profile, t)); - } - - if (velocities.empty() || std::abs(velocities.back() - profile.vf) > VELOCITY_THRESHOLD) { - velocities.push_back(profile.vf); - accelerations.push_back(0.0); - jerks.push_back(0.0); - } -} - -double SCurveVelocityPlanner1D::update(double dt) -{ - if (dt <= 0.0) { - return state_.velocity; - } - - if (!state_.has_active_profile || !active_profile_.valid) { - state_.jerk = 0.0; - updateIsMovingFlag(); - return state_.velocity; - } - - state_.elapsed_time += dt; - - if (state_.elapsed_time >= active_profile_.total_time) { - state_.elapsed_time = active_profile_.total_time; - state_.velocity = active_profile_.vf; - state_.acceleration = 0.0; - state_.jerk = 0.0; - state_.has_active_profile = false; - updateIsMovingFlag(); - return state_.velocity; - } - - state_.velocity = getVelocityAtTime(active_profile_, state_.elapsed_time); - state_.acceleration = getAccelerationAtTime(active_profile_, state_.elapsed_time); - state_.jerk = getJerkAtTime(active_profile_, state_.elapsed_time); - - updateIsMovingFlag(); - return state_.velocity; -} - -void SCurveVelocityPlanner1D::updateIsMovingFlag() -{ - state_.is_moving = - state_.has_active_profile || - std::abs(state_.velocity) > VELOCITY_THRESHOLD || - std::abs(state_.target_velocity) > VELOCITY_THRESHOLD || - std::abs(state_.acceleration) > ACCELERATION_THRESHOLD; -} - -} // namespace cmvr diff --git a/cmvr-es/algorithms/motion_planner/base_motion/motion_profile/s_curve/test/s_curve_velocity_planner_stop_test.cpp b/cmvr-es/algorithms/motion_planner/base_motion/motion_profile/s_curve/test/s_curve_velocity_planner_stop_test.cpp deleted file mode 100644 index 12ba5e38..00000000 --- a/cmvr-es/algorithms/motion_planner/base_motion/motion_profile/s_curve/test/s_curve_velocity_planner_stop_test.cpp +++ /dev/null @@ -1,77 +0,0 @@ -#include - -#include - -#include "algorithms/motion_planner/base_motion/motion_profile/s_curve/include/s_curve_velocity_planner.h" - -namespace cmvr { -namespace { - -void finishActiveProfile(SCurveVelocityPlanner1D& planner, double dt) -{ - for (int i = 0; i < 10000 && planner.hasActiveProfile(); ++i) { - planner.update(dt); - } - ASSERT_FALSE(planner.hasActiveProfile()); -} - -TEST(SCurveVelocityPlannerStopTest, FeedbackResyncDoesNotReverseSpeedMagnitude) -{ - SCurveVelocityPlanner1D planner(0.55, 3.0, 10.0); - constexpr double kDt = 0.001; - constexpr double kInitialSpeed = 0.04; - - planner.initialize(kInitialSpeed, 0.0); - planner.setTargetVelocity(0.0); - finishActiveProfile(planner, kDt); - - // Reproduce the speedL stop feedback case: the command profile has already - // reached zero, but the measured TCP still has residual speed. A 1 kHz - // finite difference may report a large negative scalar acceleration. - planner.synchronizeAndReplan(kInitialSpeed, -3.0); - - double max_speed = planner.getVelocity(); - double min_speed = planner.getVelocity(); - for (int i = 0; i < 10000 && planner.hasActiveProfile(); ++i) { - const double speed = planner.update(kDt); - max_speed = std::max(max_speed, speed); - min_speed = std::min(min_speed, speed); - } - - EXPECT_GE(min_speed, -1e-9); - EXPECT_LE(max_speed, kInitialSpeed + 1e-9); - EXPECT_NEAR(planner.getVelocity(), 0.0, 1e-9); -} - -TEST(SCurveVelocityPlannerStopTest, LargerMeasuredDecelerationDoesNotIncreaseStopSpeed) -{ - constexpr double kDt = 0.001; - constexpr double kInitialSpeed = 0.04; - const double measured_accelerations[] = {-0.5, -1.0, -2.0, -3.0}; - - for (const double measured_acceleration : measured_accelerations) { - SCurveVelocityPlanner1D planner(0.55, 3.0, 10.0); - planner.initialize(kInitialSpeed, 0.0); - planner.setTargetVelocity(0.0); - finishActiveProfile(planner, kDt); - - planner.synchronizeAndReplan(kInitialSpeed, measured_acceleration); - - double max_speed = planner.getVelocity(); - double min_speed = planner.getVelocity(); - for (int i = 0; i < 10000 && planner.hasActiveProfile(); ++i) { - const double speed = planner.update(kDt); - max_speed = std::max(max_speed, speed); - min_speed = std::min(min_speed, speed); - } - - EXPECT_GE(min_speed, -1e-9) << "measured_acceleration=" << measured_acceleration; - EXPECT_LE(max_speed, kInitialSpeed + 1e-9) - << "measured_acceleration=" << measured_acceleration; - EXPECT_NEAR(planner.getVelocity(), 0.0, 1e-9) - << "measured_acceleration=" << measured_acceleration; - } -} - -} // namespace -} // namespace cmvr diff --git a/cmvr-es/algorithms/planner/CMakeLists.txt b/cmvr-es/algorithms/planner/CMakeLists.txt new file mode 100644 index 00000000..1216b7a4 --- /dev/null +++ b/cmvr-es/algorithms/planner/CMakeLists.txt @@ -0,0 +1,49 @@ +add_library(base_motion SHARED + cartesian/s_curve/src/s_curve_planner.cpp) +target_include_directories(base_motion PUBLIC "${PROJECT_SOURCE_DIR}/cmvr-es") +target_link_libraries(base_motion PUBLIC + cmvr_es::curves OsqpEigen tinyxml2 fcl cmvr_es::common) +add_library(cmvr_es::base_motion ALIAS base_motion) +install(TARGETS base_motion LIBRARY DESTINATION lib) + +add_library(arm_motion SHARED + cartesian/pinocchio/src/pinocchio_cartesian_trajectory_planner.cpp + cartesian/pinocchio/src/pinocchio_cartesian_velocity_planner.cpp) +target_include_directories(arm_motion PUBLIC "${PROJECT_SOURCE_DIR}/cmvr-es") +target_link_libraries(arm_motion PUBLIC + cmvr_es::ik_solver cmvr_es::base_motion cmvr_es::curves) +add_library(cmvr_es::arm_motion ALIAS arm_motion) +add_library(cmvr_es::algorithms::arm_motion ALIAS arm_motion) +install(TARGETS arm_motion LIBRARY DESTINATION lib) + +add_library(joint_path_planner SHARED + joint/ompl/src/rrt_connect.cpp) +target_include_directories(joint_path_planner PUBLIC "${PROJECT_SOURCE_DIR}/cmvr-es") +target_link_libraries(joint_path_planner PUBLIC cmvr_es::proto PRIVATE ompl) +add_library(cmvr_es::joint_path_planner ALIAS joint_path_planner) +install(TARGETS joint_path_planner LIBRARY DESTINATION lib) + +add_executable(s_curve_planner_reversal_test + cartesian/s_curve/test/s_curve_planner_reversal_test.cpp) +target_link_libraries(s_curve_planner_reversal_test PRIVATE + cmvr_es::base_motion gtest gtest_main) + +add_executable(pinocchio_speedl_limits_test + cartesian/pinocchio/test/pinocchio_speedl_limits_test.cpp) +target_compile_definitions(pinocchio_speedl_limits_test PRIVATE + CMVR_TEST_SOURCE_DIR="${PROJECT_SOURCE_DIR}") +target_link_libraries(pinocchio_speedl_limits_test PRIVATE + cmvr_es::algorithms::arm_motion gtest gtest_main) + +add_executable(rrt_connect_test + joint/ompl/test/rrt_connect_test.cpp) +target_link_libraries(rrt_connect_test PRIVATE + cmvr_es::joint_path_planner ompl gtest pthread) + +add_executable(rrt_connect_self_collision_test + joint/ompl/test/rrt_connect_self_collision_test.cpp) +target_compile_definitions(rrt_connect_self_collision_test PRIVATE + CMVR_ES_SOURCE_DIR="${PROJECT_SOURCE_DIR}") +target_link_libraries(rrt_connect_self_collision_test PRIVATE + cmvr_es::joint_path_planner cmvr_es::collision_checker + ompl gtest pthread) diff --git a/cmvr-es/algorithms/planner/cartesian/cartesian_motion_planner_factory.h b/cmvr-es/algorithms/planner/cartesian/cartesian_motion_planner_factory.h new file mode 100644 index 00000000..1cedc0f1 --- /dev/null +++ b/cmvr-es/algorithms/planner/cartesian/cartesian_motion_planner_factory.h @@ -0,0 +1,64 @@ +#ifndef CMVR_ES_CARTESIAN_MOTION_PLANNER_FACTORY_H +#define CMVR_ES_CARTESIAN_MOTION_PLANNER_FACTORY_H + +#include + +#include "algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_ik_base.h" +#include "algorithms/planner/cartesian/pinocchio/include/pinocchio_cartesian_trajectory_planner.h" +#include "algorithms/planner/cartesian/pinocchio/include/pinocchio_cartesian_velocity_planner.h" +#include "algorithms/planner/cartesian/cartesian_trajectory_planner.h" +#include "algorithms/planner/cartesian/cartesian_velocity_planner.h" +#include "cmvr/config/arm_config/arm_config.pb.h" + +namespace cmvr::device { + +class CartesianMotionPlannerFactory { +public: + static std::shared_ptr createMoveL( + const config::MoveLConfig& move_l, + const std::shared_ptr& solver) + { + if (!solver) { + return nullptr; + } + switch (move_l.algorithm_case()) { + case config::MoveLConfig::kPinocchioCartesianMotionPlanner: { + auto planner = std::make_shared(solver); + if (!planner->configureMoveL(move_l.pinocchio_cartesian_motion_planner())) { + return nullptr; + } + return planner; + } + case config::MoveLConfig::ALGORITHM_NOT_SET: + default: + return nullptr; + } + } + + static std::shared_ptr createSpeedL( + const config::SpeedLConfig& speed_l, + const std::shared_ptr& solver, + std::size_t dof) + { + if (!solver) { + return nullptr; + } + switch (speed_l.algorithm_case()) { + case config::SpeedLConfig::kPinocchioCartesianMotionPlanner: { + auto planner = std::make_shared(solver); + if (!planner->configureSpeedL(speed_l.pinocchio_cartesian_motion_planner(), dof)) { + return nullptr; + } + return planner; + } + case config::SpeedLConfig::ALGORITHM_NOT_SET: + default: + return nullptr; + } + } + +}; + +} // namespace cmvr::device + +#endif // CMVR_ES_CARTESIAN_MOTION_PLANNER_FACTORY_H diff --git a/cmvr-es/algorithms/planner/cartesian/cartesian_trajectory_planner.h b/cmvr-es/algorithms/planner/cartesian/cartesian_trajectory_planner.h new file mode 100644 index 00000000..557f741f --- /dev/null +++ b/cmvr-es/algorithms/planner/cartesian/cartesian_trajectory_planner.h @@ -0,0 +1,41 @@ +#ifndef CMVR_ES_CARTESIAN_TRAJECTORY_PLANNER_H +#define CMVR_ES_CARTESIAN_TRAJECTORY_PLANNER_H + +#include +#include + +#include "cmvr/config/arm_config/arm_config.pb.h" +#include "common/types/arm/arm_types.h" + +namespace cmvr::device { + +struct CartesianJointTrajectory { + std::vector> position; + std::vector> velocity; + std::vector time; + double planned_path_length{0.0}; + double executable_path_length{0.0}; + bool truncated{false}; + std::string truncation_reason; +}; + +// Offline trajectory planning, independent of online velocity state. +class CartesianTrajectoryPlanner { +public: + virtual ~CartesianTrajectoryPlanner() = default; + virtual bool configureMoveL(const config::MoveLPlannerConfig& config) = 0; + + virtual bool planMoveL(const CartesianPose& target, + const std::vector& q_start, + const std::vector& qd_max, + double velocity, + double acceleration, + double jerk, + FrameType frame, + CartesianJointTrajectory& trajectory) = 0; + +}; + +} // namespace cmvr::device + +#endif // CMVR_ES_CARTESIAN_TRAJECTORY_PLANNER_H diff --git a/cmvr-es/algorithms/planner/cartesian/cartesian_velocity_planner.h b/cmvr-es/algorithms/planner/cartesian/cartesian_velocity_planner.h new file mode 100644 index 00000000..6ae2a659 --- /dev/null +++ b/cmvr-es/algorithms/planner/cartesian/cartesian_velocity_planner.h @@ -0,0 +1,62 @@ +#ifndef CMVR_ES_CARTESIAN_VELOCITY_PLANNER_H +#define CMVR_ES_CARTESIAN_VELOCITY_PLANNER_H + +#include +#include + +#include "cmvr/config/arm_config/arm_config.pb.h" +#include "common/types/arm/arm_types.h" + +namespace cmvr::device { + +struct CartesianVelocityStep { + Result status{Result::failure(ArmErrorCode::RobotNotReady, "no velocity step")}; + // A valid step may be decelerating to a controlled stop. Keep executing + // successful steps and report this reason only after measured stop. + Result stop_reason{Result::success()}; + JointVelocityCommand joint_velocity; + // Smoothed Cartesian target before joint limits, not measured TCP velocity. + CartesianVelocity twist_base{}; + SpeedLReference reference{}; + // Zero target has finished decelerating, including its acceleration state. + // The executor must still check measured joint velocity before finishing. + bool settled{false}; +}; + +// Online planner. Calls are serialized by the control thread; no device I/O. +class CartesianVelocityPlanner { +public: + virtual ~CartesianVelocityPlanner() = default; + virtual bool configureSpeedL(const config::SpeedLPlannerConfig& config, + std::size_t dof) = 0; + + // Start a new execution from feedback, discarding any interrupted command. + virtual Result reset(const std::vector& q, const std::vector& qd) = 0; + + // A valid submission replaces the target/options without resetting motion. + virtual Result submit(const CartesianVelocity& target, const SpeedLOptions& options, + FrameType frame) = 0; + // Prepare a candidate without advancing the committed planner state. A new + // step, reset or submission discards any uncommitted candidate. + // Failure returns no command. Reference is returned on the first successful + // step of a capture request; publish it only after sending the joint command. + // Apply scaling before S-curve planning; zero pauses without losing the target. + virtual CartesianVelocityStep step(double dt, const std::vector& q, + const std::vector& qd, + double speed_scaling = 1.0) = 0; + // Joint-space braking after a planning failure, without the Cartesian task + // equality. Failure means constrained braking is unavailable. + virtual CartesianVelocityStep brakeStep(double, const std::vector&, + const std::vector&) { + CartesianVelocityStep result; + result.status = Result::failure(ArmErrorCode::UnsupportedCommand, + "joint braking is not supported"); + return result; + } + // Call only after the candidate joint command was successfully submitted. + virtual void commitStep() {} +}; + +} // namespace cmvr::device + +#endif // CMVR_ES_CARTESIAN_VELOCITY_PLANNER_H diff --git a/cmvr-es/algorithms/planner/cartesian/pinocchio/include/pinocchio_cartesian_trajectory_planner.h b/cmvr-es/algorithms/planner/cartesian/pinocchio/include/pinocchio_cartesian_trajectory_planner.h new file mode 100644 index 00000000..282a1161 --- /dev/null +++ b/cmvr-es/algorithms/planner/cartesian/pinocchio/include/pinocchio_cartesian_trajectory_planner.h @@ -0,0 +1,63 @@ +#ifndef CMVR_ES_PINOCCHIO_CARTESIAN_TRAJECTORY_PLANNER_H +#define CMVR_ES_PINOCCHIO_CARTESIAN_TRAJECTORY_PLANNER_H + +#include + +#include +#include +#include + +#include "algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_ik_base.h" +#include "algorithms/planner/cartesian/cartesian_trajectory_planner.h" + +namespace cmvr::device { + +class PinocchioCartesianTrajectoryPlanner final : public CartesianTrajectoryPlanner { +public: + explicit PinocchioCartesianTrajectoryPlanner(std::shared_ptr solver); + + bool configureMoveL(const config::MoveLPlannerConfig& config) override; + + bool planMoveL(const CartesianPose& target, + const std::vector& q_start, + const std::vector& qd_max, + double velocity, + double acceleration, + double jerk, + FrameType frame, + CartesianJointTrajectory& trajectory) override; + +private: + bool checkMoveLPlanLineDeviation_(const Eigen::Vector3d& p_start, + const Eigen::Vector3d& line_direction, + const Eigen::Vector3d& p_current, + double traveled, + bool& deviation_warned, + bool& direction_warned, + std::string& stop_reason) const; + bool checkMoveLPlanJointContinuity_(const Eigen::VectorXd& q_current, + const Eigen::VectorXd& q_next, + const Eigen::VectorXd& qdot, + const Eigen::VectorXd& prev_qdot, + double dt, + double path_position, + std::string& stop_reason) const; + bool checkMoveLPlanJointPositionLimits_(const Eigen::VectorXd& q_current, + const Eigen::VectorXd& q_next, + const Eigen::VectorXd& qdot, + double dt, + double path_position, + std::string& stop_reason) const; + bool checkMoveLPlanCartesianStepFeasibility_( + const Eigen::Matrix& desired_twist, + const Eigen::Matrix& achieved_twist, + double path_position, + std::string& stop_reason) const; + + std::shared_ptr solver_{nullptr}; + config::MoveLPlannerConfig movel_config_{}; +}; + +} // namespace cmvr::device + +#endif // CMVR_ES_PINOCCHIO_CARTESIAN_TRAJECTORY_PLANNER_H diff --git a/cmvr-es/algorithms/planner/cartesian/pinocchio/include/pinocchio_cartesian_velocity_planner.h b/cmvr-es/algorithms/planner/cartesian/pinocchio/include/pinocchio_cartesian_velocity_planner.h new file mode 100644 index 00000000..fb4bafb3 --- /dev/null +++ b/cmvr-es/algorithms/planner/cartesian/pinocchio/include/pinocchio_cartesian_velocity_planner.h @@ -0,0 +1,100 @@ +#ifndef CMVR_ES_PINOCCHIO_CARTESIAN_VELOCITY_PLANNER_H +#define CMVR_ES_PINOCCHIO_CARTESIAN_VELOCITY_PLANNER_H + +#include + +#include +#include +#include +#include + +#include "algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_ik_base.h" +#include "algorithms/planner/cartesian/cartesian_velocity_planner.h" +#include "algorithms/planner/cartesian/s_curve/include/s_curve_planner.h" + +namespace cmvr::device { + +class PinocchioCartesianVelocityPlanner final : public CartesianVelocityPlanner { +public: + explicit PinocchioCartesianVelocityPlanner(std::shared_ptr solver); + + bool configureSpeedL(const config::SpeedLPlannerConfig& config, + std::size_t dof) override; + + Result reset(const std::vector& q, const std::vector& qd) override; + Result submit(const CartesianVelocity& target, const SpeedLOptions& options, + FrameType frame) override; + CartesianVelocityStep step(double dt, const std::vector& q_measured, + const std::vector& qd_measured, + double speed_scaling = 1.0) override; + CartesianVelocityStep brakeStep(double dt, const std::vector& q, + const std::vector& qd) override; + void commitStep() override; + +private: + CartesianVelocityStep stepImpl_(double dt, const std::vector& q, + const std::vector& qd, double speed_scaling); + double adaptiveScale_(const Eigen::Matrix& target_base, + const Eigen::MatrixXd& jacobian, const std::vector& q, + const std::vector& qd, double dt); + bool updateSpeedLLimits_(const SpeedLOptions& options); + bool refreshJointAccelerationLimits_(); + Eigen::VectorXd jointAccelerationStepLimits_(Eigen::Index dof, double dt) const; + bool updateAndValidateSpeedLLineDeviation_(const Eigen::Vector3d& tcp_position, + bool is_stop_command, + const Eigen::Vector3d& command_linear_base, + const Eigen::Vector3d& target_linear_base); + bool validateSpeedLJointVelocityCommand_(const Eigen::VectorXd& qdot, + const Eigen::VectorXd& reference, + double dt) const; + bool validateSpeedLPredictedJointPositionLimits_(const std::vector& q_measured, + const Eigen::VectorXd& qdot, + double dt) const; + bool validateSpeedLCartesianVelocityFeasibility_( + const Eigen::Matrix& desired_twist, + const Eigen::Matrix& achieved_twist, + const Eigen::VectorXd& q_current, + const Eigen::VectorXd& qdot) const; + std::string describeJointLimitCandidates_(const Eigen::VectorXd& q_current, + const Eigen::VectorXd& qdot) const; + + std::shared_ptr solver_{nullptr}; + config::SpeedLPlannerConfig speedl_config_{}; + struct State { + cmvr::SCurvePlanner s_curve_planner_{}; + Eigen::VectorXd joint_acceleration_limits_; + std::vector prev_qdot_command_; + Eigen::Matrix speedl_command_twist_base_{Eigen::Matrix::Zero()}; + CartesianVelocity speedl_target_{}; + FrameType speedl_frame_{FrameType::Base}; + bool speedl_capture_pending_{false}; + bool speedl_command_ready_{false}; + Eigen::Vector3d speedl_line_start_tcp_base_{Eigen::Vector3d::Zero()}; + Eigen::Vector3d speedl_line_direction_base_{Eigen::Vector3d::Zero()}; + double speedl_applied_acceleration_{0.25}; + double speedl_applied_angular_acceleration_{0.25}; + double speedl_applied_linear_jerk_{-1.0}; + bool speedl_line_check_active_{false}; + bool speedl_line_alignment_pending_{false}; + bool speedl_line_deviation_warned_{false}; + bool speedl_line_direction_warned_{false}; + + double adaptive_logged_scale{1.0}; + double adaptive_log_elapsed{0.0}; + double adaptive_scale{1.0}; + Result adaptive_stop_reason{Result::success()}; + FrameType adaptive_frame{FrameType::Base}; + Eigen::Matrix adaptive_original_target{Eigen::Matrix::Zero()}; + Eigen::Matrix adaptive_limited_target{Eigen::Matrix::Zero()}; + Eigen::Matrix adaptive_direction_base{Eigen::Matrix::Zero()}; + Eigen::VectorXd adaptive_joint_direction; + }; + State state_; + std::optional pending_; + + bool speedl_configured_{false}; +}; + +} // namespace cmvr::device + +#endif // CMVR_ES_PINOCCHIO_CARTESIAN_VELOCITY_PLANNER_H diff --git a/cmvr-es/algorithms/planner/cartesian/pinocchio/src/pinocchio_cartesian_trajectory_planner.cpp b/cmvr-es/algorithms/planner/cartesian/pinocchio/src/pinocchio_cartesian_trajectory_planner.cpp new file mode 100644 index 00000000..4002b8a7 --- /dev/null +++ b/cmvr-es/algorithms/planner/cartesian/pinocchio/src/pinocchio_cartesian_trajectory_planner.cpp @@ -0,0 +1,679 @@ +#include "algorithms/planner/cartesian/pinocchio/include/pinocchio_cartesian_trajectory_planner.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "curves/s_curve/include/s_curve.h" +#include "common/base/logging/logger.h" +#include "common/math/cartesian_motion_math.h" +#include "common/config/config_files.h" +#include "common/math/transform_math.h" + +namespace cmvr::device { + +using cmvr::common::config::positiveOr; +using cmvr::device::cartesian_motion::clamp; +using cmvr::device::cartesian_motion::directionDeviationDeg; +using cmvr::device::cartesian_motion::lateralDistanceToLine; +using cmvr::device::cartesian_motion::rotationVector; +using cmvr::device::cartesian_motion::toEigenVector; +using cmvr::device::cartesian_motion::toStdVector; + +namespace { + +double elapsedMs(const std::chrono::steady_clock::time_point start, + const std::chrono::steady_clock::time_point end) +{ + return std::chrono::duration(end - start).count(); +} + +} // namespace + +PinocchioCartesianTrajectoryPlanner::PinocchioCartesianTrajectoryPlanner( + std::shared_ptr solver) + : solver_(std::move(solver)) +{ +} + +bool PinocchioCartesianTrajectoryPlanner::configureMoveL( + const config::MoveLPlannerConfig& config) +{ + if (!std::isfinite(config.sample_period_s()) || + !std::isfinite(config.position_gain()) || + !std::isfinite(config.rotation_gain())) { + return false; + } + movel_config_ = config; + return true; +} + +bool PinocchioCartesianTrajectoryPlanner::planMoveL(const CartesianPose& target, + const std::vector& q_start, + const std::vector& qd_max, + const double velocity, + const double acceleration, + const double jerk, + const FrameType frame, + CartesianJointTrajectory& trajectory) +{ + const auto plan_start_time = std::chrono::steady_clock::now(); + double validation_ms = 0.0; + double current_pose_jacobian_ms = 0.0; + double solve_velocity_ms = 0.0; + double next_pose_jacobian_ms = 0.0; + std::size_t loop_count = 0; + struct PlanMoveLTimingLog { + std::chrono::steady_clock::time_point start_time; + double& validation_ms; + double& current_pose_jacobian_ms; + double& solve_velocity_ms; + double& next_pose_jacobian_ms; + std::size_t& loop_count; + CartesianJointTrajectory& trajectory; + + ~PlanMoveLTimingLog() + { + const auto end_time = std::chrono::steady_clock::now(); + const double total_ms = elapsedMs(start_time, end_time); + const double kinematics_ms = current_pose_jacobian_ms + next_pose_jacobian_ms; + const double measured_planning_ms = kinematics_ms + solve_velocity_ms; + const double planning_ms = std::max(0.0, total_ms - validation_ms); + const double misc_ms = std::max(0.0, planning_ms - measured_planning_ms); + const double loop_count_d = static_cast(loop_count); + const double per_loop_ms = loop_count_d > 0.0 ? planning_ms / loop_count_d : 0.0; + std::ostringstream oss; + oss << "[PinocchioCartesianTrajectoryPlanner][moveL][plan] timing: total_ms=" + << total_ms + << ", planning_ms=" << planning_ms + << ", validation_ms=" << validation_ms + << ", kinematics_ms=" << kinematics_ms + << ", ik_ms=" << solve_velocity_ms + << ", misc_ms=" << misc_ms + << ", loops=" << loop_count + << ", per_loop_ms=" << per_loop_ms + << ", points=" << trajectory.position.size() + << ", planned_path_m=" << trajectory.planned_path_length + << ", executable_path_m=" << trajectory.executable_path_length + << ", truncated=" << trajectory.truncated; + if (trajectory.truncated && !trajectory.truncation_reason.empty()) { + oss << ", reason=" << trajectory.truncation_reason; + } + CMVR_LOG(INFO) << oss.str(); + } + } timing_log{plan_start_time, + validation_ms, + current_pose_jacobian_ms, + solve_velocity_ms, + next_pose_jacobian_ms, + loop_count, + trajectory}; + auto measure_validation = [&validation_ms](auto&& validator) { + const auto start_time = std::chrono::steady_clock::now(); + const bool result = validator(); + validation_ms += elapsedMs(start_time, std::chrono::steady_clock::now()); + return result; + }; + auto measure_planning = [](double& accumulator_ms, auto&& operation) { + const auto start_time = std::chrono::steady_clock::now(); + const bool result = operation(); + accumulator_ms += elapsedMs(start_time, std::chrono::steady_clock::now()); + return result; + }; + + trajectory = {}; + const double dt = positiveOr(movel_config_.sample_period_s(), 0.001); + if (!solver_ || q_start.empty() || + velocity <= 0.0 || acceleration <= 0.0 || jerk <= 0.0) { + return false; + } + if (static_cast(q_start.size()) != solver_->chainDof()) { + return false; + } + if (!qd_max.empty() && qd_max.size() != q_start.size()) { + return false; + } + + Eigen::Matrix4d start_pose_base = Eigen::Matrix4d::Identity(); + if (!solver_->fk(q_start, start_pose_base, true)) { + return false; + } + + const Eigen::Matrix4d target_pose_input = common::math::poseToMatrix(target); + const Eigen::Matrix4d target_pose_base = + frame == FrameType::Tool ? start_pose_base * target_pose_input : target_pose_input; + + const Eigen::Vector3d p_start = start_pose_base.block<3, 1>(0, 3); + const Eigen::Vector3d p_target = target_pose_base.block<3, 1>(0, 3); + const Eigen::Vector3d dp = p_target - p_start; + const double linear_distance = dp.norm(); + + const Eigen::Matrix3d R_start = start_pose_base.block<3, 3>(0, 0); + const Eigen::Matrix3d R_target = target_pose_base.block<3, 3>(0, 0); + const Eigen::Vector3d total_rotation_vector = rotationVector(R_target * R_start.transpose()); + const double angular_distance = total_rotation_vector.norm(); + + const double path_length = linear_distance > 1e-9 ? linear_distance : angular_distance; + trajectory.planned_path_length = path_length; + trajectory.executable_path_length = 0.0; + trajectory.position.push_back(q_start); + trajectory.velocity.push_back(std::vector(q_start.size(), 0.0)); + trajectory.time.push_back(0.0); + if (path_length <= 1e-9) { + return true; + } + + cmvr::SCurve curve(velocity, acceleration, jerk); + const cmvr::SCurveProfile profile = curve.calculatePositionProfile(0.0, path_length, 0.0, 0.0); + if (profile.total_time <= 0.0) { + return false; + } + const auto reserve_count = + static_cast(std::ceil(profile.total_time / dt)) + 2U; + trajectory.position.reserve(reserve_count); + trajectory.velocity.reserve(reserve_count); + trajectory.time.reserve(reserve_count); + + Eigen::VectorXd q_current = toEigenVector(q_start); + Eigen::Vector3d linear_direction = Eigen::Vector3d::Zero(); + if (linear_distance > 1e-9) { + linear_direction = dp / linear_distance; + } + const Eigen::Quaterniond q_start_rot(R_start); + const Eigen::Quaterniond q_target_rot(R_target); + const double position_gain = positiveOr(movel_config_.position_gain(), 4.0); + const double rotation_gain = positiveOr(movel_config_.rotation_gain(), 4.0); + bool line_deviation_warned = false; + bool line_direction_warned = false; + double executable_path_length = 0.0; + Eigen::VectorXd prev_qdot = Eigen::VectorXd::Zero(q_current.size()); + Eigen::Matrix4d cached_current_pose_base = Eigen::Matrix4d::Identity(); + Eigen::MatrixXd cached_current_jacobian_base; + Eigen::Matrix3d cached_current_base_R_tool = Eigen::Matrix3d::Identity(); + bool cached_current_pose_valid = false; + std::vector q_std(q_start.size(), 0.0); + std::vector q_next_std(q_start.size(), 0.0); + std::vector qdot_std(q_start.size(), 0.0); + Eigen::Matrix4d current_pose_base = Eigen::Matrix4d::Identity(); + Eigen::MatrixXd jacobian_base; + Eigen::Matrix3d base_R_tool = Eigen::Matrix3d::Identity(); + Eigen::Matrix4d next_pose_base = Eigen::Matrix4d::Identity(); + Eigen::Matrix3d next_base_R_tool = Eigen::Matrix3d::Identity(); + auto copyEigenToStdVector = [](const Eigen::VectorXd& src, std::vector& dst) { + dst.resize(static_cast(src.size())); + Eigen::Map(dst.data(), src.size()) = src; + }; + + double previous_time = 0.0; + for (double t = std::min(dt, profile.total_time); + t <= profile.total_time + 1e-9; + t = std::min(t + dt, profile.total_time)) { + ++loop_count; + const double step_dt = std::max(1e-6, t - previous_time); + previous_time = t; + + const double s = clamp(curve.getPositionAtTime(profile, t), 0.0, path_length); + const double sd = std::max(0.0, curve.getVelocityAtTime(profile, t)); + const double ratio = clamp(s / path_length, 0.0, 1.0); + + copyEigenToStdVector(q_current, q_std); + if (cached_current_pose_valid) { + current_pose_base = cached_current_pose_base; + jacobian_base.swap(cached_current_jacobian_base); + base_R_tool = cached_current_base_R_tool; + } else { + if (!measure_planning(current_pose_jacobian_ms, [&]() { + return solver_->computePoseAndJacobianBaseAtQ(q_std, + true, + current_pose_base, + jacobian_base, + base_R_tool); + })) { + return false; + } + } + + const Eigen::Vector3d p_current = current_pose_base.block<3, 1>(0, 3); + const Eigen::Vector3d p_desired = p_start + ratio * dp; + std::string stop_reason; + if (!measure_validation([&]() { + return checkMoveLPlanLineDeviation_(p_start, + linear_direction, + p_current, + (p_current - p_start).norm(), + line_deviation_warned, + line_direction_warned, + stop_reason); + })) { + trajectory.truncated = true; + trajectory.truncation_reason = std::move(stop_reason); + trajectory.executable_path_length = executable_path_length; + break; + } + Eigen::Matrix target_twist_base = Eigen::Matrix::Zero(); + target_twist_base.head<3>() = + linear_direction * sd + position_gain * (p_desired - p_current); + + if (angular_distance > 1e-9) { + const Eigen::Matrix3d R_current = current_pose_base.block<3, 3>(0, 0); + const Eigen::Matrix3d R_desired = + q_start_rot.slerp(ratio, q_target_rot).toRotationMatrix(); + const Eigen::Vector3d rotation_error = + rotationVector(R_desired * R_current.transpose()); + target_twist_base.tail<3>() = + (total_rotation_vector / path_length) * sd + rotation_gain * rotation_error; + } + + if (!measure_planning(solve_velocity_ms, [&]() { + return solver_->solveVelocityBase(jacobian_base, + target_twist_base, + q_std, + qdot_std, + std::numeric_limits::infinity()); + })) { + return false; + } + + Eigen::Map qdot(qdot_std.data(), + static_cast(qdot_std.size())); + Eigen::VectorXd qdot_limited = qdot; + if (!qd_max.empty()) { + double scale = 1.0; + for (Eigen::Index i = 0; i < qdot_limited.size(); ++i) { + const double limit = std::abs(qd_max[static_cast(i)]); + if (limit <= 0.0 || !std::isfinite(limit)) { + continue; + } + const double value = std::abs(qdot_limited[i]); + if (value > limit) { + scale = std::min(scale, limit / value); + } + } + qdot_limited *= scale; + } + const Eigen::Matrix achieved_twist_base = jacobian_base * qdot_limited; + if (!measure_validation([&]() { + return checkMoveLPlanCartesianStepFeasibility_(target_twist_base, + achieved_twist_base, + s, + stop_reason); + })) { + trajectory.truncated = true; + trajectory.truncation_reason = std::move(stop_reason); + trajectory.executable_path_length = executable_path_length; + break; + } + const Eigen::VectorXd q_next = q_current + qdot_limited * step_dt; + if (!measure_validation([&]() { + return checkMoveLPlanJointContinuity_(q_current, + q_next, + qdot_limited, + prev_qdot, + step_dt, + s, + stop_reason); + })) { + trajectory.truncated = true; + trajectory.truncation_reason = std::move(stop_reason); + trajectory.executable_path_length = executable_path_length; + break; + } + if (!measure_validation([&]() { + return checkMoveLPlanJointPositionLimits_(q_current, + q_next, + qdot_limited, + step_dt, + s, + stop_reason); + })) { + trajectory.truncated = true; + trajectory.truncation_reason = std::move(stop_reason); + trajectory.executable_path_length = executable_path_length; + break; + } + + copyEigenToStdVector(q_next, q_next_std); + if (!measure_planning(next_pose_jacobian_ms, [&]() { + return solver_->computePoseAndJacobianBaseAtQ(q_next_std, + true, + next_pose_base, + cached_current_jacobian_base, + next_base_R_tool); + })) { + return false; + } + const Eigen::Vector3d p_next = next_pose_base.block<3, 1>(0, 3); + if (!measure_validation([&]() { + return checkMoveLPlanLineDeviation_(p_start, + linear_direction, + p_next, + (p_next - p_start).norm(), + line_deviation_warned, + line_direction_warned, + stop_reason); + })) { + trajectory.truncated = true; + trajectory.truncation_reason = std::move(stop_reason); + trajectory.executable_path_length = executable_path_length; + break; + } + + q_current = q_next; + prev_qdot = qdot_limited; + cached_current_pose_base = next_pose_base; + cached_current_base_R_tool = next_base_R_tool; + cached_current_pose_valid = true; + + trajectory.position.push_back(toStdVector(q_current)); + trajectory.velocity.push_back(toStdVector(qdot_limited)); + trajectory.time.push_back(t); + executable_path_length = s; + trajectory.executable_path_length = executable_path_length; + + if (t >= profile.total_time - 1e-9) { + break; + } + } + if (!trajectory.truncated) { + trajectory.executable_path_length = path_length; + } + + return true; +} + +bool PinocchioCartesianTrajectoryPlanner::checkMoveLPlanJointContinuity_( + const Eigen::VectorXd& q_current, + const Eigen::VectorXd& q_next, + const Eigen::VectorXd& qdot, + const Eigen::VectorXd& prev_qdot, + const double dt, + const double path_position, + std::string& stop_reason) const +{ + const auto& config = movel_config_.joint_continuity_check(); + if (!config.enable()) { + return true; + } + if (q_current.size() != q_next.size() || + q_current.size() != qdot.size() || + qdot.size() != prev_qdot.size() || + dt <= 0.0 || !std::isfinite(dt)) { + stop_reason = "joint continuity invalid state"; + CMVR_LOG(WARNING) << "[PinocchioCartesianTrajectoryPlanner][moveL][plan] joint continuity invalid state"; + return false; + } + + for (Eigen::Index i = 0; i < q_next.size(); ++i) { + if (!std::isfinite(q_current[i]) || + !std::isfinite(q_next[i]) || + !std::isfinite(qdot[i]) || + !std::isfinite(prev_qdot[i])) { + std::ostringstream oss; + oss << "joint continuity non-finite value: joint_index=" << i + << ", path_position_m=" << path_position; + stop_reason = oss.str(); + CMVR_LOG(WARNING) << "[PinocchioCartesianTrajectoryPlanner][moveL][plan] " + << stop_reason; + return false; + } + } + + const double max_delta = (q_next - q_current).cwiseAbs().maxCoeff(); + const double max_velocity = qdot.cwiseAbs().maxCoeff(); + const double max_acceleration = ((qdot - prev_qdot) / dt).cwiseAbs().maxCoeff(); + const double delta_limit = positiveOr(config.max_joint_delta_rad(), 0.05); + const double velocity_limit = positiveOr(config.max_joint_velocity_rad_s(), 10.0); + const double acceleration_limit = positiveOr(config.max_joint_acceleration_rad_s2(), 5000.0); + + if (max_delta > delta_limit || + max_velocity > velocity_limit || + max_acceleration > acceleration_limit) { + CMVR_LOG(WARNING) << "[PinocchioCartesianTrajectoryPlanner][moveL][plan] joint continuity exceeds stop threshold: max_delta_rad=" + << max_delta << ", delta_limit_rad=" << delta_limit + << ", max_velocity_rad_s=" << max_velocity + << ", velocity_limit_rad_s=" << velocity_limit + << ", max_acceleration_rad_s2=" << max_acceleration + << ", acceleration_limit_rad_s2=" << acceleration_limit + << ", path_position_m=" << path_position; + std::ostringstream oss; + oss << "joint continuity too large: max_delta_rad=" << max_delta + << ", delta_limit_rad=" << delta_limit + << ", max_velocity_rad_s=" << max_velocity + << ", velocity_limit_rad_s=" << velocity_limit + << ", max_acceleration_rad_s2=" << max_acceleration + << ", acceleration_limit_rad_s2=" << acceleration_limit + << ", path_position_m=" << path_position; + stop_reason = oss.str(); + return false; + } + return true; +} + +bool PinocchioCartesianTrajectoryPlanner::checkMoveLPlanJointPositionLimits_( + const Eigen::VectorXd& q_current, + const Eigen::VectorXd& q_next, + const Eigen::VectorXd& qdot, + const double dt, + const double path_position, + std::string& stop_reason) const +{ + if (!solver_ || !solver_->jointLimitPolicy().limits().enable()) { + return true; + } + if (q_current.size() != q_next.size() || + q_current.size() != qdot.size()) { + stop_reason = "joint position limit check size mismatch"; + CMVR_LOG(WARNING) << "[PinocchioCartesianTrajectoryPlanner][moveL][plan] " + << stop_reason; + return false; + } + + Eigen::VectorXd lower; + Eigen::VectorXd upper; + if (!solver_->getJointPositionLimits(lower, upper) || + lower.size() != q_next.size() || + upper.size() != q_next.size()) { + return true; + } + + std::vector joint_names; + (void)solver_->getChainJointNames(joint_names); + constexpr double kLimitEps = 1e-6; + for (Eigen::Index i = 0; i < q_next.size(); ++i) { + const double q = q_current[i]; + const double qn = q_next[i]; + const double lo = lower[i]; + const double hi = upper[i]; + if (!std::isfinite(q) || !std::isfinite(qn) || + !std::isfinite(lo) || !std::isfinite(hi) || hi <= lo) { + continue; + } + + const bool violates_lower = qn < lo - kLimitEps; + const bool violates_upper = qn > hi + kLimitEps; + const bool moves_out_lower = q <= lo + kLimitEps && qdot[i] < -kLimitEps; + const bool moves_out_upper = q >= hi - kLimitEps && qdot[i] > kLimitEps; + if (violates_lower || violates_upper || moves_out_lower || moves_out_upper) { + const std::string joint_name = + static_cast(i) < joint_names.size() + ? joint_names[static_cast(i)] + : std::to_string(i); + CMVR_LOG(WARNING) << "[PinocchioCartesianTrajectoryPlanner][moveL][plan] predicted joint position limit exceeded: joint=" + << joint_name << ", q=" << q + << ", q_next=" << qn + << ", lower=" << lo + << ", upper=" << hi + << ", qdot=" << qdot[i] + << ", dt=" << dt + << ", path_position_m=" << path_position; + std::ostringstream oss; + oss << "joint position limit exceeded: joint=" << joint_name + << ", q=" << q + << ", q_next=" << qn + << ", lower=" << lo + << ", upper=" << hi + << ", qdot=" << qdot[i] + << ", dt=" << dt + << ", path_position_m=" << path_position; + stop_reason = oss.str(); + return false; + } + } + return true; +} + +bool PinocchioCartesianTrajectoryPlanner::checkMoveLPlanCartesianStepFeasibility_( + const Eigen::Matrix& desired_twist, + const Eigen::Matrix& achieved_twist, + const double path_position, + std::string& stop_reason) const +{ + const auto& config = movel_config_.cartesian_step_feasibility_check(); + if (!config.enable()) { + return true; + } + + const Eigen::Vector3d desired_linear = desired_twist.head<3>(); + const Eigen::Vector3d achieved_linear = achieved_twist.head<3>(); + const double desired_linear_norm = desired_linear.norm(); + const double achieved_linear_norm = achieved_linear.norm(); + const double min_desired_linear_speed = + positiveOr(config.min_desired_linear_speed(), 1e-4); + if (desired_linear_norm >= min_desired_linear_speed) { + const double speed_ratio = achieved_linear_norm / desired_linear_norm; + const double min_ratio = positiveOr(config.min_linear_speed_ratio(), 0.2); + const double deviation_deg = + achieved_linear_norm > 1e-9 + ? directionDeviationDeg(desired_linear, achieved_linear) + : 180.0; + const double max_deviation_deg = + positiveOr(config.max_linear_direction_deviation_deg(), 45.0); + if (speed_ratio < min_ratio || deviation_deg > max_deviation_deg) { + CMVR_LOG(WARNING) << "[PinocchioCartesianTrajectoryPlanner][moveL][plan] cartesian step infeasible after joint limits: desired_linear=[" + << desired_linear.transpose() << "], achieved_linear=[" + << achieved_linear.transpose() << "], speed_ratio=" + << speed_ratio << ", min_ratio=" << min_ratio + << ", deviation_deg=" << deviation_deg + << ", max_deviation_deg=" << max_deviation_deg + << ", path_position_m=" << path_position; + std::ostringstream oss; + oss << "cartesian step infeasible after joint limits: linear_speed_ratio=" + << speed_ratio << ", min_ratio=" << min_ratio + << ", linear_deviation_deg=" << deviation_deg + << ", max_deviation_deg=" << max_deviation_deg + << ", path_position_m=" << path_position; + stop_reason = oss.str(); + return false; + } + } + + const Eigen::Vector3d desired_angular = desired_twist.tail<3>(); + const Eigen::Vector3d achieved_angular = achieved_twist.tail<3>(); + const double desired_angular_norm = desired_angular.norm(); + const double achieved_angular_norm = achieved_angular.norm(); + const double min_desired_angular_speed = + positiveOr(config.min_desired_angular_speed(), 1e-4); + if (desired_angular_norm >= min_desired_angular_speed) { + const double speed_ratio = achieved_angular_norm / desired_angular_norm; + const double min_ratio = positiveOr(config.min_angular_speed_ratio(), 0.2); + const double deviation_deg = + achieved_angular_norm > 1e-9 + ? directionDeviationDeg(desired_angular, achieved_angular) + : 180.0; + const double max_deviation_deg = + positiveOr(config.max_angular_direction_deviation_deg(), 45.0); + if (speed_ratio < min_ratio || deviation_deg > max_deviation_deg) { + CMVR_LOG(WARNING) << "[PinocchioCartesianTrajectoryPlanner][moveL][plan] cartesian angular step infeasible after joint limits: desired_angular=[" + << desired_angular.transpose() << "], achieved_angular=[" + << achieved_angular.transpose() << "], speed_ratio=" + << speed_ratio << ", min_ratio=" << min_ratio + << ", deviation_deg=" << deviation_deg + << ", max_deviation_deg=" << max_deviation_deg + << ", path_position_m=" << path_position; + std::ostringstream oss; + oss << "cartesian angular step infeasible after joint limits: angular_speed_ratio=" + << speed_ratio << ", min_ratio=" << min_ratio + << ", angular_deviation_deg=" << deviation_deg + << ", max_deviation_deg=" << max_deviation_deg + << ", path_position_m=" << path_position; + stop_reason = oss.str(); + return false; + } + } + + return true; +} + +bool PinocchioCartesianTrajectoryPlanner::checkMoveLPlanLineDeviation_( + const Eigen::Vector3d& p_start, + const Eigen::Vector3d& line_direction, + const Eigen::Vector3d& p_current, + const double traveled, + bool& deviation_warned, + bool& direction_warned, + std::string& stop_reason) const +{ + const auto& config = movel_config_.line_deviation_check(); + if (!config.enable() || line_direction.squaredNorm() <= 1e-12) { + return true; + } + + const double min_distance = positiveOr(config.line_check_min_distance_m(), 0.01); + if (traveled < min_distance) { + return true; + } + + const double lateral_error = lateralDistanceToLine(p_start, line_direction, p_current); + const double stop_m = positiveOr(config.line_deviation_stop_m(), 0.03); + if (lateral_error >= stop_m) { + CMVR_LOG(WARNING) << "[PinocchioCartesianTrajectoryPlanner][moveL][plan] line deviation exceeds stop threshold: lateral_error_m=" + << lateral_error << ", stop_m=" << stop_m + << ", traveled_m=" << traveled; + deviation_warned = true; + std::ostringstream oss; + oss << "line deviation too large: lateral_error_m=" << lateral_error + << ", stop_m=" << stop_m + << ", traveled_m=" << traveled; + stop_reason = oss.str(); + return false; + } + + const double warn_m = positiveOr(config.line_deviation_warn_m(), 0.01); + if (!deviation_warned && lateral_error >= warn_m) { + CMVR_LOG(WARNING) << "[PinocchioCartesianTrajectoryPlanner][moveL][plan] line deviation warning: lateral_error_m=" + << lateral_error << ", warn_m=" << warn_m + << ", traveled_m=" << traveled; + deviation_warned = true; + } + + const Eigen::Vector3d actual_direction = (p_current - p_start) / traveled; + const double deviation_deg = directionDeviationDeg(line_direction, actual_direction); + const double stop_deg = positiveOr(config.line_direction_stop_deg(), 45.0); + if (deviation_deg >= stop_deg) { + CMVR_LOG(WARNING) << "[PinocchioCartesianTrajectoryPlanner][moveL][plan] line direction deviation exceeds stop threshold: deviation_deg=" + << deviation_deg << ", stop_deg=" << stop_deg + << ", traveled_m=" << traveled; + direction_warned = true; + std::ostringstream oss; + oss << "line direction deviation too large: deviation_deg=" << deviation_deg + << ", stop_deg=" << stop_deg + << ", traveled_m=" << traveled; + stop_reason = oss.str(); + return false; + } + + const double warn_deg = positiveOr(config.line_direction_warn_deg(), 20.0); + if (!direction_warned && deviation_deg >= warn_deg) { + CMVR_LOG(WARNING) << "[PinocchioCartesianTrajectoryPlanner][moveL][plan] line direction deviation warning: deviation_deg=" + << deviation_deg << ", warn_deg=" << warn_deg + << ", traveled_m=" << traveled; + direction_warned = true; + } + return true; +} + +} // namespace cmvr::device diff --git a/cmvr-es/algorithms/planner/cartesian/pinocchio/src/pinocchio_cartesian_velocity_planner.cpp b/cmvr-es/algorithms/planner/cartesian/pinocchio/src/pinocchio_cartesian_velocity_planner.cpp new file mode 100644 index 00000000..18c99e37 --- /dev/null +++ b/cmvr-es/algorithms/planner/cartesian/pinocchio/src/pinocchio_cartesian_velocity_planner.cpp @@ -0,0 +1,1017 @@ +#include "algorithms/planner/cartesian/pinocchio/include/pinocchio_cartesian_velocity_planner.h" + +#include +#include +#include +#include +#include +#include +#include +#include "algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_qp_ik_solver.h" + +#include "algorithms/planner/cartesian/s_curve/include/s_curve_planner_config.h" +#include "common/base/logging/logger.h" +#include "common/config/config_files.h" +#include "common/math/cartesian_motion_math.h" +#include "common/math/transform_math.h" + +namespace cmvr::device { + +using cmvr::common::config::positiveOr; +using cmvr::device::cartesian_motion::directionDeviationDeg; +using cmvr::device::cartesian_motion::lateralDistanceToLine; +using cmvr::device::cartesian_motion::toEigenVector; +using cmvr::device::cartesian_motion::toStdVector; + +PinocchioCartesianVelocityPlanner::PinocchioCartesianVelocityPlanner( + std::shared_ptr solver) + : solver_(std::move(solver)) +{ +} + +bool PinocchioCartesianVelocityPlanner::refreshJointAccelerationLimits_() +{ + if (!solver_) { + return false; + } + const auto& limits = solver_->jointLimitPolicy().limits(); + if (limits.source() != config::JOINT_LIMIT_SOURCE_CUSTOM) { + state_.joint_acceleration_limits_.resize(0); + return true; + } + + std::vector joint_names; + if (!solver_->getChainJointNames(joint_names) || joint_names.empty()) { + return false; + } + + std::unordered_map custom_limits; + custom_limits.reserve(static_cast(limits.joints_size())); + for (const auto& item : limits.joints()) { + if (!item.joint_name().empty()) { + custom_limits[item.joint_name()] = item; + } + } + + Eigen::VectorXd acceleration_limits(static_cast(joint_names.size())); + for (Eigen::Index i = 0; i < acceleration_limits.size(); ++i) { + const auto& joint_name = joint_names[static_cast(i)]; + const auto it = custom_limits.find(joint_name); + if (it == custom_limits.end() || !std::isfinite(it->second.qdd()) || it->second.qdd() < 0.0) { + CMVR_LOG(ERROR) << "[PinocchioCartesianVelocityPlanner] invalid custom qdd for " + << joint_name; + return false; + } + acceleration_limits[i] = std::abs(it->second.qdd()); + } + state_.joint_acceleration_limits_ = std::move(acceleration_limits); + return true; +} + +Eigen::VectorXd PinocchioCartesianVelocityPlanner::jointAccelerationStepLimits_( + const Eigen::Index dof, const double dt) const +{ + Eigen::VectorXd delta(dof); + for (Eigen::Index i = 0; i < dof; ++i) { + double acc_limit = 8.0; + if (state_.joint_acceleration_limits_.size() == dof && + state_.joint_acceleration_limits_[i] > 0.0) { + acc_limit = state_.joint_acceleration_limits_[i]; + } + delta[i] = acc_limit * dt; + } + return delta; +} + +bool PinocchioCartesianVelocityPlanner::configureSpeedL(const config::SpeedLPlannerConfig& config, + const std::size_t dof) +{ + if (!solver_ || dof == 0) { + return false; + } + if (!std::isfinite(config.adaptive_speed().lookahead_s()) || + config.adaptive_speed().lookahead_s() < 0.0) { + CMVR_LOG(ERROR) << "[PinocchioCartesianVelocityPlanner] invalid adaptive speed lookahead"; + return false; + } + const double min_speed_ratio = config.adaptive_speed().min_speed_ratio(); + if (!std::isfinite(min_speed_ratio) || min_speed_ratio < 0.0 || min_speed_ratio > 1.0) { + CMVR_LOG(ERROR) << "[PinocchioCartesianVelocityPlanner] min_speed_ratio must be within [0, 1]"; + return false; + } + pending_.reset(); + const auto solver_dof = static_cast(std::max(0, solver_->chainVelocityDof())); + if (solver_dof != 0 && solver_dof != dof) { + return false; + } + cmvr::SCurvePlanner planner; + try { + cartesian_motion::configureSCurvePlannerFromSpeedLConfig(planner, config); + } catch (const std::invalid_argument& error) { + CMVR_LOG(ERROR) << "[PinocchioCartesianVelocityPlanner] invalid speedL configuration: " + << error.what(); + return false; + } + + if (!refreshJointAccelerationLimits_()) { + return false; + } + + speedl_config_ = config; + state_.s_curve_planner_ = std::move(planner); + state_.speedl_applied_linear_jerk_ = -1.0; + + state_.prev_qdot_command_.assign(dof, 0.0); + state_.speedl_command_twist_base_.setZero(); + state_.speedl_line_check_active_ = false; + state_.speedl_line_alignment_pending_ = false; + state_.speedl_line_deviation_warned_ = false; + state_.speedl_line_direction_warned_ = false; + state_.speedl_command_ready_ = false; + state_.speedl_capture_pending_ = false; + state_.speedl_applied_acceleration_ = positiveOr(speedl_config_.linear_acceleration_max(), 5.0); + state_.speedl_applied_angular_acceleration_ = positiveOr(speedl_config_.angular_acceleration_max(), 5.0); + state_.adaptive_scale = state_.adaptive_logged_scale = 1.0; + state_.adaptive_stop_reason = Result::success(); + state_.adaptive_log_elapsed = 0.0; + state_.adaptive_joint_direction.resize(0); + speedl_configured_ = true; + return true; +} + +Result PinocchioCartesianVelocityPlanner::reset( + const std::vector& q, const std::vector& qd) +{ + pending_.reset(); + if (!solver_ || !speedl_configured_) { + return Result::failure(ArmErrorCode::RobotNotReady, "velocity planner is not configured"); + } + if (static_cast(q.size()) != solver_->chainDof() || + static_cast(qd.size()) != solver_->chainVelocityDof()) { + return Result::failure(ArmErrorCode::InvalidDof, "velocity reset state size mismatch"); + } + const auto finite = [](double value) { return std::isfinite(value); }; + if (!std::all_of(q.begin(), q.end(), finite) || !std::all_of(qd.begin(), qd.end(), finite)) { + return Result::failure(ArmErrorCode::InvalidArgument, "non-finite velocity reset state"); + } + Eigen::Matrix4d pose; + Eigen::MatrixXd jacobian; + Eigen::Matrix3d rotation; + if (!solver_->computePoseAndJacobianBaseAtQ(q, true, pose, jacobian, rotation) || + jacobian.rows() != 6 || jacobian.cols() != static_cast(qd.size()) || + !jacobian.allFinite()) { + return Result::failure(ArmErrorCode::CommandFailed, "velocity reset kinematics failed"); + } + const Eigen::Matrix initial_twist = jacobian * toEigenVector(qd); + try { + // initialize() is transactional and starts with zero acceleration. + state_.s_curve_planner_.initialize(initial_twist); + } catch (const std::invalid_argument& error) { + return Result::failure(ArmErrorCode::InvalidArgument, error.what()); + } + state_.prev_qdot_command_ = qd; + state_.speedl_command_twist_base_ = initial_twist; + state_.speedl_target_ = {}; + state_.speedl_frame_ = FrameType::Base; + state_.speedl_command_ready_ = false; + state_.speedl_capture_pending_ = false; + state_.speedl_line_start_tcp_base_.setZero(); + state_.speedl_line_direction_base_.setZero(); + state_.speedl_line_check_active_ = false; + state_.speedl_line_alignment_pending_ = false; + state_.speedl_line_deviation_warned_ = false; + state_.speedl_line_direction_warned_ = false; + state_.adaptive_scale = state_.adaptive_logged_scale = 1.0; + state_.adaptive_stop_reason = Result::success(); + state_.adaptive_log_elapsed = 0.0; + state_.adaptive_joint_direction.resize(0); + return Result::success(); +} + +bool PinocchioCartesianVelocityPlanner::updateAndValidateSpeedLLineDeviation_( + const Eigen::Vector3d& tcp_position, + const bool is_stop_command, + const Eigen::Vector3d& command_linear_base, + const Eigen::Vector3d& target_linear_base) +{ + const auto& config = speedl_config_.line_deviation_check(); + if (!config.enable()) { + return true; + } + + const double command_norm = command_linear_base.norm(); + if (is_stop_command || command_norm <= 1e-9) { + state_.speedl_line_check_active_ = false; + state_.speedl_line_alignment_pending_ = false; + state_.speedl_line_deviation_warned_ = false; + state_.speedl_line_direction_warned_ = false; + return true; + } + + const Eigen::Vector3d command_direction = command_linear_base / command_norm; + const double target_norm = target_linear_base.norm(); + const bool aligned = target_norm > 1e-9 && + (command_direction - target_linear_base / target_norm).norm() <= 1e-6; + // A turn can end less than reset_deg from the last transient axis. Relatch + // once when aligned; otherwise normal straight motion accumulates false drift. + bool reset_line = !state_.speedl_line_check_active_ || (state_.speedl_line_alignment_pending_ && aligned); + state_.speedl_line_alignment_pending_ = target_norm > 1e-9 && !aligned; + if (!reset_line && state_.speedl_line_direction_base_.squaredNorm() > 1e-12) { + const double reset_deg = positiveOr(config.line_direction_reset_deg(), 10.0); + const double command_change_deg = + directionDeviationDeg(state_.speedl_line_direction_base_, command_direction); + reset_line = command_change_deg >= reset_deg; + } + + if (reset_line) { + state_.speedl_line_start_tcp_base_ = tcp_position; + state_.speedl_line_direction_base_ = command_direction; + state_.speedl_line_check_active_ = true; + state_.speedl_line_deviation_warned_ = false; + state_.speedl_line_direction_warned_ = false; + return true; + } + + const Eigen::Vector3d delta = tcp_position - state_.speedl_line_start_tcp_base_; + const double traveled = delta.norm(); + const double min_distance = positiveOr(config.line_check_min_distance_m(), 0.01); + if (traveled < min_distance) { + return true; + } + + const double lateral_error = + lateralDistanceToLine(state_.speedl_line_start_tcp_base_, state_.speedl_line_direction_base_, tcp_position); + const double stop_m = positiveOr(config.line_deviation_stop_m(), 0.03); + if (lateral_error >= stop_m) { + CMVR_LOG(ERROR) << "[PinocchioCartesianVelocityPlanner][speedL] line deviation too large: lateral_error_m=" + << lateral_error << ", stop_m=" << stop_m + << ", traveled_m=" << traveled + << ", line_direction=" << state_.speedl_line_direction_base_.transpose() + << ", command_direction=" << command_direction.transpose(); + return false; + } + + const double warn_m = positiveOr(config.line_deviation_warn_m(), 0.01); + if (!state_.speedl_line_deviation_warned_ && lateral_error >= warn_m) { + CMVR_LOG(WARNING) << "[PinocchioCartesianVelocityPlanner][speedL] line deviation warning: lateral_error_m=" + << lateral_error << ", warn_m=" << warn_m + << ", traveled_m=" << traveled; + state_.speedl_line_deviation_warned_ = true; + } + + const Eigen::Vector3d actual_direction = delta / traveled; + const double deviation_deg = + directionDeviationDeg(state_.speedl_line_direction_base_, actual_direction); + const double stop_deg = positiveOr(config.line_direction_stop_deg(), 45.0); + if (deviation_deg >= stop_deg) { + CMVR_LOG(ERROR) << "[PinocchioCartesianVelocityPlanner][speedL] line direction deviation too large: deviation_deg=" + << deviation_deg << ", stop_deg=" << stop_deg + << ", traveled_m=" << traveled; + return false; + } + + const double warn_deg = positiveOr(config.line_direction_warn_deg(), 20.0); + if (!state_.speedl_line_direction_warned_ && deviation_deg >= warn_deg) { + CMVR_LOG(WARNING) << "[PinocchioCartesianVelocityPlanner][speedL] line direction deviation warning: deviation_deg=" + << deviation_deg << ", warn_deg=" << warn_deg + << ", traveled_m=" << traveled; + state_.speedl_line_direction_warned_ = true; + } + + return true; +} + +CartesianVelocityStep PinocchioCartesianVelocityPlanner::step( + const double dt, const std::vector& q_measured, + const std::vector& qd_measured, const double speed_scaling) +{ + pending_.reset(); + auto committed = state_; + try { + auto result = stepImpl_(dt, q_measured, qd_measured, speed_scaling); + if (result.status.ok()) pending_ = std::move(state_); + state_ = std::move(committed); + return result; + } catch (...) { + state_ = std::move(committed); + throw; + } +} + +void PinocchioCartesianVelocityPlanner::commitStep() +{ + if (!pending_) return; + const bool starting_stop = state_.adaptive_stop_reason.ok() && !pending_->adaptive_stop_reason.ok(); + state_ = std::move(*pending_); + pending_.reset(); + if (starting_stop) { + CMVR_LOG(WARNING) << "[PinocchioCartesianVelocityPlanner][ADAPTIVE_SPEED_STOP] " + << state_.adaptive_stop_reason.message << "; decelerating through S-curve"; + } + const double scale = state_.adaptive_scale; + const bool entering = scale < 0.999 && state_.adaptive_logged_scale >= 0.999; + const bool restoring = scale >= 0.999 && state_.adaptive_logged_scale < 0.999; + const bool stopping = scale == 0.0 && state_.adaptive_logged_scale > 0.0; + const bool changed = std::abs(scale - state_.adaptive_logged_scale) >= 0.01 && + state_.adaptive_log_elapsed >= 0.1; + if (speedl_config_.adaptive_speed().enable() && (entering || restoring || stopping || changed)) { + const auto& original = state_.adaptive_original_target; + const auto& limited = state_.adaptive_limited_target; + CMVR_LOG(INFO) << "[PinocchioCartesianVelocityPlanner][ADAPTIVE_SPEED]" + << " frame=" << (state_.adaptive_frame == FrameType::Tool ? "Tool" : "Base") + << ", original_target=[" << original.transpose() << "]" + << ", reduction_percent=" << (1.0 - scale) * 100.0 + << ", limited_target=[" << limited.transpose() << "]" + << ", original_linear_m_s=" << original.head<3>().norm() + << ", limited_linear_m_s=" << limited.head<3>().norm() + << ", original_angular_rad_s=" << original.tail<3>().norm() + << ", limited_angular_rad_s=" << limited.tail<3>().norm() + << ", planned_linear_m_s=" << state_.speedl_command_twist_base_.head<3>().norm() + << ", planned_angular_rad_s=" << state_.speedl_command_twist_base_.tail<3>().norm(); + state_.adaptive_logged_scale = scale; + state_.adaptive_log_elapsed = 0.0; + } +} + +double PinocchioCartesianVelocityPlanner::adaptiveScale_( + const Eigen::Matrix& target_base, const Eigen::MatrixXd& jacobian, + const std::vector& q, const std::vector& qd, const double dt) +{ + if (!speedl_config_.adaptive_speed().enable() || target_base.squaredNorm() < 1e-12 || + !solver_->jointLimitPolicy().limits().enable()) return 1.0; + // The preview QP keeps redundancy available while finding a feasible target + // scale. Its future-target bounds deliberately exclude one-step acceleration; + // the S-curve and final command QP enforce the actual next-step constraints. + Eigen::VectorXd lower, upper, velocity; + const Eigen::Index dof = static_cast(q.size()); + if (!solver_->getJointPositionLimits(lower, upper) || !solver_->getJointVelocityLimits(velocity) || + lower.size() != dof || upper.size() != dof || velocity.size() != dof || + !lower.allFinite() || !upper.allFinite() || !velocity.allFinite() || + (lower.array() >= upper.array()).any()) return std::numeric_limits::quiet_NaN(); + double horizon = std::max(positiveOr(speedl_config_.adaptive_speed().lookahead_s(), 0.15), 2.0 * dt); + // Keep at least the current S-curve stopping duration as preview time. + // Joint jerk is not inferred from Cartesian jerk; joint braking is checked separately. + const auto& curve = state_.s_curve_planner_; + for (int offset : {0, 3}) { + const double speed = curve.getTwistBase().segment<3>(offset).norm(); + const double acceleration = curve.getAccelerationBase().segment<3>(offset).norm(); + const double a_max = offset == 0 ? state_.speedl_applied_acceleration_ : state_.speedl_applied_angular_acceleration_; + const double j_max = offset == 0 ? positiveOr(state_.speedl_applied_linear_jerk_, 10.0) + : positiveOr(speedl_config_.angular_jerk_max(), 12.0); + const auto stop = SCurve(speed + acceleration * acceleration / (2.0 * j_max) + 1.0, a_max, j_max).calculateVelocityProfile( + speed, 0.0, std::min(acceleration, a_max)); + if (stop.valid) horizon = std::max(horizon, stop.total_time + 2.0 * dt); + } + const auto delta = jointAccelerationStepLimits_(dof, dt); + Eigen::VectorXd preview_lower(dof), preview_upper(dof); + const auto& soft = solver_->jointLimitPolicy().soft_limit(); + for (Eigen::Index i = 0; i < dof; ++i) { + const double previous = state_.prev_qdot_command_[i]; + const double positive_speed = std::max({0.0, qd[i], previous}); + const double negative_speed = std::max({0.0, -qd[i], -previous}); + const double acceleration = delta[i] / dt; + const double lower_reserve = negative_speed * dt + negative_speed * negative_speed / (2.0 * acceleration); + const double upper_reserve = positive_speed * dt + positive_speed * positive_speed / (2.0 * acceleration); + // Stay inside the solver's 1e-6 hard-limit clamp, including roundoff. + const double lower_distance = std::max(0.0, q[i] - lower[i] - 2e-6); + const double upper_distance = std::max(0.0, upper[i] - q[i] - 2e-6); + preview_lower[i] = -std::min(std::abs(velocity[i]), std::max(0.0, lower_distance - lower_reserve) / horizon); + preview_upper[i] = std::min(std::abs(velocity[i]), std::max(0.0, upper_distance - upper_reserve) / horizon); + if (soft.enable()) { + const double margin = std::max(positiveOr(soft.min_margin_rad(), 0.02), + positiveOr(soft.margin_ratio(), 0.08) * (upper[i] - lower[i])); + preview_lower[i] = std::max(preview_lower[i], -std::abs(velocity[i]) * std::min(1.0, lower_distance / margin)); + preview_upper[i] = std::min(preview_upper[i], std::abs(velocity[i]) * std::min(1.0, upper_distance / margin)); + } + } + double scale = 0.0; + if (!PinocchioQpIKSolver::computeVelocityScale(jacobian, target_base, preview_lower, preview_upper, scale)) { + return std::numeric_limits::quiet_NaN(); + } + // The preview QP may use a different redundant-joint allocation from the + // command QP. During straight motion also predict from the allocation that + // was actually sent, so a theoretical nullspace solution cannot postpone + // deceleration until the currently moving joint reaches its limit. + const auto& current = state_.speedl_command_twist_base_; + const double projection = current.dot(target_base) / target_base.squaredNorm(); + const auto direction = target_base.normalized().eval(); + if (current.norm() >= 1e-4 && projection > 0.0 && + (current - projection * target_base).norm() <= 1e-3 * current.norm()) { + state_.adaptive_joint_direction = toEigenVector(state_.prev_qdot_command_) / current.norm(); + state_.adaptive_direction_base = direction; + } + // Keep the last resolved direction when almost stopped; dividing numerical + // IK residuals by a vanishing TCP speed would otherwise restart acceleration. + if (state_.adaptive_joint_direction.size() == dof && + (direction - state_.adaptive_direction_base).norm() <= 1e-3) { + for (Eigen::Index i = 0; i < dof; ++i) { + const double predicted = state_.adaptive_joint_direction[i] * target_base.norm(); + if (predicted > 1e-9) scale = std::min(scale, preview_upper[i] / predicted); + if (predicted < -1e-9) scale = std::min(scale, preview_lower[i] / predicted); + } + } + return scale >= 1.0 - 1e-6 ? 1.0 : scale; +} + +CartesianVelocityStep PinocchioCartesianVelocityPlanner::brakeStep( + const double dt, const std::vector& q, const std::vector& qd) +{ + pending_.reset(); + CartesianVelocityStep result; + const auto finite = [](double value) { return std::isfinite(value); }; + if (!solver_ || !speedl_configured_ || !std::isfinite(dt) || dt < 1e-9 || + q.size() != static_cast(solver_->chainDof()) || qd.size() != q.size() || + state_.prev_qdot_command_.size() != q.size() || + !std::all_of(q.begin(), q.end(), finite) || !std::all_of(qd.begin(), qd.end(), finite)) { + result.status = Result::failure(ArmErrorCode::InvalidArgument, "invalid joint braking state"); + return result; + } + const auto delta = jointAccelerationStepLimits_(q.size(), dt); + Eigen::VectorXd lower, upper, velocity; + const bool bounded = solver_->jointLimitPolicy().limits().enable(); + if (bounded && (!solver_->getJointPositionLimits(lower, upper) || + !solver_->getJointVelocityLimits(velocity) || lower.size() != static_cast(q.size()) || + upper.size() != lower.size() || velocity.size() != lower.size())) { + result.status = Result::failure(ArmErrorCode::InvalidArgument, "invalid joint braking limits"); + return result; + } + result.joint_velocity.velocity.resize(q.size()); + result.settled = true; + for (std::size_t i = 0; i < q.size(); ++i) { + double lo = std::max(qd[i], state_.prev_qdot_command_[i]) - delta[i]; + double hi = std::min(qd[i], state_.prev_qdot_command_[i]) + delta[i]; + if (bounded) { + lo = std::max(lo, -std::abs(velocity[i])); + hi = std::min(hi, std::abs(velocity[i])); + } + if (lo > hi) { + result.status = Result::failure(ArmErrorCode::CommandFailed, "joint braking acceleration bounds conflict"); + result.joint_velocity.velocity.clear(); + return result; + } + const double command = std::clamp(0.0, lo, hi); + const double stop_distance = std::abs(command) * dt + command * command / (2.0 * (delta[i] / dt)); + const double furthest = q[i] + std::copysign(stop_distance, command); + if (bounded && (q[i] < lower[i] - 1e-6 || q[i] > upper[i] + 1e-6 || + furthest < lower[i] - 1e-6 || furthest > upper[i] + 1e-6)) { + result.status = Result::failure(ArmErrorCode::OutOfJointLimit, "joint braking would cross hard position limit"); + result.joint_velocity.velocity.clear(); + return result; + } + result.joint_velocity.velocity[i] = command; + result.settled = result.settled && std::abs(command) < 1e-9; + } + pending_ = state_; + pending_->prev_qdot_command_ = result.joint_velocity.velocity; + pending_->speedl_command_twist_base_.setZero(); + result.status = Result::success(); + return result; +} + +CartesianVelocityStep PinocchioCartesianVelocityPlanner::stepImpl_( + const double dt, const std::vector& q_measured, + const std::vector& qd_measured, const double speed_scaling) +{ + auto failure = [](ArmErrorCode code, const char* message) { + CartesianVelocityStep result; + result.status = Result::failure(code, message); + return result; + }; + if (!solver_ || !speedl_configured_ || !state_.speedl_command_ready_) { + return failure(ArmErrorCode::RobotNotReady, "velocity planner has no submitted command"); + } + if (!std::isfinite(dt) || dt <= 0.0) { + return failure(ArmErrorCode::InvalidArgument, "invalid velocity planning period"); + } + if (!std::isfinite(speed_scaling) || speed_scaling < 0.0 || speed_scaling > 1.0) { + return failure(ArmErrorCode::InvalidArgument, "speed scaling must be finite and within [0, 1]"); + } + if (static_cast(q_measured.size()) != solver_->chainDof() || + static_cast(qd_measured.size()) != solver_->chainVelocityDof()) { + return failure(ArmErrorCode::InvalidDof, "velocity planning state size mismatch"); + } + const auto finite = [](double value) { return std::isfinite(value); }; + if (!std::all_of(q_measured.begin(), q_measured.end(), finite) || + !std::all_of(qd_measured.begin(), qd_measured.end(), finite)) { + return failure(ArmErrorCode::InvalidArgument, "non-finite velocity planning state"); + } + + Eigen::Matrix4d tcp_pose_base; + Eigen::MatrixXd jacobian_base; + Eigen::Matrix3d base_R_tool; + if (!solver_->computePoseAndJacobianBaseAtQ(q_measured, true, tcp_pose_base, + jacobian_base, base_R_tool) || + !tcp_pose_base.allFinite() || !jacobian_base.allFinite()) { + return failure(ArmErrorCode::CommandFailed, "velocity planning kinematics failed"); + } + if (state_.speedl_frame_ == FrameType::Tool && !base_R_tool.allFinite()) { + return failure(ArmErrorCode::InvalidArgument, "non-finite Tool rotation"); + } + + const auto target_twist = common::math::velocityToVector(state_.speedl_target_); + bool is_stop_command = target_twist.squaredNorm() <= 1e-12; + auto plan_target = target_twist; + const double linear_limit = positiveOr(speedl_config_.linear_velocity_max(), .55); + const double angular_limit = positiveOr(speedl_config_.angular_velocity_max(), 1.0); + if (plan_target.head<3>().norm() > linear_limit) { + plan_target.head<3>() *= linear_limit / plan_target.head<3>().norm(); + } + if (plan_target.tail<3>().norm() > angular_limit) { + plan_target.tail<3>() *= angular_limit / plan_target.tail<3>().norm(); + } + plan_target *= speed_scaling; + state_.adaptive_original_target = plan_target; + state_.adaptive_frame = state_.speedl_frame_; + auto base_target = plan_target; + if (state_.speedl_frame_ == FrameType::Tool) { + base_target.head<3>() = base_R_tool * plan_target.head<3>(); + base_target.tail<3>() = base_R_tool * plan_target.tail<3>(); + } + if (state_.adaptive_stop_reason.ok()) { + state_.adaptive_scale = adaptiveScale_(base_target, jacobian_base, q_measured, qd_measured, dt); + if (!std::isfinite(state_.adaptive_scale)) { + return failure(ArmErrorCode::CommandFailed, "adaptive speed feasibility preview failed"); + } + const double min_ratio = speedl_config_.adaptive_speed().min_speed_ratio(); + if (speedl_config_.adaptive_speed().enable() && min_ratio > 0.0 && + base_target.squaredNorm() > 1e-12 && state_.adaptive_scale < min_ratio) { + std::ostringstream reason; + reason << "adaptive speed ratio below min_speed_ratio: allowed_ratio=" << state_.adaptive_scale + << ", min_speed_ratio=" << min_ratio + << ", original_linear_m_s=" << plan_target.head<3>().norm() + << ", original_angular_rad_s=" << plan_target.tail<3>().norm(); + state_.adaptive_stop_reason = Result::failure(ArmErrorCode::OutOfVelocityLimit, reason.str()); + } + // Preserve the previous near-zero hold behavior when the percentage + // threshold is disabled. Never quantize the ratio before comparing it. + if (min_ratio == 0.0 && state_.adaptive_scale < 1.0 && + state_.adaptive_scale * base_target.head<3>().norm() < + positiveOr(speedl_config_.linear_target_replan_threshold(), 1e-4) && + state_.adaptive_scale * base_target.tail<3>().norm() < + positiveOr(speedl_config_.angular_target_replan_threshold(), 1e-4)) { + state_.adaptive_scale = 0.0; + } + } + if (!state_.adaptive_stop_reason.ok()) { + // Finish the accepted S-curve stop even if feasibility subsequently + // improves. The executor publishes the reason after measured stop. + state_.adaptive_scale = 0.0; + is_stop_command = true; + } + plan_target *= state_.adaptive_scale; + state_.adaptive_limited_target = plan_target; + state_.adaptive_log_elapsed += dt; + try { + if (is_stop_command) { + plan_target.setZero(); + } + + state_.speedl_command_twist_base_ = state_.s_curve_planner_.plan( + plan_target, state_.speedl_frame_ == FrameType::Tool ? CartesianFrame::Tool : CartesianFrame::Base, + dt, base_R_tool); + } catch (const std::invalid_argument& error) { + return failure(ArmErrorCode::InvalidArgument, error.what()); + } catch (const std::runtime_error& error) { + return failure(ArmErrorCode::CommandFailed, error.what()); + } + Eigen::Vector3d target_linear_base = target_twist.head<3>(); + if (state_.speedl_frame_ == FrameType::Tool) target_linear_base = base_R_tool * target_linear_base.eval(); + if (!updateAndValidateSpeedLLineDeviation_(tcp_pose_base.block<3, 1>(0, 3), + is_stop_command, + state_.speedl_command_twist_base_.head<3>(), + target_linear_base)) { + return failure(ArmErrorCode::OutOfWorkspace, "velocity planning line deviation exceeded"); + } + + const Eigen::VectorXd reference = toEigenVector( + state_.prev_qdot_command_.size() == q_measured.size() ? state_.prev_qdot_command_ : qd_measured); + const bool limit_acceleration = !speedl_config_.has_enforce_joint_acceleration_limits() || + speedl_config_.enforce_joint_acceleration_limits(); + Eigen::VectorXd lower = Eigen::VectorXd::Constant(reference.size(), + -std::numeric_limits::infinity()); + Eigen::VectorXd upper = -lower; + if (limit_acceleration) { + const Eigen::VectorXd delta = jointAccelerationStepLimits_(reference.size(), dt); + lower = reference - delta; + upper = reference + delta; + } + Eigen::VectorXd qdot = Eigen::VectorXd::Zero(reference.size()); + const bool stopped_profile = !state_.s_curve_planner_.isMoving() && + state_.speedl_command_twist_base_.squaredNorm() <= 1e-12; + if (solver_->supportsJointVelocityBounds()) { + if (solver_->jointLimitPolicy().limits().enable()) { + Eigen::VectorXd position_lower, position_upper; + if (!solver_->getJointPositionLimits(position_lower, position_upper) || + position_lower.size() != reference.size() || + position_upper.size() != reference.size()) { + return failure(ArmErrorCode::InvalidArgument, "invalid joint position limits"); + } + const Eigen::VectorXd q = toEigenVector(q_measured); + lower = lower.cwiseMax((position_lower - q) / dt); + upper = upper.cwiseMin((position_upper - q) / dt); + } + // Also solve zero targets with acceleration bounds, so a stopped + // Cartesian profile cannot abruptly discard remaining joint motion. + std::vector qdot_std; + if (!solver_->solveVelocityBase(jacobian_base, state_.speedl_command_twist_base_, q_measured, + qdot_std, lower, upper)) { + CMVR_LOG(ERROR) << "[PinocchioCartesianVelocityPlanner][SPEEDL_QP_STATE] dt=" << dt + << ", q=[" << toEigenVector(q_measured).transpose() << "]" + << ", measured_qd=[" << toEigenVector(qd_measured).transpose() << "]" + << ", previous_command=[" << reference.transpose() << "]" + << ", external_lower=[" << lower.transpose() << "]" + << ", external_upper=[" << upper.transpose() << "]"; + return failure(ArmErrorCode::CommandFailed, + "Cartesian velocity is infeasible within joint limits"); + } + qdot = toEigenVector(qdot_std); + } else { + // DLS retains its existing acceleration limiting behavior. + if (!stopped_profile) { + std::vector qdot_std; + if (!solver_->solveVelocityBase(jacobian_base, state_.speedl_command_twist_base_, q_measured, + qdot_std, std::numeric_limits::infinity())) { + return failure(ArmErrorCode::CommandFailed, "velocity IK failed"); + } + qdot = toEigenVector(qdot_std); + } + if (limit_acceleration) qdot = qdot.cwiseMax(lower).cwiseMin(upper); + } + const Eigen::Matrix achieved_twist_base = jacobian_base * qdot; + // A near-zero stop command cannot define a meaningful direction/speed ratio. + if (!is_stop_command && speed_scaling > 0.0 && + !validateSpeedLCartesianVelocityFeasibility_(state_.speedl_command_twist_base_, + achieved_twist_base, + toEigenVector(q_measured), qdot)) { + return failure(ArmErrorCode::CommandFailed, "Cartesian velocity is infeasible after joint limits"); + } + if (!validateSpeedLJointVelocityCommand_(qdot, reference, dt)) { + return failure(ArmErrorCode::CommandFailed, "joint velocity or acceleration check failed"); + } + if (!validateSpeedLPredictedJointPositionLimits_(q_measured, qdot, dt)) { + return failure(ArmErrorCode::OutOfJointLimit, "predicted joint position limit exceeded"); + } + if (state_.speedl_line_check_active_) { + const Eigen::VectorXd q_predicted = toEigenVector(q_measured) + qdot * dt; + Eigen::Matrix4d predicted_pose_base; + if (!solver_->fk(toStdVector(q_predicted), predicted_pose_base, true)) { + return failure(ArmErrorCode::CommandFailed, "predicted FK failed"); + } + if (!updateAndValidateSpeedLLineDeviation_(predicted_pose_base.block<3, 1>(0, 3), + is_stop_command, + state_.speedl_command_twist_base_.head<3>(), + target_linear_base)) { + return failure(ArmErrorCode::OutOfWorkspace, "predicted line deviation exceeded"); + } + } + + CartesianVelocityStep result; + result.status = Result::success(); + result.stop_reason = state_.adaptive_stop_reason; + result.joint_velocity.velocity = toStdVector(qdot); + result.twist_base = common::math::vectorToVelocity(state_.speedl_command_twist_base_); + result.settled = is_stop_command && !state_.s_curve_planner_.isMoving(); + if (state_.speedl_capture_pending_) { + auto target_base = target_twist; + if (state_.speedl_frame_ == FrameType::Tool) { + target_base.head<3>() = base_R_tool * target_base.head<3>().eval(); + target_base.tail<3>() = base_R_tool * target_base.tail<3>().eval(); + } + result.reference.valid = true; + result.reference.tcp_pose_base = common::math::matrixToPose(tcp_pose_base); + result.reference.target_base = common::math::vectorToVelocity(target_base); + // The reference and all subsequent steps use this captured Base axis. + state_.speedl_target_ = result.reference.target_base; + state_.speedl_frame_ = FrameType::Base; + state_.speedl_capture_pending_ = false; + } + state_.prev_qdot_command_ = result.joint_velocity.velocity; + return result; +} + +bool PinocchioCartesianVelocityPlanner::validateSpeedLJointVelocityCommand_( + const Eigen::VectorXd& qdot, + const Eigen::VectorXd& reference, + const double dt) const +{ + const auto& config = speedl_config_.joint_velocity_check(); + if (!config.enable()) { + return true; + } + if (qdot.size() <= 0 || qdot.size() != reference.size() || + dt <= 0.0 || !std::isfinite(dt)) { + CMVR_LOG(ERROR) << "[PinocchioCartesianVelocityPlanner][speedL] joint velocity check invalid state: qdot_size=" + << qdot.size() << ", reference_size=" << reference.size() + << ", dt=" << dt; + return false; + } + + for (Eigen::Index i = 0; i < qdot.size(); ++i) { + if (!std::isfinite(qdot[i]) || !std::isfinite(reference[i])) { + CMVR_LOG(ERROR) << "[PinocchioCartesianVelocityPlanner][speedL] joint velocity command non-finite: joint_index=" + << i << ", qdot=" << qdot[i] + << ", reference=" << reference[i]; + return false; + } + } + + const double max_velocity = qdot.cwiseAbs().maxCoeff(); + const double max_acceleration = ((qdot - reference) / dt).cwiseAbs().maxCoeff(); + const double velocity_limit = positiveOr(config.max_joint_velocity_rad_s(), 30.0); + const double acceleration_limit = positiveOr(config.max_joint_acceleration_rad_s2(), 10000.0); + if (max_velocity > velocity_limit || max_acceleration > acceleration_limit) { + CMVR_LOG(ERROR) << "[PinocchioCartesianVelocityPlanner][speedL] joint velocity command exceeds threshold: max_joint_velocity_rad_s=" + << max_velocity << ", velocity_limit_rad_s=" << velocity_limit + << ", max_joint_acceleration_rad_s2=" << max_acceleration + << ", acceleration_limit_rad_s2=" << acceleration_limit + << ", dt=" << dt; + return false; + } + return true; +} + +bool PinocchioCartesianVelocityPlanner::validateSpeedLPredictedJointPositionLimits_( + const std::vector& q_measured, + const Eigen::VectorXd& qdot, + const double dt) const +{ + if (!solver_ || !solver_->jointLimitPolicy().limits().enable()) { + return true; + } + if (static_cast(q_measured.size()) != qdot.size()) { + CMVR_LOG(ERROR) << "[PinocchioCartesianVelocityPlanner][speedL] joint position limit check size mismatch: q=" + << q_measured.size() << ", qdot=" << qdot.size(); + return false; + } + + Eigen::VectorXd lower; + Eigen::VectorXd upper; + if (!solver_->getJointPositionLimits(lower, upper) || + lower.size() != qdot.size() || + upper.size() != qdot.size()) { + return true; + } + + std::vector joint_names; + (void)solver_->getChainJointNames(joint_names); + constexpr double kLimitEps = 1e-6; + for (Eigen::Index i = 0; i < qdot.size(); ++i) { + const double q = q_measured[static_cast(i)]; + const double q_next = q + qdot[i] * dt; + const double lo = lower[i]; + const double hi = upper[i]; + if (!std::isfinite(q) || !std::isfinite(q_next) || + !std::isfinite(lo) || !std::isfinite(hi) || hi <= lo) { + continue; + } + + const bool violates_lower = q_next < lo - kLimitEps; + const bool violates_upper = q_next > hi + kLimitEps; + const bool moves_out_lower = q <= lo + kLimitEps && qdot[i] < -kLimitEps; + const bool moves_out_upper = q >= hi - kLimitEps && qdot[i] > kLimitEps; + if (violates_lower || violates_upper || moves_out_lower || moves_out_upper) { + const std::string joint_name = + static_cast(i) < joint_names.size() + ? joint_names[static_cast(i)] + : std::to_string(i); + CMVR_LOG(ERROR) << "[PinocchioCartesianVelocityPlanner][speedL] predicted joint position limit exceeded: joint=" + << joint_name << ", q=" << q + << ", q_next=" << q_next + << ", lower=" << lo + << ", upper=" << hi + << ", qdot=" << qdot[i] + << ", dt=" << dt; + return false; + } + } + return true; +} + +bool PinocchioCartesianVelocityPlanner::validateSpeedLCartesianVelocityFeasibility_( + const Eigen::Matrix& desired_twist, + const Eigen::Matrix& achieved_twist, + const Eigen::VectorXd& q_current, + const Eigen::VectorXd& qdot) const +{ + const auto& config = speedl_config_.cartesian_velocity_feasibility_check(); + if (!config.enable()) { + return true; + } + + const Eigen::Vector3d desired_linear = desired_twist.head<3>(); + const Eigen::Vector3d achieved_linear = achieved_twist.head<3>(); + const double desired_linear_norm = desired_linear.norm(); + const double achieved_linear_norm = achieved_linear.norm(); + const double min_desired_linear_speed = + positiveOr(config.min_desired_linear_speed(), 1e-4); + if (desired_linear_norm >= min_desired_linear_speed) { + const double speed_ratio = achieved_linear_norm / desired_linear_norm; + const double min_ratio = positiveOr(config.min_linear_speed_ratio(), 0.2); + const double deviation_deg = + achieved_linear_norm > 1e-9 + ? directionDeviationDeg(desired_linear, achieved_linear) + : 180.0; + const double max_deviation_deg = + positiveOr(config.max_linear_direction_deviation_deg(), 45.0); + if (speed_ratio < min_ratio || deviation_deg > max_deviation_deg) { + CMVR_LOG(ERROR) << "[PinocchioCartesianVelocityPlanner][speedL] cartesian velocity infeasible after joint limits " << "limit_candidates=[" + << describeJointLimitCandidates_(q_current, qdot) << "]: desired_linear=[" + << desired_linear.transpose() << "], achieved_linear=[" + << achieved_linear.transpose() << "], speed_ratio=" + << speed_ratio << ", min_ratio=" << min_ratio + << ", deviation_deg=" << deviation_deg + << ", max_deviation_deg=" << max_deviation_deg + ; + return false; + } + } + + const Eigen::Vector3d desired_angular = desired_twist.tail<3>(); + const Eigen::Vector3d achieved_angular = achieved_twist.tail<3>(); + const double desired_angular_norm = desired_angular.norm(); + const double achieved_angular_norm = achieved_angular.norm(); + const double min_desired_angular_speed = + positiveOr(config.min_desired_angular_speed(), 1e-4); + if (desired_angular_norm >= min_desired_angular_speed) { + const double speed_ratio = achieved_angular_norm / desired_angular_norm; + const double min_ratio = positiveOr(config.min_angular_speed_ratio(), 0.2); + const double deviation_deg = + achieved_angular_norm > 1e-9 + ? directionDeviationDeg(desired_angular, achieved_angular) + : 180.0; + const double max_deviation_deg = + positiveOr(config.max_angular_direction_deviation_deg(), 45.0); + if (speed_ratio < min_ratio || deviation_deg > max_deviation_deg) { + CMVR_LOG(ERROR) << "[PinocchioCartesianVelocityPlanner][speedL] cartesian angular velocity infeasible after joint limits: desired_angular=[" + << desired_angular.transpose() << "], achieved_angular=[" + << achieved_angular.transpose() << "], speed_ratio=" + << speed_ratio << ", min_ratio=" << min_ratio + << ", deviation_deg=" << deviation_deg + << ", max_deviation_deg=" << max_deviation_deg + << ", limit_candidates=[" + << describeJointLimitCandidates_(q_current, qdot) << "]"; + return false; + } + } + + return true; +} + +std::string PinocchioCartesianVelocityPlanner::describeJointLimitCandidates_( + const Eigen::VectorXd& q_current, + const Eigen::VectorXd& qdot) const +{ + if (!solver_ || q_current.size() != qdot.size()) { + return "none"; + } + + std::vector joint_names; + (void)solver_->getChainJointNames(joint_names); + + Eigen::VectorXd qd_limits; + const bool has_qd_limits = + solver_->getJointVelocityLimits(qd_limits) && qd_limits.size() == qdot.size(); + Eigen::VectorXd lower; + Eigen::VectorXd upper; + const bool has_q_limits = + solver_->getJointPositionLimits(lower, upper) && + lower.size() == q_current.size() && + upper.size() == q_current.size(); + + std::vector candidates; + constexpr double kVelocityRatio = 0.98; + for (Eigen::Index i = 0; i < qdot.size(); ++i) { + const std::string joint_name = + static_cast(i) < joint_names.size() + ? joint_names[static_cast(i)] + : std::to_string(i); + + std::vector reasons; + if (has_qd_limits) { + const double qd_limit = std::abs(qd_limits[i]); + if (std::isfinite(qd_limit) && qd_limit > 0.0 && + std::abs(qdot[i]) >= kVelocityRatio * qd_limit) { + std::ostringstream oss; + oss << "qd=" << qdot[i] << "/" << qd_limit; + reasons.push_back(oss.str()); + } + } + + if (has_q_limits) { + const double q = q_current[i]; + const double lo = lower[i]; + const double hi = upper[i]; + if (std::isfinite(q) && std::isfinite(lo) && std::isfinite(hi) && hi > lo) { + const double margin = std::max(0.02, 0.02 * (hi - lo)); + if (q <= lo + margin) { + std::ostringstream oss; + oss << "near_lower q=" << q << "/" << lo; + reasons.push_back(oss.str()); + } + if (q >= hi - margin) { + std::ostringstream oss; + oss << "near_upper q=" << q << "/" << hi; + reasons.push_back(oss.str()); + } + } + } + + if (!reasons.empty()) { + std::ostringstream item; + item << joint_name << "("; + for (std::size_t j = 0; j < reasons.size(); ++j) { + if (j > 0) { + item << "; "; + } + item << reasons[j]; + } + item << ")"; + candidates.push_back(item.str()); + } + } + + if (candidates.empty()) { + return "none"; + } + std::ostringstream oss; + for (std::size_t i = 0; i < candidates.size(); ++i) { + if (i > 0) { + oss << ", "; + } + oss << candidates[i]; + } + return oss.str(); +} + +bool PinocchioCartesianVelocityPlanner::updateSpeedLLimits_(const SpeedLOptions& options) +{ + const double jerk_max = positiveOr(speedl_config_.linear_jerk_max(), 10.0); + const double requested_jerk = options.linear_jerk.value_or(jerk_max); + // Validate before clamping: invalid requests must not become valid limits. + if (!speedl_configured_ || !std::isfinite(options.acceleration) || options.acceleration <= 0.0 || + !std::isfinite(requested_jerk) || requested_jerk <= 0.0) { + return false; + } + const double acceleration = std::min(options.acceleration, + positiveOr(speedl_config_.linear_acceleration_max(), 5.0)); + const double angular_acceleration = std::min(options.acceleration, + positiveOr(speedl_config_.angular_acceleration_max(), 5.0)); + const double jerk = std::min(requested_jerk, jerk_max); + const bool continuous = options.continuous_linear_reversal.value_or( + !speedl_config_.has_continuous_linear_reversal() || speedl_config_.continuous_linear_reversal()); + if (std::abs(state_.speedl_applied_acceleration_ - acceleration) <= 1e-9 && + std::abs(state_.speedl_applied_angular_acceleration_ - angular_acceleration) <= 1e-9 && + std::abs(state_.speedl_applied_linear_jerk_ - jerk) <= 1e-9) { + state_.s_curve_planner_.setContinuousLinearReversal(continuous); + return true; + } + + // Commit both sets of limits and the policy together. A rejected update + // must leave the previous command and its entire future profile intact. + auto candidate = state_.s_curve_planner_; + candidate.setLinearConstraints( + positiveOr(speedl_config_.linear_velocity_max(), .55), + acceleration, jerk); + candidate.setAngularConstraints( + positiveOr(speedl_config_.angular_velocity_max(), 1.0), + angular_acceleration, positiveOr(speedl_config_.angular_jerk_max(), 12.0)); + candidate.setContinuousLinearReversal(continuous); + state_.s_curve_planner_ = std::move(candidate); + state_.speedl_applied_acceleration_ = acceleration; + state_.speedl_applied_angular_acceleration_ = angular_acceleration; + state_.speedl_applied_linear_jerk_ = jerk; + return true; +} + +Result PinocchioCartesianVelocityPlanner::submit( + const CartesianVelocity& target, const SpeedLOptions& options, const FrameType frame) +{ + pending_.reset(); + if (!speedl_configured_) { + return Result::failure(ArmErrorCode::RobotNotReady, "velocity planner is not configured"); + } + if (!state_.adaptive_stop_reason.ok()) { + return Result::failure(ArmErrorCode::RobotNotReady, + "adaptive speed stop is in progress; reset before submitting another command"); + } + if ((frame != FrameType::Base && frame != FrameType::Tool) || + !std::isfinite(common::math::velocityToVector(target).norm())) { + return Result::failure(ArmErrorCode::InvalidArgument, "invalid velocity target or frame"); + } + try { + if (!updateSpeedLLimits_(options)) { + return Result::failure(ArmErrorCode::InvalidArgument, "invalid velocity planning limits"); + } + } catch (const std::invalid_argument& error) { + return Result::failure(ArmErrorCode::InvalidArgument, error.what()); + } catch (const std::runtime_error& error) { + return Result::failure(ArmErrorCode::CommandFailed, error.what()); + } + state_.speedl_target_ = target; + state_.speedl_frame_ = frame; + state_.speedl_capture_pending_ = options.capture_reference; + state_.speedl_command_ready_ = true; + return Result::success(); +} + +} // namespace cmvr::device diff --git a/cmvr-es/algorithms/planner/cartesian/pinocchio/test/pinocchio_speedl_limits_test.cpp b/cmvr-es/algorithms/planner/cartesian/pinocchio/test/pinocchio_speedl_limits_test.cpp new file mode 100644 index 00000000..20600678 --- /dev/null +++ b/cmvr-es/algorithms/planner/cartesian/pinocchio/test/pinocchio_speedl_limits_test.cpp @@ -0,0 +1,1161 @@ +#include + +#include +#include +#include +#include +#include + +#include "algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_dls_ik_solver.h" +#include "algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_qp_ik_solver.h" +#include "algorithms/planner/cartesian/pinocchio/include/pinocchio_cartesian_velocity_planner.h" +#include "common/io/proto_file_io.h" +#include "common/math/transform_math.h" + +namespace cmvr::device { +namespace { +constexpr double kDt = .001; +using Twist = Eigen::Matrix; + +// A successful planner candidate becomes the executed state only after the +// controller accepts it. These pure planner tests model successful submission. +CartesianVelocityStep stepAndCommit(PinocchioCartesianVelocityPlanner& planner, + double dt, const std::vector& q, + const std::vector& qd, double scaling = 1) +{ + auto result = planner.step(dt, q, qd, scaling); + if (result.status.ok()) planner.commitStep(); + return result; +} + +// Exercise the production planner and real URDF kinematics, without motor I/O. +class PinocchioSpeedLLimits : public ::testing::Test { +protected: + void SetUp() override { + const auto root = std::filesystem::path(CMVR_TEST_SOURCE_DIR); + config::ArmRootConfig arms; + ASSERT_TRUE(ProtoMessageIo::getProtoFromAsciiFile( + (root / "cmvr-es/config/devices/arm/arm.pb.txt").string(), &arms)); + ASSERT_GT(arms.arm().robot_arms_size(), 0); + auto ik = arms.arm().robot_arms(0).kinematics().pinocchio_dls_ik_solver(); + ik.set_urdf_path((root / "model/xiaoyan_description/dual_arm.urdf").string()); + solver_ = std::make_shared(ik); + ASSERT_TRUE(solver_->init()); + planner_ = std::make_unique(solver_); + limits_.set_linear_velocity_max(.2); + limits_.set_linear_acceleration_max(.4); + limits_.set_linear_jerk_max(2); + limits_.set_angular_velocity_max(1); + limits_.set_angular_acceleration_max(.8); + limits_.set_angular_jerk_max(4); + limits_.set_enforce_joint_acceleration_limits(false); + ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size())); + last_twist_.setZero(); + } + + struct Peaks { double velocity{0}, acceleration{0}, jerk{0}; }; + Peaks sample(const CartesianVelocity& target, const SpeedLOptions& options, + bool angular = false, int steps = 2200) { + Peaks peaks; + const auto submitted = planner_->submit(target, options, FrameType::Base); + if (!submitted.ok()) { + ADD_FAILURE() << submitted.message; + return peaks; + } + Twist previous = last_twist_; + Twist previous_acceleration = Twist::Zero(); + for (int i = 0; i < steps; ++i) { + const auto result = stepAndCommit(*planner_, kDt, q_, qd_); + if (!result.status.ok()) { + ADD_FAILURE() << "Planning failed at sample " << i << ": " << result.status.message; + break; + } + const Twist velocity = common::math::velocityToVector(result.twist_base); + const Twist acceleration = (velocity - previous) / kDt; + const Twist jerk = (acceleration - previous_acceleration) / kDt; + const int offset = angular ? 3 : 0; + peaks.velocity = std::max(peaks.velocity, velocity.segment<3>(offset).norm()); + peaks.acceleration = std::max(peaks.acceleration, acceleration.segment<3>(offset).norm()); + peaks.jerk = std::max(peaks.jerk, jerk.segment<3>(offset).norm()); + previous = velocity; + previous_acceleration = acceleration; + last_twist_ = velocity; + } + return peaks; + } + + void expectPeaks(const Peaks& p, double velocity, double acceleration, double jerk) { + // These trajectories contain plateaus: limits must be reached, as well + // as obeyed, so an unintended smaller cap cannot pass the test. + EXPECT_NEAR(p.velocity, velocity, 1e-8); + EXPECT_NEAR(p.acceleration, acceleration, 1e-8); + EXPECT_NEAR(p.jerk, jerk, 1e-6); + } + + std::shared_ptr solver_; + std::unique_ptr planner_; + config::SpeedLPlannerConfig limits_; + const std::vector q_{.25, 1, M_PI / 2, M_PI / 2, -M_PI / 2, 0, 0}; + const std::vector qd_ = std::vector(7, 0); + Twist last_twist_{Twist::Zero()}; +}; + +TEST_F(PinocchioSpeedLLimits, ExcessiveRequestsRespectAllLinearLimits) { + SpeedLOptions options; + options.acceleration = 60; + options.linear_jerk = 60; + CartesianVelocity target; + target.vx = .6; + target.vy = .8; + expectPeaks(sample(target, options), .2, .4, 2); +} + +TEST_F(PinocchioSpeedLLimits, LowerRequestsRemainEffective) { + SpeedLOptions options; + options.acceleration = .15; + options.linear_jerk = .8; + CartesianVelocity target; + target.vy = 1; + expectPeaks(sample(target, options), .2, .15, .8); +} + +TEST_F(PinocchioSpeedLLimits, OmittedJerkRestoresArmLimit) { + SpeedLOptions options; + options.acceleration = .4; + options.linear_jerk = .3; + ASSERT_TRUE(planner_->submit({}, options, FrameType::Base).ok()); + options.linear_jerk.reset(); + CartesianVelocity target; + target.vy = 1; + expectPeaks(sample(target, options), .2, .4, 2); +} + +TEST_F(PinocchioSpeedLLimits, AccelerationOnlyRequestsAndStopAreCapped) { + SpeedLOptions options; + options.acceleration = 60; + CartesianVelocity target; + target.vy = 1; + expectPeaks(sample(target, options, false, 1200), .2, .4, 2); + const auto stop = sample({}, options, false, 1200); + EXPECT_LE(stop.velocity, .2); + EXPECT_NEAR(stop.acceleration, .4, 1e-8); + EXPECT_NEAR(stop.jerk, 2, 1e-6); + EXPECT_NEAR(last_twist_[1], 0, 1e-12); +} + +TEST_F(PinocchioSpeedLLimits, AngularAccelerationHasItsOwnCapAndCache) { + limits_.set_linear_acceleration_max(.2); + ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size())); + last_twist_.setZero(); + SpeedLOptions options; + options.acceleration = .3; + ASSERT_TRUE(planner_->submit({}, options, FrameType::Base).ok()); + // Linear effective acceleration stays at .2, but angular must change. + options.acceleration = .6; + CartesianVelocity target; + target.wy = 2; + expectPeaks(sample(target, options, true), 1, .6, 4); + ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size())); + last_twist_.setZero(); + options.acceleration = 60; + expectPeaks(sample(target, options, true), 1, .8, 4); +} + +TEST_F(PinocchioSpeedLLimits, InvalidRequestsAreRejectedBeforeClamping) { + for (double invalid : {0.0, -1.0, 1e-12, std::numeric_limits::infinity(), + std::numeric_limits::quiet_NaN()}) { + SpeedLOptions options; + options.acceleration = invalid; + EXPECT_FALSE(planner_->submit({}, options, FrameType::Base).ok()); + options.acceleration = .3; + options.linear_jerk = invalid; + EXPECT_FALSE(planner_->submit({}, options, FrameType::Base).ok()); + } +} + +TEST_F(PinocchioSpeedLLimits, IncompatibleLimitsRejectStopWithoutChangingPreviousCommand) { + limits_.set_linear_velocity_max(1); + limits_.set_linear_acceleration_max(3); + limits_.set_linear_jerk_max(10); + ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size())); + CartesianVelocity target; + target.vy = .8; + SpeedLOptions options; + options.acceleration = 3; + options.linear_jerk = 10; + ASSERT_TRUE(planner_->submit(target, options, FrameType::Base).ok()); + for (int i = 0; i < 100; ++i) ASSERT_TRUE(stepAndCommit(*planner_, kDt, q_, qd_).status.ok()); + + // Current a=1: lowering a to .1 would jump; jerk=.01 cannot remove + // acceleration before exceeding the velocity bound. Both must reject. + for (bool lower_jerk : {false, true}) { + auto candidate = *planner_; + auto reference = *planner_; + auto invalid_options = options; + if (lower_jerk) invalid_options.linear_jerk = .01; + else invalid_options.acceleration = .1; + const auto rejected = candidate.submit({}, invalid_options, FrameType::Base); + EXPECT_FALSE(rejected.ok()); + EXPECT_FALSE(rejected.message.empty()); + for (int i = 0; i < 100; ++i) { + const auto actual = stepAndCommit(candidate, kDt, q_, qd_); + const auto expected = stepAndCommit(reference, kDt, q_, qd_); + ASSERT_TRUE(actual.status.ok()) << actual.status.message; + ASSERT_TRUE(expected.status.ok()) << expected.status.message; + EXPECT_EQ(actual.joint_velocity.velocity, expected.joint_velocity.velocity); + } + // The rejected request must not poison a subsequent stop at valid limits. + ASSERT_TRUE(candidate.submit({}, options, FrameType::Base).ok()); + CartesianVelocityStep stopped; + for (int i = 0; i < 1200; ++i) { + stopped = stepAndCommit(candidate, kDt, q_, qd_); + ASSERT_TRUE(stopped.status.ok()) << stopped.status.message; + } + EXPECT_NEAR(common::math::velocityToVector(stopped.twist_base).norm(), 0, 1e-10); + } +} + +TEST_F(PinocchioSpeedLLimits, RejectedAngularLimitDoesNotPartiallyApplyLinearLimitOrPolicy) { + limits_.set_linear_acceleration_max(3); + limits_.set_angular_acceleration_max(3); + limits_.set_angular_jerk_max(10); + ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size())); + CartesianVelocity target; + target.vy = .1; + target.wy = .8; + SpeedLOptions options; + options.acceleration = 3; + ASSERT_TRUE(planner_->submit(target, options, FrameType::Base).ok()); + for (int i = 0; i < 100; ++i) ASSERT_TRUE(stepAndCommit(*planner_, kDt, q_, qd_).status.ok()); + auto reference = *planner_; + options.acceleration = .5; // Linear a=.2 fits; angular a=1 does not. + options.continuous_linear_reversal = false; + EXPECT_FALSE(planner_->submit({}, options, FrameType::Base).ok()); + for (int i = 0; i < 200; ++i) { + const auto actual = stepAndCommit(*planner_, kDt, q_, qd_); + const auto expected = stepAndCommit(reference, kDt, q_, qd_); + ASSERT_TRUE(actual.status.ok()) << actual.status.message; + ASSERT_TRUE(expected.status.ok()) << expected.status.message; + EXPECT_EQ(actual.joint_velocity.velocity, expected.joint_velocity.velocity); + } +} + +TEST_F(PinocchioSpeedLLimits, InvalidConfigurationKeepsPreviousCommand) { + CartesianVelocity target; + target.vy = .1; + SpeedLOptions options; + options.acceleration = .3; + ASSERT_TRUE(planner_->submit(target, options, FrameType::Base).ok()); + ASSERT_TRUE(stepAndCommit(*planner_, kDt, q_, qd_).status.ok()); + auto reference = *planner_; + using Config = config::SpeedLPlannerConfig; + for (auto setter : {&Config::set_linear_velocity_max, &Config::set_linear_acceleration_max, + &Config::set_linear_jerk_max, &Config::set_angular_velocity_max, + &Config::set_angular_acceleration_max, &Config::set_angular_jerk_max, + &Config::set_linear_target_replan_threshold, + &Config::set_angular_target_replan_threshold}) { + for (double invalid : {-1.0, std::numeric_limits::infinity(), + std::numeric_limits::quiet_NaN()}) { + auto invalid_config = limits_; + (invalid_config.*setter)(invalid); + EXPECT_FALSE(planner_->configureSpeedL(invalid_config, q_.size())); + const auto actual = stepAndCommit(*planner_, kDt, q_, qd_); + const auto expected = stepAndCommit(reference, kDt, q_, qd_); + ASSERT_TRUE(actual.status.ok()) << actual.status.message; + ASSERT_TRUE(expected.status.ok()) << expected.status.message; + EXPECT_EQ(actual.joint_velocity.velocity, expected.joint_velocity.velocity); + EXPECT_DOUBLE_EQ((common::math::velocityToVector(actual.twist_base) - + common::math::velocityToVector(expected.twist_base)).norm(), 0); + } + } + for (double invalid : {-1.0, std::numeric_limits::infinity(), + std::numeric_limits::quiet_NaN()}) { + auto invalid_config = limits_; + invalid_config.mutable_adaptive_speed()->set_enable(true); + invalid_config.mutable_adaptive_speed()->set_lookahead_s(invalid); + EXPECT_FALSE(planner_->configureSpeedL(invalid_config, q_.size())); + const auto actual = stepAndCommit(*planner_, kDt, q_, qd_); + const auto expected = stepAndCommit(reference, kDt, q_, qd_); + ASSERT_TRUE(actual.status.ok()) << actual.status.message; + ASSERT_TRUE(expected.status.ok()) << expected.status.message; + EXPECT_EQ(actual.joint_velocity.velocity, expected.joint_velocity.velocity); + } + for (double invalid : {-1.0, 1.01, std::numeric_limits::infinity(), + std::numeric_limits::quiet_NaN()}) { + auto invalid_config = limits_; + invalid_config.mutable_adaptive_speed()->set_enable(true); + invalid_config.mutable_adaptive_speed()->set_min_speed_ratio(invalid); + EXPECT_FALSE(planner_->configureSpeedL(invalid_config, q_.size())); + const auto actual = stepAndCommit(*planner_, kDt, q_, qd_); + const auto expected = stepAndCommit(reference, kDt, q_, qd_); + ASSERT_TRUE(actual.status.ok()) << actual.status.message; + ASSERT_TRUE(expected.status.ok()) << expected.status.message; + EXPECT_EQ(actual.joint_velocity.velocity, expected.joint_velocity.velocity); + } + // Unspecified protobuf scalars remain zero and select the existing defaults. + EXPECT_TRUE(planner_->configureSpeedL(Config{}, q_.size())); +} + +TEST_F(PinocchioSpeedLLimits, StreamingNearZeroMotionKeepsProfileAndAcceleration) { + SpeedLOptions options; + options.acceleration = .3; + options.linear_jerk = .01; + options.continuous_linear_reversal = false; + CartesianVelocity target; + target.vy = .02; + ASSERT_TRUE(planner_->submit(target, options, FrameType::Base).ok()); + for (int i = 1; i <= 200; ++i) { + const auto result = stepAndCommit(*planner_, kDt, q_, qd_); + ASSERT_TRUE(result.status.ok()) << result.status.message; + const double time = i * kDt; + EXPECT_NEAR(result.twist_base.vy, .5 * *options.linear_jerk * time * time, 1e-12); + } + + // Change axis below the former reset threshold while acceleration is + // nonzero. The transition must preserve it, rather than restart from rest. + ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size())); + ASSERT_TRUE(planner_->submit(target, options, FrameType::Base).ok()); + const auto first = stepAndCommit(*planner_, kDt, q_, qd_); + ASSERT_TRUE(first.status.ok()) << first.status.message; + ASSERT_GT(first.twist_base.vy, 0); + ASSERT_LT(first.twist_base.vy, 1e-6); + target.vy = 0; + target.vx = .02; + ASSERT_TRUE(planner_->submit(target, options, FrameType::Base).ok()); + const auto switching = stepAndCommit(*planner_, kDt, q_, qd_); + ASSERT_TRUE(switching.status.ok()) << switching.status.message; + EXPECT_GT(switching.twist_base.vy, first.twist_base.vy); + const Twist first_v = common::math::velocityToVector(first.twist_base); + const Twist next_v = common::math::velocityToVector(switching.twist_base); + EXPECT_LE(((next_v - 2 * first_v) / (kDt * kDt)).head<3>().norm(), + *options.linear_jerk + 1e-7); +} + +TEST_F(PinocchioSpeedLLimits, StreamingDirectionChangesRespectAccelerationAndJerk) { + for (const double jerk : {10.0, 30.0}) { + SCOPED_TRACE(jerk); + limits_.set_continuous_linear_reversal(true); + limits_.set_linear_acceleration_max(5); + limits_.set_linear_jerk_max(jerk); + ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size())); + last_twist_.setZero(); + SpeedLOptions options; + options.acceleration = .5; + CartesianVelocity target; + target.vy = .02; + sample(target, options, false, 300); + ASSERT_NEAR(last_twist_[1], .02, 1e-10); + + // Same acceleration/jerk: the policy override must bypass their cache. + options.continuous_linear_reversal = false; + double min_speed = .02; + double max_error = 0; + Twist previous = last_twist_; + Twist previous_acceleration = Twist::Zero(); + for (int i = 0; i < 2000; ++i) { + const double angle = (i / 20) * .01; + target.vx = .02 * std::sin(angle); + target.vy = .02 * std::cos(angle); + ASSERT_TRUE(planner_->submit(target, options, FrameType::Base).ok()); + const auto result = stepAndCommit(*planner_, kDt, q_, qd_); + ASSERT_TRUE(result.status.ok()) << result.status.message; + const Twist actual = common::math::velocityToVector(result.twist_base); + const Twist acceleration = (actual - previous) / kDt; + const Twist discrete_jerk = (acceleration - previous_acceleration) / kDt; + EXPECT_LE(acceleration.head<3>().norm(), options.acceleration + 1e-7); + EXPECT_LE(discrete_jerk.head<3>().norm(), jerk + 1e-5); + previous = actual; + previous_acceleration = acceleration; + last_twist_ = actual; + min_speed = std::min(min_speed, actual.head<3>().norm()); + max_error = std::max(max_error, (actual - common::math::velocityToVector(target)).norm()); + } + EXPECT_GT(min_speed, .019); // Smooth tracking may lag; it must not stop periodically. + EXPECT_LT(max_error, .002); + // Once the target stops changing, converge to its exact direction. + sample(target, options, false, 300); + EXPECT_NEAR((last_twist_ - common::math::velocityToVector(target)).norm(), 0, 1e-10); + } +} + +TEST_F(PinocchioSpeedLLimits, ContactReversalStillCrossesZeroAfterStreamingAlignment) { + limits_.set_linear_acceleration_max(1); + limits_.set_linear_jerk_max(4); + ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size())); + last_twist_.setZero(); + SpeedLOptions options; + options.acceleration = 1; + options.continuous_linear_reversal = false; + CartesianVelocity target; + target.vy = .02; + sample(target, options, false, 300); + ASSERT_NEAR(last_twist_[1], .02, 1e-10); + + options.continuous_linear_reversal = true; + target.vy = -.02; + ASSERT_TRUE(planner_->submit(target, options, FrameType::Base).ok()); + for (int i = 0; i < 100; ++i) { + const auto result = stepAndCommit(*planner_, kDt, q_, qd_); + ASSERT_TRUE(result.status.ok()) << result.status.message; + last_twist_ = common::math::velocityToVector(result.twist_base); + } + EXPECT_NEAR(last_twist_[1], 0, 1e-10); + const auto result = stepAndCommit(*planner_, kDt, q_, qd_); + ASSERT_TRUE(result.status.ok()) << result.status.message; + EXPECT_LT(result.twist_base.vy, -.0003); +} +TEST_F(PinocchioSpeedLLimits, StepRequiresCommandAndNeverReturnsOldOutputOnFailure) { + auto expect_empty_failure = [](const CartesianVelocityStep& result) { + EXPECT_FALSE(result.status.ok()); + EXPECT_FALSE(result.status.message.empty()); + EXPECT_TRUE(result.joint_velocity.velocity.empty()); + EXPECT_DOUBLE_EQ(common::math::velocityToVector(result.twist_base).norm(), 0); + EXPECT_FALSE(result.reference.valid); + }; + const auto unsubmitted = stepAndCommit(*planner_, kDt, q_, qd_); + EXPECT_EQ(unsubmitted.status.code, ArmErrorCode::RobotNotReady); + expect_empty_failure(unsubmitted); + + CartesianVelocity target; + target.vy = .02; + SpeedLOptions options; + options.capture_reference = true; + ASSERT_TRUE(planner_->submit(target, options, FrameType::Base).ok()); + const auto valid = stepAndCommit(*planner_, kDt, q_, qd_); + ASSERT_TRUE(valid.status.ok()) << valid.status.message; + ASSERT_EQ(valid.joint_velocity.velocity.size(), q_.size()); + ASSERT_GT(valid.twist_base.vy, 0); + ASSERT_TRUE(valid.reference.valid); + for (double dt : {0.0, -kDt, std::numeric_limits::infinity(), + std::numeric_limits::quiet_NaN()}) { + SCOPED_TRACE(dt); + expect_empty_failure(stepAndCommit(*planner_, dt, q_, qd_)); + } + expect_empty_failure(stepAndCommit(*planner_, kDt, {}, qd_)); + expect_empty_failure(stepAndCommit(*planner_, kDt, q_, {})); +} + +TEST_F(PinocchioSpeedLLimits, OnlyCommittedSuccessfulStepsAdvanceProfileAndReference) { + CartesianVelocity target; + target.vy = .1; + SpeedLOptions options; + options.acceleration = .4; + options.capture_reference = true; + ASSERT_TRUE(planner_->submit(target, options, FrameType::Tool).ok()); + const auto first = planner_->step(kDt, q_, qd_); + const auto uncommitted = planner_->step(kDt, q_, qd_); + ASSERT_TRUE(first.status.ok()) << first.status.message; + ASSERT_TRUE(uncommitted.status.ok()) << uncommitted.status.message; + EXPECT_EQ(first.joint_velocity.velocity, uncommitted.joint_velocity.velocity); + EXPECT_TRUE(first.reference.valid); + EXPECT_TRUE(uncommitted.reference.valid); + planner_->commitStep(); + + const auto second = planner_->step(kDt, q_, qd_); + ASSERT_TRUE(second.status.ok()) << second.status.message; + EXPECT_FALSE(second.reference.valid); + EXPECT_GT(common::math::velocityToVector(second.twist_base).norm(), + common::math::velocityToVector(first.twist_base).norm()); + // An invalid request must discard the pending second command. In + // particular, accidentally committing after failure cannot advance it. + EXPECT_FALSE(planner_->step(0, q_, qd_).status.ok()); + planner_->commitStep(); + const auto retried = planner_->step(kDt, q_, qd_); + ASSERT_TRUE(retried.status.ok()) << retried.status.message; + EXPECT_EQ(retried.joint_velocity.velocity, second.joint_velocity.velocity); +} + +TEST_F(PinocchioSpeedLLimits, ToolReferenceUsesFirstStepPoseAndKeepsBaseDirection) { + CartesianVelocity target; + target.vx = .03; + SpeedLOptions options; + options.capture_reference = true; + ASSERT_TRUE(planner_->submit(target, options, FrameType::Tool).ok()); + auto first_q = q_; + first_q[0] += .1; + Eigen::Matrix4d pose; + ASSERT_TRUE(solver_->fk(first_q, pose, true)); + const Eigen::Vector3d expected_base = pose.block<3, 3>(0, 0) * Eigen::Vector3d(.03, 0, 0); + const auto first = stepAndCommit(*planner_, kDt, first_q, qd_); + ASSERT_TRUE(first.status.ok()) << first.status.message; + ASSERT_TRUE(first.reference.valid); + EXPECT_NEAR(first.reference.tcp_pose_base.x, pose(0, 3), 1e-12); + EXPECT_NEAR(first.reference.tcp_pose_base.y, pose(1, 3), 1e-12); + EXPECT_NEAR(first.reference.tcp_pose_base.z, pose(2, 3), 1e-12); + EXPECT_NEAR((common::math::velocityToVector(first.reference.target_base).head<3>() - expected_base).norm(), + 0, 1e-12); + PinocchioCartesianVelocityPlanner base_planner(solver_); + ASSERT_TRUE(base_planner.configureSpeedL(limits_, q_.size())); + options.capture_reference = false; + ASSERT_TRUE(base_planner.submit(first.reference.target_base, options, FrameType::Base).ok()); + ASSERT_TRUE(stepAndCommit(base_planner, kDt, first_q, qd_).status.ok()); + auto later_q = first_q; + later_q[0] += .2; + Eigen::Matrix4d later_pose; + ASSERT_TRUE(solver_->fk(later_q, later_pose, true)); + // Ensure the changed pose would produce a different Base direction if + // Tool conversion were incorrectly repeated after capturing the reference. + EXPECT_GT((later_pose.block<3, 3>(0, 0) * Eigen::Vector3d(.03, 0, 0) - expected_base).norm(), 1e-5); + // Compare long enough that the limiter's own transient axis lock cannot + // hide accidental Tool-frame reconversion on later control cycles. + for (int i = 0; i < 300; ++i) { + const auto later = stepAndCommit(*planner_, kDt, later_q, qd_); + const auto base = stepAndCommit(base_planner, kDt, later_q, qd_); + ASSERT_TRUE(later.status.ok()) << later.status.message; + ASSERT_TRUE(base.status.ok()) << base.status.message; + EXPECT_FALSE(later.reference.valid); + EXPECT_NEAR((common::math::velocityToVector(later.twist_base) - + common::math::velocityToVector(base.twist_base)).norm(), 0, 1e-10); + } +} + +TEST_F(PinocchioSpeedLLimits, StopSettlesProfileBeforeRestartingOnAnotherAxis) { + limits_.set_linear_acceleration_max(.5); + limits_.set_linear_jerk_max(10); + ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size())); + SpeedLOptions options; + options.acceleration = .5; + options.linear_jerk = 10; + CartesianVelocity target; + target.vx = .05; + ASSERT_TRUE(planner_->submit(target, options, FrameType::Base).ok()); + for (int i = 0; i < 800; ++i) { + const auto step = stepAndCommit(*planner_, kDt, q_, qd_); + ASSERT_TRUE(step.status.ok()) << step.status.message; + EXPECT_FALSE(step.settled); + } + + ASSERT_TRUE(planner_->submit({}, options, FrameType::Base).ok()); + bool small_command_before_settled = false; + CartesianVelocityStep stopped; + for (int i = 0; i < 500; ++i) { + stopped = stepAndCommit(*planner_, kDt, q_, qd_); + ASSERT_TRUE(stopped.status.ok()) << stopped.status.message; + double squared_speed = 0; + for (double velocity : stopped.joint_velocity.velocity) squared_speed += velocity * velocity; + if (std::sqrt(squared_speed) < 1e-3 && !stopped.settled) { + small_command_before_settled = true; + } + if (stopped.settled) break; + } + EXPECT_TRUE(small_command_before_settled); + ASSERT_TRUE(stopped.settled); + EXPECT_DOUBLE_EQ(common::math::velocityToVector(stopped.twist_base).norm(), 0); + + PinocchioCartesianVelocityPlanner fresh(solver_); + ASSERT_TRUE(fresh.configureSpeedL(limits_, q_.size())); + target.vx = 0; + target.vy = .05; + ASSERT_TRUE(planner_->submit(target, options, FrameType::Base).ok()); + ASSERT_TRUE(fresh.submit(target, options, FrameType::Base).ok()); + for (int i = 0; i < 300; ++i) { + const auto restarted = stepAndCommit(*planner_, kDt, q_, qd_); + const auto expected = stepAndCommit(fresh, kDt, q_, qd_); + ASSERT_TRUE(restarted.status.ok()) << restarted.status.message; + ASSERT_TRUE(expected.status.ok()) << expected.status.message; + EXPECT_EQ(restarted.joint_velocity.velocity, expected.joint_velocity.velocity); + EXPECT_DOUBLE_EQ((common::math::velocityToVector(restarted.twist_base) - + common::math::velocityToVector(expected.twist_base)).norm(), 0); + } +} + +TEST_F(PinocchioSpeedLLimits, ContinuousTurnFinishesLineAlignmentWithoutDisablingDriftCheck) { + limits_.set_linear_acceleration_max(.5); + limits_.set_linear_jerk_max(10); + auto* line = limits_.mutable_line_deviation_check(); + line->set_enable(true); + line->set_line_deviation_stop_m(.005); + line->set_line_direction_reset_deg(10); + line->set_line_check_min_distance_m(.01); + SpeedLOptions options; + options.acceleration = .5; + options.linear_jerk = 10; + options.continuous_linear_reversal = true; + + for (FrameType frame : {FrameType::Base, FrameType::Tool}) { + SCOPED_TRACE(static_cast(frame)); + ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size())); + auto q = q_; + auto qd = qd_; + // Follow real velocity IK with FK feedback, including the curved + // transition from +X to +Y. Resubmission must not erase the reference. + for (int i = 0; i < 2600; ++i) { + Twist target = Twist::Zero(); + target[i < 800 ? 0 : 1] = .05; + if (frame == FrameType::Tool) { + Eigen::Matrix4d pose; + ASSERT_TRUE(solver_->fk(q, pose, true)); + target.head<3>() = pose.block<3, 3>(0, 0).transpose() * target.head<3>().eval(); + } + ASSERT_TRUE(planner_->submit(common::math::vectorToVelocity(target), options, frame).ok()); + const auto step = stepAndCommit(*planner_, kDt, q, qd); + ASSERT_TRUE(step.status.ok()) << "sample=" << i << ": " << step.status.message; + qd = step.joint_velocity.velocity; + for (std::size_t joint = 0; joint < q.size(); ++joint) q[joint] += qd[joint] * kDt; + } + + // Introduce a measured 8 mm cross-track disturbance after steady +Y + // travel. The unchanged Base target must still trigger the 5 mm guard. + Eigen::Matrix4d before; + ASSERT_TRUE(solver_->fk(q, before, true)); + auto disturbed_pose = before; + disturbed_pose(0, 3) += .008; + solver_->update_joints_state(q); + ASSERT_TRUE(solver_->ik(disturbed_pose, q, true)); + Eigen::Matrix4d measured; + ASSERT_TRUE(solver_->fk(q, measured, true)); + ASSERT_GT(measured(0, 3) - before(0, 3), .007); + Twist target = Twist::Zero(); + target[1] = .05; + if (frame == FrameType::Tool) { + target.head<3>() = measured.block<3, 3>(0, 0).transpose() * target.head<3>().eval(); + } + ASSERT_TRUE(planner_->submit(common::math::vectorToVelocity(target), options, frame).ok()); + const auto rejected = stepAndCommit(*planner_, kDt, q, qd); + EXPECT_EQ(rejected.status.code, ArmErrorCode::OutOfWorkspace) << rejected.status.message; + EXPECT_TRUE(rejected.joint_velocity.velocity.empty()); + } +} + +TEST_F(PinocchioSpeedLLimits, ResetDiscardsInterruptedProfileAndRequiresNewCommand) { + CartesianVelocity target; + target.vy = .15; + SpeedLOptions options; + options.acceleration = .4; + options.capture_reference = true; + ASSERT_TRUE(planner_->submit(target, options, FrameType::Tool).ok()); + for (int i = 0; i < 100; ++i) ASSERT_TRUE(stepAndCommit(*planner_, kDt, q_, qd_).status.ok()); + // Simulate an external hard stop while the S-curve still has acceleration. + ASSERT_TRUE(planner_->reset(q_, qd_).ok()); + EXPECT_EQ(stepAndCommit(*planner_, kDt, q_, qd_).status.code, ArmErrorCode::RobotNotReady); + + PinocchioCartesianVelocityPlanner fresh(solver_); + ASSERT_TRUE(fresh.configureSpeedL(limits_, q_.size())); + ASSERT_TRUE(fresh.reset(q_, qd_).ok()); + target.vy = 0; + target.vx = .1; + options.capture_reference = false; + ASSERT_TRUE(planner_->submit(target, options, FrameType::Base).ok()); + ASSERT_TRUE(fresh.submit(target, options, FrameType::Base).ok()); + for (int i = 0; i < 300; ++i) { + const auto restarted = stepAndCommit(*planner_, kDt, q_, qd_); + const auto expected = stepAndCommit(fresh, kDt, q_, qd_); + ASSERT_TRUE(restarted.status.ok()) << restarted.status.message; + ASSERT_TRUE(expected.status.ok()) << expected.status.message; + EXPECT_FALSE(restarted.reference.valid); + EXPECT_EQ(restarted.joint_velocity.velocity, expected.joint_velocity.velocity); + EXPECT_DOUBLE_EQ((common::math::velocityToVector(restarted.twist_base) - + common::math::velocityToVector(expected.twist_base)).norm(), 0); + } +} + +TEST_F(PinocchioSpeedLLimits, ResetUsesMeasuredTwistAndJointVelocity) { + limits_.set_enforce_joint_acceleration_limits(true); + ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size())); + auto measured_qd = qd_; + measured_qd[0] = .05; + Eigen::Matrix4d pose; + Eigen::MatrixXd jacobian; + Eigen::Matrix3d rotation; + ASSERT_TRUE(solver_->computePoseAndJacobianBaseAtQ(q_, true, pose, jacobian, rotation)); + const Twist measured_twist = jacobian * Eigen::Map(measured_qd.data(), measured_qd.size()); + ASSERT_TRUE(planner_->reset(q_, measured_qd).ok()); + SpeedLOptions options; + options.acceleration = .4; + ASSERT_TRUE(planner_->submit(common::math::vectorToVelocity(measured_twist), options, + FrameType::Base).ok()); + const auto result = stepAndCommit(*planner_, kDt, q_, measured_qd); + ASSERT_TRUE(result.status.ok()) << result.status.message; + EXPECT_NEAR((common::math::velocityToVector(result.twist_base) - measured_twist).norm(), 0, 1e-12); + // A zero reset baseline would clip this below .01 rad/s on the first cycle. + EXPECT_GT(result.joint_velocity.velocity[0], .03); +} + +TEST_F(PinocchioSpeedLLimits, ScalingPreservesBoundsAndCapturedToolReferenceThroughPause) { + SpeedLOptions options; + options.acceleration = .8; + options.capture_reference = true; + CartesianVelocity target; + target.vx = 1; // Clamp to the arm limits before applying the speed ratio. + target.wy = 2; + ASSERT_TRUE(planner_->submit(target, options, FrameType::Tool).ok()); + Eigen::Matrix4d pose; + ASSERT_TRUE(solver_->fk(q_, pose, true)); + Twist capped_base = Twist::Zero(); + capped_base.head<3>() = pose.block<3, 3>(0, 0) * Eigen::Vector3d(.2, 0, 0); + capped_base.tail<3>() = pose.block<3, 3>(0, 0) * Eigen::Vector3d(0, 1, 0); + auto later_q = q_; + later_q[0] += .2; + Twist previous = Twist::Zero(); + Twist previous_acceleration = Twist::Zero(); + int captures = 0; + int samples = 0; + for (double scaling : {1.0, .5, 0.0, 1.0}) { + SCOPED_TRACE(scaling); + CartesianVelocityStep result; + for (int i = 0; i < 2200; ++i, ++samples) { + result = stepAndCommit(*planner_, kDt, samples == 0 ? q_ : later_q, qd_, scaling); + ASSERT_TRUE(result.status.ok()) << result.status.message; + EXPECT_FALSE(result.settled); // Pausing must retain the active request. + if (result.reference.valid) { + ++captures; + EXPECT_NEAR(common::math::velocityToVector(result.reference.target_base).head<3>().norm(), 1, 1e-12); + EXPECT_NEAR(common::math::velocityToVector(result.reference.target_base).tail<3>().norm(), 2, 1e-12); + } + const Twist velocity = common::math::velocityToVector(result.twist_base); + const Twist acceleration = (velocity - previous) / kDt; + const Twist jerk = (acceleration - previous_acceleration) / kDt; + EXPECT_LE(velocity.head<3>().norm(), .2 + 1e-10); + EXPECT_LE(velocity.tail<3>().norm(), 1 + 1e-10); + EXPECT_LE(acceleration.head<3>().norm(), .4 + 1e-8); + EXPECT_LE(acceleration.tail<3>().norm(), .8 + 1e-8); + EXPECT_LE(jerk.head<3>().norm(), 2 + 1e-6); + EXPECT_LE(jerk.tail<3>().norm(), 4 + 1e-6); + previous = velocity; + previous_acceleration = acceleration; + } + EXPECT_NEAR((previous - scaling * capped_base).norm(), 0, 1e-10); + if (scaling == 0) { + for (double qdot : result.joint_velocity.velocity) EXPECT_DOUBLE_EQ(qdot, 0); + } + } + EXPECT_EQ(captures, 1); +} + +TEST_F(PinocchioSpeedLLimits, InvalidScalingOrResetLeavesActiveProfileUnchanged) { + SpeedLOptions options; + options.acceleration = .4; + CartesianVelocity target; + target.vy = .1; + ASSERT_TRUE(planner_->submit(target, options, FrameType::Base).ok()); + for (int i = 0; i < 100; ++i) ASSERT_TRUE(stepAndCommit(*planner_, kDt, q_, qd_).status.ok()); + auto reference = *planner_; + for (double invalid : {-1.0, 1.01, std::numeric_limits::infinity(), + std::numeric_limits::quiet_NaN()}) { + const auto rejected = stepAndCommit(*planner_, kDt, q_, qd_, invalid); + EXPECT_EQ(rejected.status.code, ArmErrorCode::InvalidArgument); + EXPECT_TRUE(rejected.joint_velocity.velocity.empty()); + } + EXPECT_EQ(planner_->reset({}, qd_).code, ArmErrorCode::InvalidDof); + auto invalid_qd = qd_; + invalid_qd[0] = std::numeric_limits::quiet_NaN(); + EXPECT_EQ(planner_->reset(q_, invalid_qd).code, ArmErrorCode::InvalidArgument); + for (int i = 0; i < 300; ++i) { + const auto actual = stepAndCommit(*planner_, kDt, q_, qd_); + const auto expected = stepAndCommit(reference, kDt, q_, qd_); + ASSERT_TRUE(actual.status.ok()) << actual.status.message; + ASSERT_TRUE(expected.status.ok()) << expected.status.message; + EXPECT_EQ(actual.joint_velocity.velocity, expected.joint_velocity.velocity); + } +} + +TEST_F(PinocchioSpeedLLimits, StoppedOrPausedProfileCannotGenerateNullspaceMotion) { + auto policy = solver_->jointLimitPolicy(); + policy.mutable_avoidance()->set_enable(true); + solver_->setJointLimitPolicy(policy); + auto near_limit = q_; + near_limit[6] = 1.5; + Eigen::Matrix4d pose; + Eigen::MatrixXd jacobian; + Eigen::Matrix3d rotation; + ASSERT_TRUE(solver_->computePoseAndJacobianBaseAtQ(near_limit, true, pose, jacobian, rotation)); + std::vector nullspace_velocity; + ASSERT_TRUE(solver_->solveVelocityBase(jacobian, Twist::Zero(), near_limit, nullspace_velocity, + std::numeric_limits::infinity())); + EXPECT_GT(Eigen::Map(nullspace_velocity.data(), nullspace_velocity.size()).norm(), 1e-6); + ASSERT_TRUE(planner_->reset(near_limit, qd_).ok()); + SpeedLOptions options; + options.acceleration = .4; + CartesianVelocity target; + target.vy = .1; + for (bool pause : {false, true}) { + ASSERT_TRUE(planner_->submit(pause ? target : CartesianVelocity{}, options, FrameType::Base).ok()); + const auto result = stepAndCommit(*planner_, kDt, near_limit, qd_, pause ? 0 : 1); + ASSERT_TRUE(result.status.ok()) << result.status.message; + EXPECT_EQ(result.settled, !pause); + for (double qdot : result.joint_velocity.velocity) EXPECT_DOUBLE_EQ(qdot, 0); + } +} + +class PinocchioQpSpeedLIntegration : public ::testing::Test { +protected: + void SetUp() override { + const auto root = std::filesystem::path(CMVR_TEST_SOURCE_DIR); + config::ArmRootConfig arms; + ASSERT_TRUE(ProtoMessageIo::getProtoFromAsciiFile( + (root / "cmvr-es/config/devices/arm/arm_mujoco_qp.pb.txt").string(), &arms)); + ASSERT_GT(arms.arm().robot_arms_size(), 0); + const auto& arm = arms.arm().robot_arms(0); + auto ik = arm.kinematics().pinocchio_qp_ik_solver(); + ik.set_urdf_path((root / "model/xiaoyan_description/dual_arm.urdf").string()); + solver_ = std::make_shared(ik); + ASSERT_TRUE(solver_->init()); + planner_ = std::make_unique(solver_); + limits_ = arm.motion().speed_l().pinocchio_cartesian_motion_planner(); + ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size())); + ASSERT_TRUE(solver_->getJointPositionLimits(lower_, upper_)); + ASSERT_TRUE(solver_->getJointVelocityLimits(velocity_limits_)); + std::vector names; + ASSERT_TRUE(solver_->getChainJointNames(names)); + acceleration_limits_.assign(names.size(), 0); + for (std::size_t i = 0; i < names.size(); ++i) { + for (const auto& limit : ik.joint_limit_policy().limits().joints()) { + if (limit.joint_name() == names[i]) acceleration_limits_[i] = limit.qdd(); + } + ASSERT_GT(acceleration_limits_[i], 0); + } + } + + // Integrate the actual joint command, not the requested Cartesian twist. + ::testing::AssertionResult advance(CartesianVelocityStep& result, double scaling = 1) { + Eigen::Matrix4d pose; + Eigen::MatrixXd jacobian; + Eigen::Matrix3d rotation; + if (!solver_->computePoseAndJacobianBaseAtQ(q_, true, pose, jacobian, rotation)) + return ::testing::AssertionFailure() << "FK/Jacobian failed"; + result = stepAndCommit(*planner_, kDt, q_, qd_, scaling); + if (!result.status.ok()) return ::testing::AssertionFailure() << result.status.message; + if (result.joint_velocity.velocity.size() != q_.size()) + return ::testing::AssertionFailure() << "wrong command size"; + const auto& next_qd = result.joint_velocity.velocity; + const Eigen::Map velocity(next_qd.data(), next_qd.size()); + const Twist desired = common::math::velocityToVector(result.twist_base); + if (!velocity.allFinite() || !desired.allFinite()) + return ::testing::AssertionFailure() << "non-finite command"; + const double residual = (jacobian * velocity - desired).norm(); + if (residual > 1e-5) + return ::testing::AssertionFailure() << "Cartesian equality residual=" << residual; + for (std::size_t i = 0; i < q_.size(); ++i) { + const double next_q = q_[i] + next_qd[i] * kDt; + const double acceleration = std::abs(next_qd[i] - qd_[i]) / kDt; + if (next_q < lower_[i] - 1e-7 || next_q > upper_[i] + 1e-7 || + std::abs(next_qd[i]) > velocity_limits_[i] + 1e-6 || + acceleration > acceleration_limits_[i] + 1e-3) { + return ::testing::AssertionFailure() << "joint=" << i << " q=" << next_q + << " qd=" << next_qd[i] << " qdd=" << acceleration; + } + } + qd_ = next_qd; + for (std::size_t i = 0; i < q_.size(); ++i) q_[i] += qd_[i] * kDt; + return ::testing::AssertionSuccess(); + } + + std::shared_ptr solver_; + std::unique_ptr planner_; + config::SpeedLPlannerConfig limits_; + std::vector q_{.25, 1, M_PI / 2, M_PI / 2, -M_PI / 2, 0, 0}; + std::vector qd_ = std::vector(7, 0); + std::vector acceleration_limits_; + Eigen::VectorXd lower_, upper_, velocity_limits_; +}; + +TEST_F(PinocchioQpSpeedLIntegration, TouchingAtShoulderLimitKeepsStraightToolMotion) { + // Recorded off-centre touch pose that previously accumulated 5 mm drift. + q_ = {.2667416268, 1.57, .9599837007, 1.223555827, + -2.912197805, -.4882931474, -.03457454408}; + ASSERT_TRUE(planner_->reset(q_, qd_).ok()); + Eigen::Matrix4d initial_pose; + ASSERT_TRUE(solver_->fk(q_, initial_pose, true)); + const Eigen::Vector3d axis = -initial_pose.block<3, 3>(0, 0).col(1); + CartesianVelocity target; + target.vy = -.04; + SpeedLOptions options; + options.acceleration = 6; + options.linear_jerk = 100; + options.continuous_linear_reversal = true; + ASSERT_TRUE(planner_->submit(target, options, FrameType::Tool).ok()); + double max_lateral_error = 0; + Eigen::Matrix4d pose; + CartesianVelocityStep result; + for (int i = 0; i < 2000; ++i) { + ASSERT_TRUE(advance(result)) << "sample=" << i; + ASSERT_TRUE(solver_->fk(q_, pose, true)); + const Eigen::Vector3d delta = pose.block<3, 1>(0, 3) - initial_pose.block<3, 1>(0, 3); + max_lateral_error = std::max(max_lateral_error, (delta - axis * axis.dot(delta)).norm()); + } + const Eigen::Vector3d delta = pose.block<3, 1>(0, 3) - initial_pose.block<3, 1>(0, 3); + EXPECT_GT(axis.dot(delta), .06); // A stopped or heavily slowed arm must not pass. + EXPECT_LT(axis.dot(delta), .081); + EXPECT_LT(max_lateral_error, .0002); + EXPECT_NEAR(common::math::velocityToVector(result.twist_base).head<3>().norm(), .04, 1e-7); +} + +TEST_F(PinocchioQpSpeedLIntegration, AdaptiveSpeedSlowsTouchTargetThroughSCurveBeforeWristLimit) { + const std::vector initial{.250503734519, 1.1370261797, 1.58375920865, + .774603121123, -2.87240757376, .387646573327, -.395308298864}; + CartesianVelocity target; + target.vy = -.04; + SpeedLOptions options; + options.acceleration = 6; + options.linear_jerk = 100; + options.continuous_linear_reversal = true; + for (bool adaptive : {false, true}) { + SCOPED_TRACE(adaptive); + limits_.mutable_adaptive_speed()->set_enable(adaptive); + limits_.mutable_adaptive_speed()->set_lookahead_s(.15); + limits_.mutable_adaptive_speed()->set_min_speed_ratio(0); // Legacy near-zero hold. + ASSERT_TRUE(planner_->configureSpeedL(limits_, initial.size())); + q_ = initial; + qd_.assign(initial.size(), 0); + ASSERT_TRUE(planner_->reset(q_, qd_).ok()); + ASSERT_TRUE(planner_->submit(target, options, FrameType::Tool).ok()); + Twist previous = Twist::Zero(), previous_acceleration = Twist::Zero(); + double max_speed = 0, max_acceleration = 0, max_jerk = 0, late_max_speed = 0; + int failure_tick = -1; + for (int tick = 0; tick < (adaptive ? 6000 : 3000); ++tick) { + CartesianVelocityStep result; + const auto advanced = advance(result); + if (!advanced) { + failure_tick = tick; + if (adaptive) ADD_FAILURE() << "tick=" << tick << ": " << advanced.message(); + break; + } + const Twist velocity = common::math::velocityToVector(result.twist_base); + const Twist acceleration = (velocity - previous) / kDt; + const Twist jerk = (acceleration - previous_acceleration) / kDt; + max_speed = std::max(max_speed, velocity.head<3>().norm()); + max_acceleration = std::max(max_acceleration, acceleration.head<3>().norm()); + max_jerk = std::max(max_jerk, jerk.head<3>().norm()); + if (tick >= 5000) late_max_speed = std::max(late_max_speed, velocity.head<3>().norm()); + previous = velocity; + previous_acceleration = acceleration; + } + EXPECT_LE(max_speed, .04 + 1e-8); + EXPECT_LE(max_acceleration, options.acceleration + 1e-5); + EXPECT_LE(max_jerk, *options.linear_jerk + 1e-3); + EXPECT_GT(max_speed, .039); + if (adaptive) { + EXPECT_EQ(failure_tick, -1); + EXPECT_LT(previous.head<3>().norm(), .035); + RecordProperty("adaptive_final_speed_m_s", std::to_string(previous.head<3>().norm())); + RecordProperty("adaptive_max_acceleration_m_s2", std::to_string(max_acceleration)); + RecordProperty("adaptive_max_jerk_m_s3", std::to_string(max_jerk)); + RecordProperty("adaptive_wrist_position_rad", std::to_string(q_[6])); + EXPECT_LT(late_max_speed, 1e-5); // No spurious speed recovery near rest. + RecordProperty("near_rest_max_speed_m_s", std::to_string(late_max_speed)); + if (failure_tick < 0) { + const double wrist_before_reverse = q_[6]; + CartesianVelocity retreat; + retreat.vy = .04; + ASSERT_TRUE(planner_->submit(retreat, options, FrameType::Tool).ok()); + for (int tick = 0; tick < 500; ++tick) { + CartesianVelocityStep result; + ASSERT_TRUE(advance(result)) << "retreat tick=" << tick; + const Twist velocity = common::math::velocityToVector(result.twist_base); + const Twist acceleration = (velocity - previous) / kDt; + const Twist jerk = (acceleration - previous_acceleration) / kDt; + EXPECT_LE(velocity.head<3>().norm(), .04 + 1e-8); + EXPECT_LE(acceleration.head<3>().norm(), options.acceleration + 1e-5); + EXPECT_LE(jerk.head<3>().norm(), *options.linear_jerk + 1e-3); + previous = velocity; + previous_acceleration = acceleration; + } + EXPECT_GT(q_[6] - wrist_before_reverse, .01); + EXPECT_NEAR(previous.head<3>().norm(), .04, 1e-7); + RecordProperty("reverse_wrist_displacement_rad", std::to_string(q_[6] - wrist_before_reverse)); + } + } else { + EXPECT_GE(failure_tick, 1000); + EXPECT_LT(failure_tick, 1500); + RecordProperty("without_adaptation_failure_tick", failure_tick); + } + } +} + +TEST_F(PinocchioQpSpeedLIntegration, AdaptiveMinimumRatioStopsSmoothlyAndLatchesUntilReset) { + q_ = {.250503734519, 1.1370261797, 1.58375920865, .774603121123, + -2.87240757376, .387646573327, -.395308298864}; + limits_.mutable_adaptive_speed()->set_enable(true); + limits_.mutable_adaptive_speed()->set_lookahead_s(.15); + limits_.mutable_adaptive_speed()->set_min_speed_ratio(.1); + ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size())); + ASSERT_TRUE(planner_->reset(q_, qd_).ok()); + CartesianVelocity target; + target.vy = -.04; + SpeedLOptions options; + options.acceleration = 6; + options.linear_jerk = 100; + options.continuous_linear_reversal = true; + ASSERT_TRUE(planner_->submit(target, options, FrameType::Tool).ok()); + Twist previous = Twist::Zero(), previous_acceleration = Twist::Zero(); + double max_velocity = 0, max_acceleration = 0, max_jerk = 0; + int trigger_tick = -1, settled_tick = -1; + CartesianVelocityStep result; + for (int tick = 0; tick < 3000; ++tick) { + ASSERT_TRUE(advance(result)) << "tick=" << tick; + const Twist velocity = common::math::velocityToVector(result.twist_base); + const Twist acceleration = (velocity - previous) / kDt; + const Twist jerk = (acceleration - previous_acceleration) / kDt; + max_velocity = std::max(max_velocity, velocity.head<3>().norm()); + max_acceleration = std::max(max_acceleration, acceleration.head<3>().norm()); + max_jerk = std::max(max_jerk, jerk.head<3>().norm()); + previous = velocity; + previous_acceleration = acceleration; + if (tick == 0) { + EXPECT_LT(velocity.head<3>().norm(), .004); + EXPECT_TRUE(result.stop_reason.ok()); // Startup below 10% is normal. + } + if (!result.stop_reason.ok()) { + EXPECT_EQ(result.stop_reason.code, ArmErrorCode::OutOfVelocityLimit); + EXPECT_NE(result.stop_reason.message.find("adaptive speed ratio below min_speed_ratio"), + std::string::npos); + if (trigger_tick < 0) { + trigger_tick = tick; + EXPECT_FALSE(result.settled); // Must decelerate, not jump to zero. + EXPECT_GT(velocity.head<3>().norm(), 1e-6); + RecordProperty("speed_at_minimum_ratio_m_s", std::to_string(velocity.head<3>().norm())); + auto retreat = target; + retreat.vy = .04; + EXPECT_FALSE(planner_->submit(retreat, options, FrameType::Tool).ok()); + } + EXPECT_FALSE(planner_->submit(target, options, FrameType::Tool).ok()); + if (result.settled) { settled_tick = tick; break; } + } else { + EXPECT_LT(trigger_tick, 0) << "A latched stop must not disappear"; + } + } + EXPECT_GT(trigger_tick, 1000); + ASSERT_GT(settled_tick, trigger_tick); + EXPECT_LT(settled_tick - trigger_tick, 500); + EXPECT_LE(max_velocity, .04 + 1e-8); + EXPECT_GT(max_velocity, .039); + EXPECT_LE(max_acceleration, options.acceleration + 1e-5); + EXPECT_LE(max_jerk, *options.linear_jerk + 1e-3); + EXPECT_NEAR(previous.norm(), 0, 1e-10); + for (double velocity : qd_) EXPECT_NEAR(velocity, 0, 1e-9); + EXPECT_GT(q_[6], -.57); + const double wrist_before_reverse = q_[6]; + for (int tick = 0; tick < 10; ++tick) { + ASSERT_TRUE(advance(result)); + EXPECT_TRUE(result.settled); + EXPECT_FALSE(result.stop_reason.ok()); + } + RecordProperty("minimum_ratio_trigger_tick", trigger_tick); + RecordProperty("minimum_ratio_settled_tick", settled_tick); + RecordProperty("minimum_ratio_max_jerk_m_s3", std::to_string(max_jerk)); + RecordProperty("minimum_ratio_stopped_wrist_rad", std::to_string(q_[6])); + ASSERT_TRUE(planner_->reset(q_, qd_).ok()); + target.vy = .04; + ASSERT_TRUE(planner_->submit(target, options, FrameType::Tool).ok()); + for (int tick = 0; tick < 500; ++tick) { + ASSERT_TRUE(advance(result)) << "retreat tick=" << tick; + EXPECT_TRUE(result.stop_reason.ok()); + } + EXPECT_GT(q_[6] - wrist_before_reverse, .01); + EXPECT_NEAR(common::math::velocityToVector(result.twist_base).head<3>().norm(), .04, 1e-7); +} + +TEST_F(PinocchioQpSpeedLIntegration, AdaptiveMinimumRatioDoesNotRejectManualSlowSpeedOrPause) { + limits_.mutable_adaptive_speed()->set_enable(true); + limits_.mutable_adaptive_speed()->set_min_speed_ratio(.1); + ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size())); + ASSERT_TRUE(planner_->reset(q_, qd_).ok()); + CartesianVelocity target; + target.vy = .02; + SpeedLOptions options; + options.acceleration = .5; + options.linear_jerk = 10; + ASSERT_TRUE(planner_->submit(target, options, FrameType::Base).ok()); + for (double scaling : {.05, 0.0, .05, 1.0}) { + SCOPED_TRACE(scaling); + CartesianVelocityStep result; + for (int tick = 0; tick < 500; ++tick) { + ASSERT_TRUE(advance(result, scaling)) << "tick=" << tick; + EXPECT_TRUE(result.stop_reason.ok()); + EXPECT_FALSE(result.settled); // A manual zero multiplier is a pause. + } + EXPECT_NEAR(common::math::velocityToVector(result.twist_base).head<3>().norm(), + .02 * scaling, 1e-7); + } +} + +TEST_F(PinocchioQpSpeedLIntegration, JointBrakingStopsRecordedFirstFailureWithinAccelerationAndPositionLimits) { + q_ = {.582722602717, 1.18224927602, 1.476371331, .30800863072, + -2.97894487049, .408292452313, -.568806827985}; + qd_ = {.435860147793, .0609563589904, -.147285286364, -.702869190529, + -.151214590595, .0319060685236, -.320632525731}; + ASSERT_TRUE(planner_->reset(q_, qd_).ok()); + double maximum_acceleration = 0; + CartesianVelocityStep braking; + for (int tick = 0; tick < 100; ++tick) { + braking = planner_->brakeStep(kDt, q_, qd_); + ASSERT_TRUE(braking.status.ok()) << "tick=" << tick << ": " << braking.status.message; + ASSERT_EQ(braking.joint_velocity.velocity.size(), q_.size()); + for (std::size_t joint = 0; joint < q_.size(); ++joint) { + const double next = braking.joint_velocity.velocity[joint]; + const double acceleration = std::abs(next - qd_[joint]) / kDt; + maximum_acceleration = std::max(maximum_acceleration, acceleration); + EXPECT_LE(acceleration, acceleration_limits_[joint] + 1e-6); + EXPECT_LE(std::abs(next), std::abs(qd_[joint]) + 1e-9); + EXPECT_GE(next * qd_[joint], -1e-12); + q_[joint] += next * kDt; + EXPECT_GE(q_[joint], lower_[joint] - 1e-9); + EXPECT_LE(q_[joint], upper_[joint] + 1e-9); + } + // There is no successful Cartesian command to commit at the first + // failure. The brake must use the measured moving state immediately. + if (tick == 0) EXPECT_GT(braking.joint_velocity.velocity[6], qd_[6]); + qd_ = braking.joint_velocity.velocity; + planner_->commitStep(); + if (braking.settled) break; + } + EXPECT_TRUE(braking.settled); + EXPECT_GE(q_[6], -.5693); // Old command held for two ticks ended at -.569448. + for (double velocity : qd_) EXPECT_DOUBLE_EQ(velocity, 0); + RecordProperty("maximum_braking_acceleration_rad_s2", std::to_string(maximum_acceleration)); + RecordProperty("stopped_wrist_position_rad", std::to_string(q_[6])); +} + +TEST_F(PinocchioQpSpeedLIntegration, ReversalPauseResumeAndStopRespectJointBounds) { + // Make nullspace avoidance active even at this pose away from hard limits. + auto policy = solver_->jointLimitPolicy(); + policy.mutable_avoidance()->set_enable(true); + policy.mutable_avoidance()->set_gain(.2); + policy.mutable_avoidance()->set_margin_ratio(.4); + policy.mutable_avoidance()->set_max_push(.1); + solver_->setJointLimitPolicy(policy); + const auto initial_q = q_; + SpeedLOptions options; + options.acceleration = .3; + options.linear_jerk = 20; + options.continuous_linear_reversal = true; + + // Angular reversal stops before restarting: each 0.05 rad/s transition + // takes v/a + a/j = 0.1917 s at a=0.3, j=12. Allow both transitions + // (0.3834 s), followed by at least 100 ms of steady-state observation. + constexpr int kPhaseSamples = 500; + constexpr int kRestSamples = 100; + // Cover a translating and a rotating request, including both signs. + for (int axis : {1, 4}) { + SCOPED_TRACE(axis); + q_ = initial_q; + qd_.assign(q_.size(), 0); + ASSERT_TRUE(planner_->reset(q_, qd_).ok()); + for (int phase = 0; phase < 5; ++phase) { + SCOPED_TRACE(phase); + Twist target = Twist::Zero(); + if (phase != 4) target[axis] = (phase == 0 ? 1 : -1) * (axis < 3 ? .02 : .05); + const double scaling = phase == 2 ? 0 : 1; + ASSERT_TRUE(planner_->submit(common::math::vectorToVelocity(target), options, + FrameType::Base).ok()); + CartesianVelocityStep result; + std::vector rest_q; + for (int i = 0; i < kPhaseSamples; ++i) { + ASSERT_TRUE(advance(result, scaling)) << "sample=" << i; + if (i == kPhaseSamples - kRestSamples - 1) rest_q = q_; + } + EXPECT_NEAR((common::math::velocityToVector(result.twist_base) - scaling * target).norm(), + 0, 1e-7); + EXPECT_EQ(result.settled, phase == 4); + const Eigen::Map velocity(qd_.data(), qd_.size()); + if (phase == 2 || phase == 4) { + EXPECT_LT(velocity.norm(), 1e-6); + for (std::size_t i = 0; i < q_.size(); ++i) EXPECT_NEAR(q_[i], rest_q[i], 1e-7); + } else { + EXPECT_GT(velocity.norm(), .001); + } + } + } +} +} // namespace +} // namespace cmvr::device diff --git a/cmvr-es/algorithms/planner/cartesian/s_curve/include/s_curve_planner.h b/cmvr-es/algorithms/planner/cartesian/s_curve/include/s_curve_planner.h new file mode 100644 index 00000000..2d247248 --- /dev/null +++ b/cmvr-es/algorithms/planner/cartesian/s_curve/include/s_curve_planner.h @@ -0,0 +1,136 @@ +#pragma once + +#include +#include +#include +#include "curves/s_curve/include/s_curve.h" + +namespace cmvr +{ + +enum class CartesianFrame +{ + Base = 0, + Tool = 1 +}; + +/** + * @brief 基于 SCurve 的六维末端在线速度规划器。 + * + * initialize() 设置初始 Base 系速度,plan() 每周期生成下一拍 Base 系命令。 + * 同轴线速度可连续过零;转向使用完整速度向量的连续过渡。 + * 非连续模式与角速度近反向时,先停稳再反向。 + * 传入零目标平滑停止;相同目标会继续当前曲线,不会每拍重规划。 + * 非法输入抛出 std::invalid_argument,无可行标量曲线抛出 std::runtime_error。 + * 失败保留原规划状态;方向重规划不可行时继续已验证的原曲线。 + */ +class SCurvePlanner +{ +public: + using Twist = Eigen::Matrix; + + void setLinearConstraints(double max_velocity, + double max_acceleration, + double max_jerk); + void setAngularConstraints(double max_velocity, + double max_acceleration, + double max_jerk); + void setLinearTargetReplanThreshold(double threshold); + void setAngularTargetReplanThreshold(double threshold); + + // 连续过零保留加速度;关闭后近反向等待停稳。 + void setContinuousLinearReversal(bool enabled); + bool continuousLinearReversalEnabled() const { return continuous_linear_reversal_; } + + // 清除旧曲线,用 Base 系初始速度开始规划。 + void initialize(const Twist& initial_twist = Twist::Zero()); + + // 每周期调用一次。Tool 目标按当拍 base_R_tool 转到 Base 系。 + Twist plan(const Twist& target_twist, CartesianFrame frame, + double dt, const Eigen::Matrix3d& base_R_tool); + + const Twist& getTwistBase() const { return twist_base_; } + const Twist& getAccelerationBase() const { return acceleration_base_; } + const Twist& getJerkBase() const { return jerk_base_; } + bool isMoving() const; + +private: + static constexpr double EPSILON = 1e-12; + static constexpr double AXIS_LOCK_COS_THRESHOLD = 0.999; + + // 保存一维速度曲线的运行状态;数学计算由 SCurve 完成。 + struct VelocityState { + struct Sample { + double velocity{0.0}; + double acceleration{0.0}; + double target_velocity{0.0}; + double elapsed_time{0.0}; + bool has_active_profile{false}; + }; + + void setConstraints(double max_velocity, double max_acceleration, double max_jerk); + void setTargetReplanThreshold(double threshold); + void initialize(double velocity = 0.0, double acceleration = 0.0); + void setTargetVelocity(double target_velocity); + double update(double dt); + + double getVelocity() const { return state_.velocity; } + double getAcceleration() const { return state_.acceleration; } + double replanThreshold() const { return target_replan_threshold_; } + std::array limits() const; + bool isSettled() const; + bool isMoving() const; + + private: + void replan(); + + SCurve curve_{1.0, 1.0, 5.0}; + Sample state_; + SCurveVelocityProfile active_profile_; + double target_replan_threshold_{1e-9}; + static constexpr double VELOCITY_THRESHOLD = 1e-6; + }; + + // Cubic Bezier velocity: endpoint accelerations are a0 and zero. + // Derivative control-point norms certify complete v/a/j bounds. + struct DirectionProfile { + std::array control{ + Eigen::Vector3d::Zero(), Eigen::Vector3d::Zero(), + Eigen::Vector3d::Zero(), Eigen::Vector3d::Zero()}; + double duration{0.0}; + double elapsed{0.0}; + bool active{false}; + bool stopping_for_reversal{false}; + + std::pair sample(double time) const; + bool fits(const std::array& limits) const; + DirectionProfile remaining() const; + }; + + VelocityState linear_velocity_; + VelocityState angular_velocity_; + DirectionProfile linear_direction_profile_; + DirectionProfile angular_direction_profile_; + bool continuous_linear_reversal_{true}; + + Twist twist_base_{Twist::Zero()}; + Twist acceleration_base_{Twist::Zero()}; + Twist jerk_base_{Twist::Zero()}; + double previous_period_{0.0}; + Eigen::Vector3d current_linear_dir_base_{Eigen::Vector3d::Zero()}; + Eigen::Vector3d current_angular_dir_base_{Eigen::Vector3d::Zero()}; + + static void setConstraints(VelocityState& scalar, DirectionProfile& profile, + double velocity, double acceleration, double jerk); + static bool planDirection(const Eigen::Vector3d& velocity, + const Eigen::Vector3d& acceleration, + const Eigen::Vector3d& target, double dt, + const std::array& limits, + DirectionProfile& profile); + static Eigen::Vector3d planVelocity(VelocityState& scalar, DirectionProfile& profile, + Eigen::Vector3d& direction, + const Eigen::Vector3d& target, double dt, + bool continuous_reversal); +}; + +} // namespace cmvr diff --git a/cmvr-es/algorithms/planner/cartesian/s_curve/include/s_curve_planner_config.h b/cmvr-es/algorithms/planner/cartesian/s_curve/include/s_curve_planner_config.h new file mode 100644 index 00000000..83b7453a --- /dev/null +++ b/cmvr-es/algorithms/planner/cartesian/s_curve/include/s_curve_planner_config.h @@ -0,0 +1,47 @@ +#ifndef CMVR_ES_S_CURVE_PLANNER_CONFIG_H +#define CMVR_ES_S_CURVE_PLANNER_CONFIG_H + +#include +#include + +#include "algorithms/planner/cartesian/s_curve/include/s_curve_planner.h" +#include "cmvr/config/arm_config/arm_config.pb.h" +#include "common/config/config_files.h" + +namespace cmvr::device::cartesian_motion { + +inline void configureSCurvePlannerFromSpeedLConfig( + cmvr::SCurvePlanner& planner, + const config::SpeedLPlannerConfig& config) +{ + using cmvr::common::config::positiveOr; + + // Zero retains the protobuf default; reject bad values before changing the planner. + for (const double value : {config.linear_velocity_max(), config.linear_acceleration_max(), + config.linear_jerk_max(), config.angular_velocity_max(), + config.angular_acceleration_max(), config.angular_jerk_max(), + config.linear_target_replan_threshold(), + config.angular_target_replan_threshold()}) { + if (!std::isfinite(value) || value < 0.0) { + throw std::invalid_argument("speedL limits and thresholds must be finite and non-negative"); + } + } + + planner.setLinearConstraints(positiveOr(config.linear_velocity_max(), 0.55), + positiveOr(config.linear_acceleration_max(), 5.0), + positiveOr(config.linear_jerk_max(), 10.0)); + planner.setAngularConstraints(positiveOr(config.angular_velocity_max(), 1.0), + positiveOr(config.angular_acceleration_max(), 5.0), + positiveOr(config.angular_jerk_max(), 12.0)); + planner.setLinearTargetReplanThreshold( + positiveOr(config.linear_target_replan_threshold(), 1e-4)); + planner.setAngularTargetReplanThreshold( + positiveOr(config.angular_target_replan_threshold(), 1e-4)); + planner.setContinuousLinearReversal(!config.has_continuous_linear_reversal() || + config.continuous_linear_reversal()); + planner.initialize(Eigen::Matrix::Zero()); +} + +} // namespace cmvr::device::cartesian_motion + +#endif // CMVR_ES_S_CURVE_PLANNER_CONFIG_H diff --git a/cmvr-es/algorithms/planner/cartesian/s_curve/src/s_curve_planner.cpp b/cmvr-es/algorithms/planner/cartesian/s_curve/src/s_curve_planner.cpp new file mode 100644 index 00000000..ebb2fd75 --- /dev/null +++ b/cmvr-es/algorithms/planner/cartesian/s_curve/src/s_curve_planner.cpp @@ -0,0 +1,420 @@ +#include "../include/s_curve_planner.h" + +#include +#include +#include + +namespace cmvr +{ +namespace { +void validateLimits(double velocity, double acceleration, double jerk) +{ + // SCurve's solver treats acceleration/jerk <= 1e-9 as degenerate. + if (!std::isfinite(velocity) || velocity <= 1e-9 || + !std::isfinite(acceleration) || acceleration <= 1e-9 || + !std::isfinite(jerk) || jerk <= 1e-9) { + throw std::invalid_argument("S-curve limits must be finite and greater than 1e-9"); + } +} + +bool withinLimit(double value, double limit) +{ + return std::isfinite(value) && value <= limit * (1.0 + 1e-10); +} +} // namespace + +std::array SCurvePlanner::VelocityState::limits() const +{ + std::array result; + curve_.getConstraints(result[0], result[1], result[2]); + return result; +} + +void SCurvePlanner::VelocityState::setConstraints(double max_velocity, + double max_acceleration, + double max_jerk) +{ + validateLimits(max_velocity, max_acceleration, max_jerk); + if (!withinLimit(std::abs(state_.velocity), max_velocity) || + !withinLimit(std::abs(state_.acceleration), max_acceleration)) { + throw std::invalid_argument("S-curve limits exclude the current velocity or acceleration"); + } + if (limits() == std::array{max_velocity, max_acceleration, max_jerk}) return; + + auto staged = *this; + staged.curve_.setConstraints(max_velocity, max_acceleration, max_jerk); + staged.state_.target_velocity = + std::clamp(state_.target_velocity, -max_velocity, max_velocity); + if (state_.has_active_profile || state_.acceleration != 0.0) staged.replan(); + *this = std::move(staged); +} + +void SCurvePlanner::VelocityState::setTargetReplanThreshold(double threshold) +{ + if (!std::isfinite(threshold) || threshold < 0.0) { + throw std::invalid_argument("S-curve replan threshold must be nonnegative and finite"); + } + target_replan_threshold_ = threshold; +} + +void SCurvePlanner::VelocityState::initialize(double velocity, double acceleration) +{ + const auto bounds = limits(); + if (!withinLimit(std::abs(velocity), bounds[0]) || + !withinLimit(std::abs(acceleration), bounds[1])) { + throw std::invalid_argument("S-curve initial velocity or acceleration exceeds limits"); + } + state_ = Sample{}; + state_.velocity = velocity; + state_.acceleration = acceleration; + state_.target_velocity = velocity; + active_profile_ = SCurveVelocityProfile(); +} + +void SCurvePlanner::VelocityState::setTargetVelocity(double target_velocity) +{ + const double velocity_limit = limits()[0]; + const double new_target = std::clamp(target_velocity, -velocity_limit, velocity_limit); + const bool same_target = + std::abs(new_target - state_.target_velocity) <= target_replan_threshold_; + if (same_target && (state_.has_active_profile || + (std::abs(state_.velocity - new_target) <= VELOCITY_THRESHOLD && + state_.acceleration == 0.0))) return; + + state_.target_velocity = new_target; + replan(); +} + +void SCurvePlanner::VelocityState::replan() +{ + const auto candidate = curve_.calculateVelocityProfile( + state_.velocity, state_.target_velocity, state_.acceleration); + const double values[] = {candidate.t1, candidate.t2, candidate.t3, + candidate.total_time, candidate.j1, candidate.j2, candidate.j3, + candidate.v0, candidate.a0, candidate.vf}; + const bool finite = std::all_of(std::begin(values), std::end(values), + [](double value) { return std::isfinite(value); }); + if (!finite || !candidate.valid || candidate.total_time <= 0.0 || + candidate.t1 < 0.0 || candidate.t2 < 0.0 || candidate.t3 < 0.0) { + if (finite && std::abs(state_.velocity - state_.target_velocity) <= VELOCITY_THRESHOLD && + state_.acceleration == 0.0) { + state_.has_active_profile = false; + return; + } + throw std::runtime_error("S-curve could not generate a finite feasible velocity profile"); + } + // The mathematical solver must not silently clamp the starting state. + if (std::abs(candidate.v0 - state_.velocity) > 1e-12 || + std::abs(candidate.a0 - state_.acceleration) > 1e-12) { + throw std::runtime_error("S-curve profile changed its initial state"); + } + active_profile_ = candidate; + state_.elapsed_time = 0.0; + state_.has_active_profile = true; +} + +double SCurvePlanner::VelocityState::update(double dt) +{ + if (!state_.has_active_profile) { + if (state_.acceleration != 0.0 || + std::abs(state_.velocity - state_.target_velocity) > VELOCITY_THRESHOLD) { + throw std::runtime_error("S-curve has no active profile for a moving transition"); + } + return state_.velocity; + } + state_.elapsed_time = std::min(state_.elapsed_time + dt, active_profile_.total_time); + if (state_.elapsed_time >= active_profile_.total_time) { + state_.velocity = active_profile_.vf; + state_.acceleration = 0.0; + state_.has_active_profile = false; + } else { + state_.velocity = curve_.getVelocityAtTime(active_profile_, state_.elapsed_time); + state_.acceleration = curve_.getAccelerationAtTime(active_profile_, state_.elapsed_time); + } + if (!std::isfinite(state_.velocity) || !std::isfinite(state_.acceleration)) { + throw std::runtime_error("S-curve produced a non-finite state"); + } + return state_.velocity; +} + +bool SCurvePlanner::VelocityState::isSettled() const +{ + return !state_.has_active_profile && + std::abs(state_.velocity) <= VELOCITY_THRESHOLD && + state_.acceleration == 0.0; +} + +bool SCurvePlanner::VelocityState::isMoving() const +{ + return !isSettled() || std::abs(state_.target_velocity) > VELOCITY_THRESHOLD; +} + +std::pair +SCurvePlanner::DirectionProfile::sample(double time) const +{ + const double u = std::clamp(time / duration, 0.0, 1.0); + const double r = 1.0 - u; + const Eigen::Vector3d velocity = r*r*r*control[0] + 3*r*r*u*control[1] + + 3*r*u*u*control[2] + u*u*u*control[3]; + const Eigen::Vector3d acceleration = (3.0 / duration) * + (r*r*(control[1]-control[0]) + 2*r*u*(control[2]-control[1]) + + u*u*(control[3]-control[2])); + return {velocity, acceleration}; +} + +bool SCurvePlanner::DirectionProfile::fits(const std::array& bounds) const +{ + if (!std::isfinite(duration) || duration <= 0.0) return false; + std::array acceleration; + for (std::size_t i = 0; i < control.size(); ++i) { + if (!withinLimit(control[i].norm(), bounds[0])) return false; + if (i < acceleration.size()) { + acceleration[i] = (3.0 / duration) * (control[i+1] - control[i]); + if (!withinLimit(acceleration[i].norm(), bounds[1])) return false; + } + } + for (std::size_t i = 0; i < 2; ++i) { + if (!withinLimit(((2.0 / duration) * (acceleration[i+1] - acceleration[i])).norm(), + bounds[2])) return false; + } + return true; +} + +SCurvePlanner::DirectionProfile SCurvePlanner::DirectionProfile::remaining() const +{ + auto result = *this; + auto work = control; + const double u = std::clamp(elapsed / duration, 0.0, 1.0); + for (std::size_t level = 1; level < control.size(); ++level) { + for (std::size_t i = 0; i < control.size() - level; ++i) { + work[i] = (1.0 - u) * work[i] + u * work[i+1]; + } + result.control[control.size()-level-1] = work[control.size()-level-1]; + } + result.duration -= elapsed; + result.elapsed = 0.0; + return result; +} + +void SCurvePlanner::setConstraints(VelocityState& scalar, DirectionProfile& profile, + double velocity, double acceleration, double jerk) +{ + validateLimits(velocity, acceleration, jerk); + if (scalar.limits() == std::array{velocity, acceleration, jerk}) return; + if (profile.active && !profile.remaining().fits({velocity, acceleration, jerk})) { + throw std::invalid_argument("S-curve limits exclude the remaining direction transition"); + } + // While a vector curve is active the scalar state is dormant at zero. + scalar.setConstraints(velocity, acceleration, jerk); +} + +void SCurvePlanner::setLinearConstraints(double velocity, double acceleration, double jerk) +{ + setConstraints(linear_velocity_, linear_direction_profile_, velocity, acceleration, jerk); +} + +void SCurvePlanner::setAngularConstraints(double velocity, double acceleration, double jerk) +{ + setConstraints(angular_velocity_, angular_direction_profile_, velocity, acceleration, jerk); +} + +void SCurvePlanner::setLinearTargetReplanThreshold(double threshold) +{ + linear_velocity_.setTargetReplanThreshold(threshold); +} + +void SCurvePlanner::setAngularTargetReplanThreshold(double threshold) +{ + angular_velocity_.setTargetReplanThreshold(threshold); +} + +void SCurvePlanner::setContinuousLinearReversal(bool enabled) +{ + if (continuous_linear_reversal_ == enabled) return; + if (!enabled && !linear_direction_profile_.active) { + const double velocity = linear_velocity_.getVelocity(); + const double acceleration = linear_velocity_.getAcceleration(); + if (velocity < 0.0 || (std::abs(velocity) <= EPSILON && acceleration < 0.0)) { + linear_velocity_.initialize(-velocity, -acceleration); + current_linear_dir_base_ = -current_linear_dir_base_; + } + } + if (enabled) linear_direction_profile_.stopping_for_reversal = false; + continuous_linear_reversal_ = enabled; +} + +void SCurvePlanner::initialize(const Twist& initial_twist) +{ + const Eigen::Vector3d v0 = initial_twist.head<3>(); + const Eigen::Vector3d w0 = initial_twist.tail<3>(); + const double v0_norm = v0.norm(); + const double w0_norm = w0.norm(); + if (!initial_twist.allFinite() || !std::isfinite(v0_norm) || !std::isfinite(w0_norm)) { + throw std::invalid_argument("S-curve initial twist must be finite"); + } + auto staged = *this; + staged.linear_velocity_.initialize(v0_norm, 0.0); + staged.angular_velocity_.initialize(w0_norm, 0.0); + staged.linear_direction_profile_ = DirectionProfile{}; + staged.angular_direction_profile_ = DirectionProfile{}; + staged.twist_base_ = initial_twist; + staged.acceleration_base_.setZero(); + staged.jerk_base_.setZero(); + staged.previous_period_ = 0.0; + staged.current_linear_dir_base_.setZero(); + staged.current_angular_dir_base_.setZero(); + if (v0_norm > EPSILON) staged.current_linear_dir_base_ = v0 / v0_norm; + if (w0_norm > EPSILON) staged.current_angular_dir_base_ = w0 / w0_norm; + *this = std::move(staged); +} + +bool SCurvePlanner::planDirection(const Eigen::Vector3d& velocity, + const Eigen::Vector3d& acceleration, + const Eigen::Vector3d& target, double dt, + const std::array& bounds, + DirectionProfile& profile) +{ + const double delta = (target - velocity).norm(); + const double a = acceleration.norm(); + // Necessary lower bounds; feasibility is not monotone in duration because + // P1 = v0 + T*a0/3 can leave the velocity ball when T grows. + const double a_over_j = a / bounds[2]; + const double delta_over_j = 6.0 * (delta / bounds[2]); + const double denominator = std::hypot(2.0 * a_over_j, std::sqrt(delta_over_j)) + + 2.0 * a_over_j; + const double jerk_duration = denominator > 0.0 ? delta_over_j / denominator : 0.0; + double duration = std::max({1e-9, std::min(dt, 1e-6), a_over_j, jerk_duration, + 3.0 * delta / (bounds[1] + a)}); + for (int attempt = 0; attempt < 50 && std::isfinite(duration); ++attempt) { + DirectionProfile candidate; + candidate.control = {velocity, velocity + (duration / 3.0) * acceleration, + target, target}; + candidate.duration = duration; + candidate.active = true; + candidate.stopping_for_reversal = profile.stopping_for_reversal; + if (candidate.fits(bounds)) { + profile = std::move(candidate); + return true; + } + duration *= 1.18; + } + return false; +} + +Eigen::Vector3d SCurvePlanner::planVelocity(VelocityState& scalar, + DirectionProfile& profile, + Eigen::Vector3d& direction, + const Eigen::Vector3d& target, double dt, + bool continuous_reversal) +{ + const auto bounds = scalar.limits(); + Eigen::Vector3d desired = target; + const double target_norm = target.norm(); + if (target_norm > bounds[0]) desired *= bounds[0] / target_norm; + + Eigen::Vector3d velocity = direction * scalar.getVelocity(); + Eigen::Vector3d acceleration = direction * scalar.getAcceleration(); + if (profile.active) { + const auto state = profile.sample(profile.elapsed); + velocity = state.first; + acceleration = state.second; + if (!continuous_reversal && velocity.norm() > EPSILON && desired.norm() > EPSILON && + velocity.normalized().dot(desired.normalized()) <= -AXIS_LOCK_COS_THRESHOLD) { + profile.stopping_for_reversal = true; + } + } + if (profile.stopping_for_reversal) desired.setZero(); + + if (!profile.active) { + if (velocity.isZero(0.0) && acceleration.isZero(0.0)) { + if (desired.norm() > EPSILON) direction = desired.normalized(); + scalar.setTargetVelocity(desired.norm()); + return direction * scalar.update(dt); + } + const double signed_target = direction.dot(desired); + const bool collinear = (desired - signed_target * direction).norm() <= + 1e-12 * desired.norm(); + const bool reverse = desired.norm() > EPSILON && + direction.dot(desired.normalized()) <= -AXIS_LOCK_COS_THRESHOLD; + if (desired.norm() <= EPSILON || (!continuous_reversal && reverse) || + (collinear && (continuous_reversal || signed_target >= 0.0))) { + scalar.setTargetVelocity((!continuous_reversal && reverse) ? 0.0 : signed_target); + const auto result = direction * scalar.update(dt); + if (profile.stopping_for_reversal && scalar.isSettled()) { + profile.stopping_for_reversal = false; + } + return result; + } + } + + if (!profile.active || + (desired - profile.control.back()).norm() > scalar.replanThreshold()) { + if (planDirection(velocity, acceleration, desired, dt, bounds, profile)) { + scalar.initialize(); + } + } + // A rejected candidate leaves the certified old curve running. In particular, + // preserve its acceleration instead of holding one velocity sample. + if (!profile.active) return direction * scalar.update(dt); + profile.elapsed = std::min(profile.elapsed + dt, profile.duration); + velocity = profile.sample(profile.elapsed).first; + if (profile.elapsed >= profile.duration) { + profile.active = false; + const double speed = velocity.norm(); + scalar.initialize(speed, 0.0); + if (speed > EPSILON) direction = velocity / speed; + if (speed <= EPSILON) profile.stopping_for_reversal = false; + } + return velocity; +} + +SCurvePlanner::Twist +SCurvePlanner::plan(const Twist& target_twist, CartesianFrame frame, + double dt, const Eigen::Matrix3d& base_R_tool) +{ + // Smaller periods cannot reliably support command differences in double precision. + if (!std::isfinite(dt) || dt < 1e-9) { + throw std::invalid_argument("S-curve period must be finite and at least 1e-9 seconds"); + } + if ((frame != CartesianFrame::Base && frame != CartesianFrame::Tool) || + !target_twist.allFinite() || + (frame == CartesianFrame::Tool && !base_R_tool.allFinite())) { + throw std::invalid_argument("invalid S-curve target, frame or tool rotation"); + } + Twist target_base = target_twist; + if (frame == CartesianFrame::Tool) { + target_base.head<3>() = base_R_tool * target_twist.head<3>(); + target_base.tail<3>() = base_R_tool * target_twist.tail<3>(); + } + if (!target_base.allFinite() || !std::isfinite(target_base.head<3>().norm()) || + !std::isfinite(target_base.tail<3>().norm())) { + throw std::invalid_argument("S-curve target magnitude must be finite"); + } + auto staged = *this; + staged.twist_base_.head<3>() = planVelocity(staged.linear_velocity_, + staged.linear_direction_profile_, staged.current_linear_dir_base_, + target_base.head<3>(), dt, continuous_linear_reversal_); + staged.twist_base_.tail<3>() = planVelocity(staged.angular_velocity_, + staged.angular_direction_profile_, staged.current_angular_dir_base_, + target_base.tail<3>(), dt, false); + // Keep the public diagnostics based on actual output commands. + staged.acceleration_base_ = (staged.twist_base_ - twist_base_) / dt; + // Acceleration samples are averages over intervals, located at their centers. + staged.jerk_base_ = (staged.acceleration_base_ - acceleration_base_) / + (0.5 * previous_period_ + 0.5 * dt); + staged.previous_period_ = dt; + if (!staged.twist_base_.allFinite() || !staged.acceleration_base_.allFinite() || + !staged.jerk_base_.allFinite()) { + throw std::runtime_error("S-curve produced a non-finite command"); + } + *this = std::move(staged); + return twist_base_; +} + +bool SCurvePlanner::isMoving() const +{ + return linear_direction_profile_.active || angular_direction_profile_.active || + linear_velocity_.isMoving() || angular_velocity_.isMoving(); +} + +} // namespace cmvr diff --git a/cmvr-es/algorithms/planner/cartesian/s_curve/test/s_curve_planner_reversal_test.cpp b/cmvr-es/algorithms/planner/cartesian/s_curve/test/s_curve_planner_reversal_test.cpp new file mode 100644 index 00000000..29013d9f --- /dev/null +++ b/cmvr-es/algorithms/planner/cartesian/s_curve/test/s_curve_planner_reversal_test.cpp @@ -0,0 +1,320 @@ +#include +#include +#include +#include + +#include +#include "algorithms/planner/cartesian/s_curve/include/s_curve_planner.h" + +namespace cmvr { +namespace { +using Twist = SCurvePlanner::Twist; +constexpr double dt = .001; +Twist y(double v) { Twist t = Twist::Zero(); t.y() = v; return t; } +struct Motion { double peak{0}, reverse_time{-1}, return_time{-1}; }; +Motion reverse(bool continuous, int approach_ticks) { + SCurvePlanner planner; + planner.setLinearConstraints(.55, 5, 10); + planner.setContinuousLinearReversal(continuous); + planner.initialize(approach_ticks == 0 ? y(.08) : Twist::Zero()); + for (int i = 0; i < approach_ticks; ++i) planner.plan(y(.08), CartesianFrame::Base, dt, Eigen::Matrix3d::Identity()); + planner.setLinearConstraints(.55, 3, 10); + Motion result; + double position = 0; + for (int i = 1; i <= 1500; ++i) { + const auto v = planner.plan(y(-.08), CartesianFrame::Base, dt, Eigen::Matrix3d::Identity()); + position += v.y() * dt; + result.peak = std::max(result.peak, position); + if (v.y() < 0 && result.reverse_time < 0) result.reverse_time = i * dt; + if (result.reverse_time > 0 && position <= 0 && result.return_time < 0) result.return_time = i * dt; + if (continuous) { + EXPECT_LE(planner.getAccelerationBase().norm(), 3.0 + 1e-7); + EXPECT_LE(planner.getJerkBase().norm(), 10.0 + 1e-6); + EXPECT_NEAR(v.x(), 0, 1e-12); + EXPECT_NEAR(v.z(), 0, 1e-12); + } + } + EXPECT_NEAR(planner.getTwistBase().y(), -.08, 1e-9); + return result; +} +TEST(SCurvePlannerReversal, ContinuousReversalReducesTimeAndForwardTravel) { + for (const int ticks : {0, 80, 120}) { + SCOPED_TRACE(ticks); + const auto legacy = reverse(false, ticks); + const auto continuous = reverse(true, ticks); + EXPECT_GT(continuous.reverse_time, 0); + EXPECT_LT(continuous.reverse_time, legacy.reverse_time); + EXPECT_LT(continuous.return_time, legacy.return_time); + EXPECT_LT(continuous.peak, legacy.peak); + } +} +TEST(SCurvePlannerReversal, ExactZeroCrossingIsStillMovingAndKeepsAcceleration) { + SCurvePlanner planner; + planner.setLinearConstraints(1, 1, 4); + planner.initialize(y(.02)); + for (int i = 0; i < 100; ++i) planner.plan(y(-.02), CartesianFrame::Base, dt, Eigen::Matrix3d::Identity()); + EXPECT_NEAR(planner.getTwistBase().y(), 0, 1e-12); + EXPECT_TRUE(planner.isMoving()); + EXPECT_LT(planner.getAccelerationBase().y(), -.39); + EXPECT_LT(planner.plan(y(-.02), CartesianFrame::Base, dt, Eigen::Matrix3d::Identity()).y(), -.0003); +} +TEST(SCurvePlannerReversal, StopFromEitherDirectionSettlesWithoutReversing) { + for (double v : {.08, -.08}) { + SCurvePlanner planner; + planner.setLinearConstraints(1, 3, 10); + planner.initialize(y(v)); + for (int i = 0; i < 1000; ++i) { + EXPECT_GE(planner.plan(Twist::Zero(), CartesianFrame::Base, dt, Eigen::Matrix3d::Identity()).y() * v, -1e-12); + } + EXPECT_FALSE(planner.isMoving()); + EXPECT_NEAR(planner.getTwistBase().norm(), 0, 1e-12); + } +} +TEST(SCurvePlannerReversal, NonCollinearChangePreservesVectorAccelerationAndJerkLimits) { + for (bool continuous : {true, false}) { + for (int offset : {0, 3}) { + for (bool accelerating : {false, true}) { + SCOPED_TRACE(::testing::Message() << "continuous=" << continuous + << " angular=" << (offset == 3) << " accelerating=" << accelerating); + SCurvePlanner planner; + planner.setLinearConstraints(1, 3, 10); + planner.setAngularConstraints(1, 3, 10); + planner.setContinuousLinearReversal(continuous); + Twist initial = Twist::Zero(), target = Twist::Zero(); + initial[offset + 1] = .08; + target[offset] = .08; + if (accelerating) { + planner.initialize(); + planner.plan(initial, CartesianFrame::Base, dt, Eigen::Matrix3d::Identity()); + ASSERT_LT(planner.getTwistBase().norm(), 1e-3); + ASSERT_GT(planner.getAccelerationBase().norm(), 1e-3); + } else { + planner.initialize(initial); + } + double max_acceleration = 0, max_jerk = 0; + Twist previous = planner.getTwistBase(); + Twist previous_acceleration = planner.getAccelerationBase(); + for (int i = 0; i < 1000; ++i) { + const auto v = planner.plan(target, CartesianFrame::Base, dt, Eigen::Matrix3d::Identity()); + const Twist acceleration = (v - previous) / dt; + const Twist jerk = (acceleration - previous_acceleration) / dt; + EXPECT_LE(acceleration.norm(), 3 + 1e-6); + EXPECT_LE(jerk.norm(), 10 + 1e-5); + previous = v; + previous_acceleration = acceleration; + max_acceleration = std::max(max_acceleration, planner.getAccelerationBase().norm()); + max_jerk = std::max(max_jerk, planner.getJerkBase().norm()); + } + EXPECT_LE(max_acceleration, 3 + 1e-6); + EXPECT_LE(max_jerk, 10 + 1e-6); + EXPECT_NEAR((planner.getTwistBase() - target).norm(), 0, 1e-9); + + // Same-axis magnitude planning must keep moving when the target + // has the same direction, including legacy linear streaming. + target *= 1.5; + for (int i = 0; i < 500; ++i) { + EXPECT_GE(planner.plan(target, CartesianFrame::Base, dt, + Eigen::Matrix3d::Identity())[offset], .08 - 1e-9); + } + EXPECT_NEAR((planner.getTwistBase() - target).norm(), 0, 1e-9); + + if (offset == 3) { + target = -target; + max_acceleration = max_jerk = 0; + for (int i = 0; i < 1000; ++i) { + planner.plan(target, CartesianFrame::Base, dt, Eigen::Matrix3d::Identity()); + max_acceleration = std::max(max_acceleration, planner.getAccelerationBase().norm()); + max_jerk = std::max(max_jerk, planner.getJerkBase().norm()); + } + EXPECT_LE(max_acceleration, 3 + 1e-6); + EXPECT_LE(max_jerk, 10 + 1e-6); + EXPECT_NEAR((planner.getTwistBase() - target).norm(), 0, 1e-9); + } + } + } + } +} + +TEST(SCurvePlannerReversal, SmallDirectionStepAndRotatingToolDoNotJumpOrPeriodicallyStop) { + for (bool continuous : {true, false}) { + for (int offset : {0, 3}) { + for (double max_velocity : {.08, 1.}) { + SCOPED_TRACE(::testing::Message() << "continuous=" << continuous + << " angular=" << (offset == 3) << " vmax=" << max_velocity); + SCurvePlanner planner; + planner.setLinearConstraints(max_velocity, 3, 10); + planner.setAngularConstraints(max_velocity, 3, 10); + planner.setContinuousLinearReversal(continuous); + Twist target = Twist::Zero(); + target[offset] = .08; + planner.initialize(target); + Twist previous = target, previous_acceleration = Twist::Zero(); + double min_speed = .08; + for (int i = 0; i < 3000; ++i) { + // First reproduce the .01-rad step, then keep rotating the Tool. + const double angle = .01 + .2 * i * dt; + Eigen::Matrix3d rotation = Eigen::Matrix3d::Identity(); + rotation(0, 0) = rotation(1, 1) = std::cos(angle); + rotation(0, 1) = -std::sin(angle); + rotation(1, 0) = std::sin(angle); + const Twist v = planner.plan(target, CartesianFrame::Tool, dt, rotation); + const Twist a = (v - previous) / dt; + const Twist j = (a - previous_acceleration) / dt; + EXPECT_LE(v.norm(), max_velocity + 1e-9); + EXPECT_LE(a.norm(), 3 + 1e-6); + EXPECT_LE(j.norm(), 10 + 1e-5); + min_speed = std::min(min_speed, v.norm()); + previous = v; + previous_acceleration = a; + } + EXPECT_GT(min_speed, .072); + for (int i = 0; i < 1500; ++i) { + const Twist v = planner.plan(Twist::Zero(), CartesianFrame::Base, dt, + Eigen::Matrix3d::Identity()); + const Twist a = (v - previous) / dt; + EXPECT_LE(a.norm(), 3 + 1e-6); + EXPECT_LE(((a - previous_acceleration) / dt).norm(), 10 + 1e-5); + previous = v; + previous_acceleration = a; + } + EXPECT_NEAR(planner.getTwistBase().norm(), 0, 1e-10); + EXPECT_FALSE(planner.isMoving()); + } + } + } +} + +TEST(SCurvePlannerReversal, SwitchingToStreamingPreservesNegativePhysicalVelocity) { + for (const int reverse_ticks : {150, 250, 500}) { + SCOPED_TRACE(reverse_ticks); + SCurvePlanner reference; + reference.setLinearConstraints(1, 3, 10); + reference.initialize(y(.08)); + for (int i = 0; i < reverse_ticks; ++i) reference.plan(y(-.08), CartesianFrame::Base, dt, Eigen::Matrix3d::Identity()); + ASSERT_LT(reference.getTwistBase().y(), 0); + auto streaming = reference; + streaming.setContinuousLinearReversal(false); + EXPECT_NEAR((streaming.getTwistBase() - reference.getTwistBase()).norm(), 0, 1e-12); + for (int i = 0; i < 500; ++i) { + const auto expected = reference.plan(y(-.08), CartesianFrame::Base, dt, Eigen::Matrix3d::Identity()); + const auto actual = streaming.plan(y(-.08), CartesianFrame::Base, dt, Eigen::Matrix3d::Identity()); + EXPECT_NEAR((actual - expected).norm(), 0, 1e-9); + EXPECT_LE(streaming.getJerkBase().norm(), 10 + 1e-6); + } + } +} + +TEST(SCurvePlannerReversal, SmallDirectionChangeWithLowJerkEventuallyReachesTarget) { + SCurvePlanner planner; + planner.setLinearConstraints(1, 3, .01); + planner.initialize(y(.08)); + Twist target = Twist::Zero(); + target.x() = .08 * std::sin(1e-4); + target.y() = .08 * std::cos(1e-4); + for (int i = 0; i < 1000; ++i) { + planner.plan(target, CartesianFrame::Base, dt, Eigen::Matrix3d::Identity()); + EXPECT_LE(planner.getAccelerationBase().norm(), 3 + 1e-7); + EXPECT_LE(planner.getJerkBase().norm(), .01 + 1e-7); + } + EXPECT_NEAR((planner.getTwistBase() - target).norm(), 0, 1e-10); +} + +TEST(SCurvePlannerReversal, ChangingPeriodUsesAccelerationSampleTimesForJerk) { + SCurvePlanner planner; + planner.setLinearConstraints(1, 3, 10); + for (int i = 0; i < 100; ++i) { + const double period = i % 2 ? .0005 : .001; + planner.plan(y(.08), CartesianFrame::Base, period, Eigen::Matrix3d::Identity()); + EXPECT_NEAR(planner.getJerkBase().y(), 10, 1e-7); + } +} + +TEST(SCurvePlannerReversal, SmallNonzeroAccelerationCannotMakeInvalidProfileLookSettled) { + SCurvePlanner actual; + actual.setLinearConstraints(.05, 1e-6, .001); + actual.initialize(y(.0499995)); + actual.plan(y(.05), CartesianFrame::Base, dt, Eigen::Matrix3d::Identity()); + auto reference = actual; + // Removing the small acceleration with this jerk would exceed vmax. + // A numerical "near zero" test must not accept and freeze this state. + EXPECT_THROW(actual.setLinearConstraints(.05, 1e-6, 1e-8), std::runtime_error); + for (int i = 0; i < 1000; ++i) { + const Twist a = actual.plan(y(.05), CartesianFrame::Base, dt, Eigen::Matrix3d::Identity()); + const Twist b = reference.plan(y(.05), CartesianFrame::Base, dt, Eigen::Matrix3d::Identity()); + EXPECT_DOUBLE_EQ((a - b).norm(), 0); + EXPECT_LE(actual.getJerkBase().norm(), .001 + 1e-7); + } + EXPECT_NEAR(actual.getTwistBase().y(), .05, 1e-12); +} + +TEST(SCurvePlannerReversal, InvalidInputThrowsWithoutChangingCurrentOrFutureState) { + SCurvePlanner seed; + seed.setLinearConstraints(1, 3, 10); + seed.setAngularConstraints(1, 3, 10); + Twist target = y(.08); + target[5] = .12; + for (int i = 0; i < 80; ++i) + seed.plan(target, CartesianFrame::Base, dt, Eigen::Matrix3d::Identity()); + + const auto expect_unchanged = [&](auto operation) { + auto expected = seed; + auto actual = seed; + EXPECT_THROW(operation(actual), std::invalid_argument); + const auto compare_state = [&] { + EXPECT_DOUBLE_EQ((actual.getTwistBase() - expected.getTwistBase()).norm(), 0); + EXPECT_DOUBLE_EQ((actual.getAccelerationBase() - expected.getAccelerationBase()).norm(), 0); + EXPECT_DOUBLE_EQ((actual.getJerkBase() - expected.getJerkBase()).norm(), 0); + EXPECT_EQ(actual.isMoving(), expected.isMoving()); + EXPECT_EQ(actual.continuousLinearReversalEnabled(), expected.continuousLinearReversalEnabled()); + }; + compare_state(); + for (int i = 0; i < 200; ++i) { + const auto expected_twist = expected.plan(target, CartesianFrame::Base, dt, Eigen::Matrix3d::Identity()); + const auto actual_twist = actual.plan(target, CartesianFrame::Base, dt, Eigen::Matrix3d::Identity()); + EXPECT_DOUBLE_EQ((actual_twist - expected_twist).norm(), 0); + compare_state(); + } + }; + const double nan = std::numeric_limits::quiet_NaN(); + const double inf = std::numeric_limits::infinity(); + for (double invalid : {-1., 0., nan, inf}) { + SCOPED_TRACE(::testing::Message() << "invalid=" << invalid); + for (int index = 0; index < 3; ++index) { + SCOPED_TRACE(index); + double limits[] = {1, 3, 10}; + limits[index] = invalid; + expect_unchanged([&](auto& p) { p.setLinearConstraints(limits[0], limits[1], limits[2]); }); + expect_unchanged([&](auto& p) { p.setAngularConstraints(limits[0], limits[1], limits[2]); }); + } + expect_unchanged([&](auto& p) { p.plan(target, CartesianFrame::Base, invalid, Eigen::Matrix3d::Identity()); }); + if (invalid != 0) { + expect_unchanged([&](auto& p) { p.setLinearTargetReplanThreshold(invalid); }); + expect_unchanged([&](auto& p) { p.setAngularTargetReplanThreshold(invalid); }); + } + } + for (double invalid : {nan, inf}) { + for (int index : {0, 5}) { + Twist invalid_twist = target; + invalid_twist[index] = invalid; + expect_unchanged([&](auto& p) { p.initialize(invalid_twist); }); + expect_unchanged([&](auto& p) { p.plan(invalid_twist, CartesianFrame::Base, dt, Eigen::Matrix3d::Identity()); }); + } + Eigen::Matrix3d invalid_rotation = Eigen::Matrix3d::Identity(); + invalid_rotation(1, 2) = invalid; + expect_unchanged([&](auto& p) { p.plan(target, CartesianFrame::Tool, dt, invalid_rotation); }); + } + // Over-limit initialization must not clamp only the internal scalar or + // reset linear motion before discovering an invalid angular component. + for (int index : {0, 5}) { + Twist initial = y(.2); + initial[index] = 2; + expect_unchanged([&](auto& p) { p.initialize(initial); }); + } + expect_unchanged([&](auto& p) { p.setLinearConstraints(.001, 3, 10); }); + expect_unchanged([&](auto& p) { p.setLinearConstraints(1, .01, 10); }); + expect_unchanged([&](auto& p) { p.plan(target, CartesianFrame::Base, 1e-300, Eigen::Matrix3d::Identity()); }); + expect_unchanged([&](auto& p) { p.plan(target, static_cast(9), dt, Eigen::Matrix3d::Identity()); }); +} + +} +} diff --git a/cmvr-es/algorithms/planner/joint/joint_path_planner.h b/cmvr-es/algorithms/planner/joint/joint_path_planner.h new file mode 100644 index 00000000..fc2f2bdc --- /dev/null +++ b/cmvr-es/algorithms/planner/joint/joint_path_planner.h @@ -0,0 +1,62 @@ +#ifndef CMVR_ES_JOINT_PATH_PLANNER_H +#define CMVR_ES_JOINT_PATH_PLANNER_H + +#include +#include +#include +#include + +namespace cmvr { + +using JointPath = std::vector>; + +struct JointPathRequest { + // All vectors use the same joint order and radians. Bounded revolute joints + // only; continuous joints require a different state space. + std::vector start; + std::vector goal; + std::vector lower_bounds; + std::vector upper_bounds; + + // Required: return true only for a valid configuration. Capture a stable + // collision scene for the entire request. Callbacks run on the calling + // thread; concurrent requests must not share a mutable collision checker. + std::function&)> is_state_valid; + std::function is_cancelled; +}; + +enum class JointPathStatus { + Success, + InvalidRequest, + InvalidStart, + InvalidGoal, + TimedOut, + Cancelled, + ValidationError, + PlanningFailed, +}; + +struct JointPathResult { + JointPathStatus status{JointPathStatus::InvalidRequest}; + // Empty on failure. Success contains both exact endpoints, without timing, + // smoothing, or motor commands. An unchanged target contains one point. + JointPath waypoints; + std::string message; + double planning_time_s{0.0}; + std::size_t validity_checks{0}; + + bool ok() const { return status == JointPathStatus::Success; } +}; + +class JointPathPlanner { +public: + virtual ~JointPathPlanner() = default; + + // Synchronous planning. Cancellation is cooperative: callbacks must return + // promptly and cannot be forcibly interrupted. + virtual JointPathResult plan(const JointPathRequest& request) const = 0; +}; + +} // namespace cmvr + +#endif // CMVR_ES_JOINT_PATH_PLANNER_H diff --git a/cmvr-es/algorithms/planner/joint/joint_path_planner_factory.h b/cmvr-es/algorithms/planner/joint/joint_path_planner_factory.h new file mode 100644 index 00000000..b16a3452 --- /dev/null +++ b/cmvr-es/algorithms/planner/joint/joint_path_planner_factory.h @@ -0,0 +1,48 @@ +#ifndef CMVR_ES_JOINT_PATH_PLANNER_FACTORY_H +#define CMVR_ES_JOINT_PATH_PLANNER_FACTORY_H + +#include +#include + +#include "algorithms/planner/joint/joint_path_planner.h" +#include "algorithms/planner/joint/ompl/include/rrt_connect.h" +#include "cmvr/config/joint_motion_config.pb.h" + +namespace cmvr { + +class JointPathPlannerFactory { +public: + static std::shared_ptr create( + const config::JointPathConfig& cfg) + { + switch (cfg.algorithm()) { + case config::RRT_CONNECT: { + const auto& rrt_connect = cfg.rrt_connect(); + RrtConnectOptions options; + if (rrt_connect.has_timeout_s()) { + options.timeout_s = rrt_connect.timeout_s(); + } + if (rrt_connect.has_range_rad()) { + options.range_rad = rrt_connect.range_rad(); + } + if (rrt_connect.has_collision_check_step_rad()) { + options.collision_check_step_rad = rrt_connect.collision_check_step_rad(); + } + if (!std::isfinite(options.timeout_s) || options.timeout_s <= 0.0 || + !std::isfinite(options.range_rad) || options.range_rad <= 0.0 || + !std::isfinite(options.collision_check_step_rad) || + options.collision_check_step_rad <= 0.0) { + return nullptr; + } + return std::make_shared(options); + } + case config::JOINT_PATH_ALGORITHM_UNKNOWN: + default: + return nullptr; + } + } +}; + +} // namespace cmvr + +#endif // CMVR_ES_JOINT_PATH_PLANNER_FACTORY_H diff --git a/cmvr-es/algorithms/planner/joint/ompl/include/rrt_connect.h b/cmvr-es/algorithms/planner/joint/ompl/include/rrt_connect.h new file mode 100644 index 00000000..f533842b --- /dev/null +++ b/cmvr-es/algorithms/planner/joint/ompl/include/rrt_connect.h @@ -0,0 +1,28 @@ +#pragma once + +#include "algorithms/planner/joint/joint_path_planner.h" + +namespace cmvr { + +struct RrtConnectOptions { + double timeout_s{1.0}; + // Maximum tree extension in the Euclidean joint-space metric. + double range_rad{0.2}; + // Maximum per-joint increment between collision samples on each edge. + // This is discrete checking, not a continuous collision guarantee. + double collision_check_step_rad{0.02}; +}; + +class RrtConnect final : public JointPathPlanner { +public: + explicit RrtConnect(const RrtConnectOptions& options = {}); + + // Each call owns a fresh OMPL context. Timeout/cancellation are cooperative: + // user callbacks must return promptly and cannot be forcibly interrupted. + JointPathResult plan(const JointPathRequest& request) const override; + +private: + RrtConnectOptions options_; +}; + +} // namespace cmvr diff --git a/cmvr-es/algorithms/planner/joint/ompl/src/rrt_connect.cpp b/cmvr-es/algorithms/planner/joint/ompl/src/rrt_connect.cpp new file mode 100644 index 00000000..8d287459 --- /dev/null +++ b/cmvr-es/algorithms/planner/joint/ompl/src/rrt_connect.cpp @@ -0,0 +1,262 @@ +#include "algorithms/planner/joint/ompl/include/rrt_connect.h" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace cmvr { +namespace { + +namespace ob = ompl::base; +namespace og = ompl::geometric; +using Clock = std::chrono::steady_clock; + +constexpr double kMaxSegmentsPerEdge = 1000000.0; + +// Use an absolute, per-joint resolution instead of a fraction of the entire +// state-space extent, so adding joints does not coarsen collision checking. +class JointMotionValidator final : public ob::MotionValidator { +public: + JointMotionValidator(const ob::SpaceInformationPtr& si, double step) + : ob::MotionValidator(si), step_(step) {} + + bool checkMotion(const ob::State* from, const ob::State* to) const override + { + std::pair last_valid{nullptr, 0.0}; + return checkMotion(from, to, last_valid); + } + + bool checkMotion(const ob::State* from, const ob::State* to, + std::pair& last_valid) const override + { + const auto* a = from->as(); + const auto* b = to->as(); + double delta = 0.0; + for (unsigned int i = 0; i < si_->getStateDimension(); ++i) { + delta = std::max(delta, std::abs(b->values[i] - a->values[i])); + } + const auto segments = static_cast( + std::max(1.0, std::ceil(delta / step_))); + ob::ScopedState<> sample(si_->getStateSpace()); + for (std::size_t i = 1; i <= segments; ++i) { + const double fraction = static_cast(i) / segments; + si_->getStateSpace()->interpolate(from, to, fraction, sample.get()); + if (!si_->isValid(sample.get())) { + last_valid.second = static_cast(i - 1) / segments; + if (last_valid.first) { + si_->getStateSpace()->interpolate( + from, to, last_valid.second, last_valid.first); + } + ++invalid_; + return false; + } + } + ++valid_; + return true; + } + +private: + double step_; +}; + +bool positiveFinite(double value) +{ + return std::isfinite(value) && value > 0.0; +} + +} // namespace + +RrtConnect::RrtConnect(const RrtConnectOptions& options) + : options_(options) +{ +} + +JointPathResult RrtConnect::plan(const JointPathRequest& request) const +{ + const auto begin = Clock::now(); + JointPathResult result; + const auto finish = [&](JointPathStatus status, const std::string& message) { + result.status = status; + result.message = message; + result.planning_time_s = std::chrono::duration(Clock::now() - begin).count(); + if (status != JointPathStatus::Success) { + result.waypoints.clear(); + } + return result; + }; + + const auto dof = request.start.size(); + if (dof == 0 || dof > std::numeric_limits::max() || + request.goal.size() != dof || request.lower_bounds.size() != dof || + request.upper_bounds.size() != dof || !request.is_state_valid) { + return finish(JointPathStatus::InvalidRequest, + "Matching non-empty joint vectors and a validity callback are required"); + } + if (!positiveFinite(options_.timeout_s) || !positiveFinite(options_.range_rad) || + !positiveFinite(options_.collision_check_step_rad)) { + return finish(JointPathStatus::InvalidRequest, + "Timeout, range, and collision checking step must be finite and positive"); + } + double extent = 0.0; + for (std::size_t i = 0; i < dof; ++i) { + const double lower = request.lower_bounds[i]; + const double upper = request.upper_bounds[i]; + const double width = upper - lower; + if (!std::isfinite(lower) || !std::isfinite(upper) || + !positiveFinite(width) || + width / options_.collision_check_step_rad > kMaxSegmentsPerEdge || + !std::isfinite(request.start[i]) || !std::isfinite(request.goal[i])) { + return finish(JointPathStatus::InvalidRequest, + "Joint values/bounds are invalid or checking resolution is too small"); + } + extent = std::hypot(extent, width); + } + // OMPL's real-vector metric squares individual joint differences. + if (!std::isfinite(extent) || extent > std::sqrt(std::numeric_limits::max())) { + return finish(JointPathStatus::InvalidRequest, "Joint-space extent is too large"); + } + const auto in_bounds = [&](const std::vector& q) { + for (std::size_t i = 0; i < dof; ++i) { + if (q[i] < request.lower_bounds[i] || q[i] > request.upper_bounds[i]) { + return false; + } + } + return true; + }; + if (!in_bounds(request.start)) { + return finish(JointPathStatus::InvalidStart, "Start is outside joint limits"); + } + if (!in_bounds(request.goal)) { + return finish(JointPathStatus::InvalidGoal, "Goal is outside joint limits"); + } + + bool cancelled = false; + bool timed_out = false; + std::string callback_error; + const auto stopped = [&] { + if (cancelled || timed_out || !callback_error.empty()) { + return true; + } + try { + cancelled = request.is_cancelled && request.is_cancelled(); + } catch (const std::exception& exception) { + callback_error = std::string("Cancellation callback failed: ") + exception.what(); + } catch (...) { + callback_error = "Cancellation callback failed"; + } + timed_out = std::chrono::duration(Clock::now() - begin).count() >= options_.timeout_s; + return cancelled || timed_out || !callback_error.empty(); + }; + const auto stop_result = [&] { + if (!callback_error.empty()) { + return finish(JointPathStatus::ValidationError, callback_error); + } + return cancelled ? finish(JointPathStatus::Cancelled, "Planning cancelled") + : finish(JointPathStatus::TimedOut, "Planning time budget exhausted"); + }; + // Never let user exceptions unwind through OMPL's search allocations. + const auto valid = [&](const std::vector& q) { + if (stopped() || !in_bounds(q)) { + return false; + } + bool accepted = false; + try { + ++result.validity_checks; + accepted = request.is_state_valid(q); + } catch (const std::exception& exception) { + callback_error = std::string("Validity callback failed: ") + exception.what(); + } catch (...) { + callback_error = "Validity callback failed"; + } + return !stopped() && accepted; + }; + + if (!valid(request.start)) { + return stopped() ? stop_result() + : finish(JointPathStatus::InvalidStart, "Start failed validity checking"); + } + if (!valid(request.goal)) { + return stopped() ? stop_result() + : finish(JointPathStatus::InvalidGoal, "Goal failed validity checking"); + } + if (request.start == request.goal) { + result.waypoints.push_back(request.start); + return finish(JointPathStatus::Success, "Start already equals goal"); + } + + try { + auto space = std::make_shared(static_cast(dof)); + ob::RealVectorBounds bounds(static_cast(dof)); + bounds.low = request.lower_bounds; + bounds.high = request.upper_bounds; + space->setBounds(bounds); + + og::SimpleSetup setup(space); + setup.setStateValidityChecker([&](const ob::State* state) { + const auto* values = state->as()->values; + return valid(std::vector(values, values + dof)); + }); + setup.getSpaceInformation()->setMotionValidator( + std::make_shared( + setup.getSpaceInformation(), options_.collision_check_step_rad)); + ob::ScopedState<> start(space), goal(space); + for (std::size_t i = 0; i < dof; ++i) { + start[i] = request.start[i]; + goal[i] = request.goal[i]; + } + // // 优先直连,整段通过现有碰撞检测后直接返回。 + // setup.getSpaceInformation()->setup(); + // const bool direct = setup.getSpaceInformation()->checkMotion(start.get(), goal.get()); + // if (stopped()) { + // return stop_result(); + // } + // if (direct) { + // result.waypoints = {request.start, request.goal}; + // return finish(JointPathStatus::Success, "Direct joint path found"); + // } + + setup.setStartAndGoalStates(start, goal); + auto planner = std::make_shared(setup.getSpaceInformation()); + planner->setRange(options_.range_rad); + setup.setPlanner(planner); + const auto status = setup.solve(ob::PlannerTerminationCondition(stopped)); + if (stopped()) { + return stop_result(); + } + // PlannerStatus::operator bool also accepts approximate solutions. + if (status != ob::PlannerStatus::EXACT_SOLUTION || !setup.haveExactSolutionPath()) { + return finish(JointPathStatus::PlanningFailed, "No exact path to the requested goal"); + } + auto& path = setup.getSolutionPath(); + setup.getPathSimplifier()->ropeShortcutPath(path); + if (!path.check()) { + return stopped() ? stop_result() + : finish(JointPathStatus::PlanningFailed, "Final path failed validation"); + } + for (const auto* state : path.getStates()) { + const auto* values = state->as()->values; + result.waypoints.emplace_back(values, values + dof); + } + if (result.waypoints.empty() || result.waypoints.front() != request.start || + result.waypoints.back() != request.goal) { + return finish(JointPathStatus::PlanningFailed, "Path endpoints do not match the request"); + } + if (stopped()) { + return stop_result(); + } + return finish(JointPathStatus::Success, "Exact RRTConnect path found"); + } catch (const std::exception& exception) { + return finish(JointPathStatus::PlanningFailed, exception.what()); + } +} + +} // namespace cmvr diff --git a/cmvr-es/algorithms/planner/joint/ompl/test/rrt_connect_self_collision_test.cpp b/cmvr-es/algorithms/planner/joint/ompl/test/rrt_connect_self_collision_test.cpp new file mode 100644 index 00000000..ca36bba8 --- /dev/null +++ b/cmvr-es/algorithms/planner/joint/ompl/test/rrt_connect_self_collision_test.cpp @@ -0,0 +1,222 @@ +#include "algorithms/planner/joint/joint_path_planner_factory.h" +#include "algorithms/collision_detection/include/collision_checker.h" + +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace cmvr { +namespace { + +class RrtConnectSelfCollisionTest : public ::testing::Test { +protected: + void SetUp() override + { + const std::vector joints{ + "right_arm_J1", "right_arm_J2", "right_arm_J3", "right_arm_J4", + "right_arm_J5", "right_arm_J6", "right_arm_J7"}; + CollisionOptions options; + options.ignored_pairs = {{"arm_link_5_2", "arm_link_7_2"}, + {"body_link", "arm_link_2_2"}}; + std::string error; + ASSERT_TRUE(checker_.init( + std::string(CMVR_ES_SOURCE_DIR) + "/model/gen2/collision/robot_collision.urdf", + joints, options, &error)) << error; + request_.start = {0.0, -0.50, 1.5708, 1.5708, -0.041, 0.0, 0.0}; + request_.goal = request_.start; + request_.goal[0] += 0.1; + // These seven bounded joints in the Gen2 collision URDF use +/- pi. + request_.lower_bounds.assign(7, -3.141592653589793); + request_.upper_bounds.assign(7, 3.141592653589793); + request_.is_state_valid = [&](const auto& q) { + const auto result = checker_.check(q); + return result.valid && !result.in_collision && result.minimum_distance_m > 0.02; + }; + cfg_.set_algorithm(config::RRT_CONNECT); + cfg_.mutable_rrt_connect()->set_timeout_s(2.0); + cfg_.mutable_rrt_connect()->set_collision_check_step_rad(0.01); + } + + CollisionChecker checker_; + JointPathRequest request_; + config::JointPathConfig cfg_; +}; + +TEST_F(RrtConnectSelfCollisionTest, PlansWithExistingGen2CollisionChecker) +{ + ASSERT_TRUE(request_.is_state_valid(request_.start)); + ASSERT_TRUE(request_.is_state_valid(request_.goal)); + const auto planner = JointPathPlannerFactory::create(cfg_); + ASSERT_NE(planner, nullptr); + const auto result = planner->plan(request_); + ASSERT_TRUE(result.ok()) << result.message; + ASSERT_GE(result.waypoints.size(), 2U); + EXPECT_EQ(result.waypoints.front(), request_.start); + EXPECT_EQ(result.waypoints.back(), request_.goal); + for (std::size_t i = 1; i < result.waypoints.size(); ++i) { + for (int sample = 0; sample <= 100; ++sample) { + std::vector q(7); + for (std::size_t joint = 0; joint < 7; ++joint) { + q[joint] = result.waypoints[i - 1][joint] + + (result.waypoints[i][joint] - result.waypoints[i - 1][joint]) * sample / 100.0; + } + EXPECT_TRUE(request_.is_state_valid(q)) << "Invalid edge " << i; + } + } +} + +TEST_F(RrtConnectSelfCollisionTest, RejectsKnownGen2CollisionPose) +{ + request_.goal = {-0.42656969579233, 1.41426471041774, -2.67949400419915, + 2.45814854129954, -2.35907388079205, 1.14125209449898, + 1.53232912981414}; + const auto planner = JointPathPlannerFactory::create(cfg_); + ASSERT_NE(planner, nullptr); + const auto result = planner->plan(request_); + EXPECT_EQ(result.status, JointPathStatus::InvalidGoal); + EXPECT_TRUE(result.waypoints.empty()); +} + +class RrtConnectObstacleTest : public ::testing::Test { +protected: + void SetUp() override + { + char path[] = "/tmp/cmvr_rrt_obstacle_XXXXXX"; + const int fd = mkstemp(path); + ASSERT_GE(fd, 0); + close(fd); + urdf_path_ = path; + std::ofstream urdf(urdf_path_); + ASSERT_TRUE(urdf.is_open()); + // A planar test mechanism makes obstacle clearance independently + // checkable: its tool center is exactly (q[0], q[1], 0). + urdf << R"( + + + + + + + + + + + + + +)"; + urdf.close(); + ASSERT_TRUE(urdf.good()); + + BoxObstacle obstacle; + obstacle.name = "blocking_box"; + obstacle.frame_id = "base"; + obstacle.size_m = Eigen::Vector3d(0.35, 0.70, 0.20); + CollisionOptions options; + options.obstacles.push_back(obstacle); + std::string error; + ASSERT_TRUE(checker_.init(urdf_path_, {"x", "y"}, options, &error)) << error; + ASSERT_EQ(checker_.activePairCount(), 1U); + + request_.start = {-0.8, 0.0}; + request_.goal = {0.8, 0.0}; + request_.lower_bounds = {-1.0, -1.0}; + request_.upper_bounds = {1.0, 1.0}; + request_.is_state_valid = [&](const auto& q) { + const auto result = checker_.check(q); + // Preserve 5 mm beyond the required clearance to account for + // finite motion-validation spacing at the obstacle corners. + return result.valid && !result.in_collision && + result.minimum_distance_m > kClearanceM + 0.005; + }; + cfg_.set_algorithm(config::RRT_CONNECT); + cfg_.mutable_rrt_connect()->set_timeout_s(2.0); + cfg_.mutable_rrt_connect()->set_range_rad(0.2); + cfg_.mutable_rrt_connect()->set_collision_check_step_rad(0.001); + } + + void TearDown() override + { + if (!urdf_path_.empty()) { + std::remove(urdf_path_.c_str()); + } + } + + static constexpr double kClearanceM = 0.02; + std::string urdf_path_; + CollisionChecker checker_; + JointPathRequest request_; + config::JointPathConfig cfg_; +}; + +TEST_F(RrtConnectObstacleTest, PlansAroundBoxAndKeepsClearanceAfterShortcut) +{ + ASSERT_TRUE(request_.is_state_valid(request_.start)); + ASSERT_TRUE(request_.is_state_valid(request_.goal)); + const auto blocked = checker_.check(std::vector{0.0, 0.0}); + ASSERT_TRUE(blocked.valid) << blocked.error; + ASSERT_TRUE(blocked.in_collision); // The direct start-to-goal segment is blocked. + + const auto planner = JointPathPlannerFactory::create(cfg_); + ASSERT_NE(planner, nullptr); + const auto result = planner->plan(request_); // Includes ropeShortcutPath. + ASSERT_TRUE(result.ok()) << result.message; + ASSERT_GT(result.waypoints.size(), 2U); + EXPECT_EQ(result.waypoints.front(), request_.start); + EXPECT_EQ(result.waypoints.back(), request_.goal); + + for (std::size_t edge = 1; edge < result.waypoints.size(); ++edge) { + const auto& a = result.waypoints[edge - 1]; + const auto& b = result.waypoints[edge]; + const double extent = std::max(std::abs(b[0] - a[0]), std::abs(b[1] - a[1])); + const int samples = std::max(1, static_cast(std::ceil(extent / 0.0005))); + for (int sample = 0; sample <= samples; ++sample) { + const double ratio = static_cast(sample) / samples; + const std::vector q{a[0] + (b[0] - a[0]) * ratio, + a[1] + (b[1] - a[1]) * ratio}; + const auto collision = checker_.check(q); + ASSERT_TRUE(collision.valid) << collision.error; + ASSERT_FALSE(collision.in_collision) << "edge=" << edge << ", sample=" << sample; + EXPECT_GT(collision.minimum_distance_m, kClearanceM) + << "edge=" << edge << ", sample=" << sample; + // Independent axis-aligned box distance, without the checker. + const double dx = std::max(0.0, std::abs(q[0]) - 0.225); + const double dy = std::max(0.0, std::abs(q[1]) - 0.400); + EXPECT_GT(std::hypot(dx, dy), kClearanceM) + << "edge=" << edge << ", sample=" << sample; + } + } +} + +TEST_F(RrtConnectObstacleTest, RejectsStartAndGoalInsideObstacle) +{ + const auto planner = JointPathPlannerFactory::create(cfg_); + ASSERT_NE(planner, nullptr); + + request_.start = {0.0, 0.0}; + auto result = planner->plan(request_); + EXPECT_EQ(result.status, JointPathStatus::InvalidStart); + EXPECT_TRUE(result.waypoints.empty()); + + request_.start = {-0.8, 0.0}; + request_.goal = {0.0, 0.0}; + result = planner->plan(request_); + EXPECT_EQ(result.status, JointPathStatus::InvalidGoal); + EXPECT_TRUE(result.waypoints.empty()); +} + +} // namespace +} // namespace cmvr + +int main(int argc, char** argv) +{ + ompl::RNG::setSeed(42); + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/cmvr-es/algorithms/planner/joint/ompl/test/rrt_connect_test.cpp b/cmvr-es/algorithms/planner/joint/ompl/test/rrt_connect_test.cpp new file mode 100644 index 00000000..3a257642 --- /dev/null +++ b/cmvr-es/algorithms/planner/joint/ompl/test/rrt_connect_test.cpp @@ -0,0 +1,304 @@ +#include "algorithms/planner/joint/joint_path_planner_factory.h" +#include "cmvr/config/arm_config/arm_config.pb.h" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace cmvr { +namespace { + +config::JointPathConfig defaultRrtConnectConfig() +{ + config::JointPathConfig cfg; + cfg.set_algorithm(config::RRT_CONNECT); + return cfg; +} + +JointPathRequest freeSpaceRequest(std::size_t dof = 7) +{ + JointPathRequest request; + request.start.assign(dof, -0.7); + request.goal.assign(dof, 0.7); + request.lower_bounds.assign(dof, -1.0); + request.upper_bounds.assign(dof, 1.0); + request.is_state_valid = [](const auto&) { return true; }; + return request; +} + +void expectValidPath(const JointPathResult& result, const JointPathRequest& request) +{ + ASSERT_TRUE(result.ok()) << result.message; + ASSERT_GE(result.waypoints.size(), 2U); + EXPECT_EQ(result.waypoints.front(), request.start); + EXPECT_EQ(result.waypoints.back(), request.goal); + for (std::size_t i = 1; i < result.waypoints.size(); ++i) { + const auto& a = result.waypoints[i - 1]; + const auto& b = result.waypoints[i]; + ASSERT_EQ(a.size(), request.start.size()); + ASSERT_EQ(b.size(), request.start.size()); + double distance = 0.0; + for (std::size_t joint = 0; joint < a.size(); ++joint) { + distance = std::max(distance, std::abs(b[joint] - a[joint])); + } + const auto count = static_cast(std::ceil(distance / 0.002)) + 1; + for (std::size_t sample = 0; sample <= count; ++sample) { + std::vector q(a.size()); + for (std::size_t joint = 0; joint < q.size(); ++joint) { + q[joint] = a[joint] + (b[joint] - a[joint]) * sample / count; + EXPECT_GE(q[joint], request.lower_bounds[joint]); + EXPECT_LE(q[joint], request.upper_bounds[joint]); + } + ASSERT_TRUE(request.is_state_valid(q)) << "Invalid interior of edge " << i; + } + } +} + +TEST(RrtConnectTest, PlansBoundedSevenJointPath) +{ + const auto request = freeSpaceRequest(); + const std::shared_ptr planner = + JointPathPlannerFactory::create(defaultRrtConnectConfig()); + ASSERT_NE(planner, nullptr); + const auto result = planner->plan(request); + expectValidPath(result, request); + EXPECT_GT(result.validity_checks, 2U); +} + +TEST(RrtConnectTest, RoutesAroundBlockedDirectConnection) +{ + auto request = freeSpaceRequest(2); + request.start = {-0.8, 0.0}; + request.goal = {0.8, 0.0}; + request.is_state_valid = [](const auto& q) { + return std::abs(q[0]) >= 0.2 || std::abs(q[1]) >= 0.5; + }; + ASSERT_FALSE(request.is_state_valid({0.0, 0.0})); + auto cfg = defaultRrtConnectConfig(); + cfg.mutable_rrt_connect()->set_timeout_s(2.0); + cfg.mutable_rrt_connect()->set_collision_check_step_rad(0.005); + const auto planner = JointPathPlannerFactory::create(cfg); + ASSERT_NE(planner, nullptr); + expectValidPath(planner->plan(request), request); +} + +TEST(RrtConnectTest, RejectsBlockedEdgesEvenWithValidEndpoints) +{ + auto request = freeSpaceRequest(1); + request.is_state_valid = [](const auto& q) { return std::abs(q[0]) >= 0.05; }; + ASSERT_TRUE(request.is_state_valid(request.start)); + ASSERT_TRUE(request.is_state_valid(request.goal)); + auto cfg = defaultRrtConnectConfig(); + cfg.mutable_rrt_connect()->set_timeout_s(0.03); + cfg.mutable_rrt_connect()->set_range_rad(2.0); + cfg.mutable_rrt_connect()->set_collision_check_step_rad(0.01); + const auto planner = JointPathPlannerFactory::create(cfg); + ASSERT_NE(planner, nullptr); + const auto result = planner->plan(request); + EXPECT_EQ(result.status, JointPathStatus::TimedOut); + EXPECT_TRUE(result.waypoints.empty()); +} + +TEST(RrtConnectTest, RequiresExplicitValidityChecker) +{ + auto request = freeSpaceRequest(); + request.is_state_valid = {}; + EXPECT_EQ(RrtConnect{}.plan(request).status, JointPathStatus::InvalidRequest); +} + +TEST(RrtConnectTest, RejectsMalformedJointVectorsAndBounds) +{ + RrtConnect planner; + auto request = freeSpaceRequest(); + request.goal.pop_back(); + EXPECT_EQ(planner.plan(request).status, JointPathStatus::InvalidRequest); + request = freeSpaceRequest(); + request.upper_bounds[0] = request.lower_bounds[0]; + EXPECT_EQ(planner.plan(request).status, JointPathStatus::InvalidRequest); + request = freeSpaceRequest(); + request.start[0] = std::numeric_limits::quiet_NaN(); + EXPECT_EQ(planner.plan(request).status, JointPathStatus::InvalidRequest); + request = freeSpaceRequest(); + request.upper_bounds[0] = std::numeric_limits::infinity(); + EXPECT_EQ(planner.plan(request).status, JointPathStatus::InvalidRequest); + EXPECT_EQ(planner.plan(freeSpaceRequest(0)).status, JointPathStatus::InvalidRequest); +} + +TEST(RrtConnectTest, RejectsInvalidOptions) +{ + const auto request = freeSpaceRequest(); + for (double value : {0.0, -1.0, std::numeric_limits::infinity(), + std::numeric_limits::quiet_NaN()}) { + for (int field = 0; field < 3; ++field) { + RrtConnectOptions options; + auto cfg = defaultRrtConnectConfig(); + if (field == 0) { + options.timeout_s = value; + cfg.mutable_rrt_connect()->set_timeout_s(value); + } + if (field == 1) { + options.range_rad = value; + cfg.mutable_rrt_connect()->set_range_rad(value); + } + if (field == 2) { + options.collision_check_step_rad = value; + cfg.mutable_rrt_connect()->set_collision_check_step_rad(value); + } + EXPECT_EQ(JointPathPlannerFactory::create(cfg), nullptr); + EXPECT_EQ(RrtConnect{options}.plan(request).status, + JointPathStatus::InvalidRequest); + } + } + RrtConnectOptions options; + options.collision_check_step_rad = 1e-12; + EXPECT_EQ(RrtConnect{options}.plan(request).status, + JointPathStatus::InvalidRequest); +} + +TEST(RrtConnectTest, DoesNotClampOutOfBoundsEndpoints) +{ + auto request = freeSpaceRequest(); + request.start[0] = -1.1; + const auto start = RrtConnect{}.plan(request); + EXPECT_EQ(start.status, JointPathStatus::InvalidStart); + EXPECT_TRUE(start.waypoints.empty()); + request = freeSpaceRequest(); + request.goal[0] = 1.1; + const auto goal = RrtConnect{}.plan(request); + EXPECT_EQ(goal.status, JointPathStatus::InvalidGoal); + EXPECT_TRUE(goal.waypoints.empty()); +} + +TEST(RrtConnectTest, RejectsCollidingEndpoints) +{ + auto request = freeSpaceRequest(); + request.is_state_valid = [](const auto& q) { return q[0] > 0.0; }; + EXPECT_EQ(RrtConnect{}.plan(request).status, JointPathStatus::InvalidStart); + request.is_state_valid = [](const auto& q) { return q[0] < 0.0; }; + EXPECT_EQ(RrtConnect{}.plan(request).status, JointPathStatus::InvalidGoal); +} + +TEST(RrtConnectTest, ReturnsSingleStateForUnchangedValidGoal) +{ + auto request = freeSpaceRequest(); + request.goal = request.start; + const auto result = RrtConnect{}.plan(request); + ASSERT_TRUE(result.ok()) << result.message; + EXPECT_EQ(result.waypoints, JointPath{request.start}); + request.is_state_valid = [](const auto&) { return false; }; + EXPECT_EQ(RrtConnect{}.plan(request).status, JointPathStatus::InvalidStart); +} + +TEST(RrtConnectTest, SupportsCancellationBeforeAndDuringSearch) +{ + auto request = freeSpaceRequest(); + request.is_cancelled = [] { return true; }; + const auto before = RrtConnect{}.plan(request); + EXPECT_EQ(before.status, JointPathStatus::Cancelled); + EXPECT_EQ(before.validity_checks, 0U); + EXPECT_TRUE(before.waypoints.empty()); + std::size_t checks = 0; + request.is_state_valid = [&](const auto&) { ++checks; return true; }; + request.is_cancelled = [&] { return checks >= 20; }; + const auto during = RrtConnect{}.plan(request); + EXPECT_EQ(during.status, JointPathStatus::Cancelled); + EXPECT_TRUE(during.waypoints.empty()); +} + +TEST(RrtConnectTest, ContainsCallbackExceptionsDuringSearch) +{ + auto request = freeSpaceRequest(); + int checks = 0; + request.is_state_valid = [&](const auto&) { + if (++checks == 10) throw std::runtime_error("collision backend unavailable"); + return true; + }; + const auto result = RrtConnect{}.plan(request); + EXPECT_EQ(result.status, JointPathStatus::ValidationError); + EXPECT_TRUE(result.waypoints.empty()); + EXPECT_NE(result.message.find("collision backend unavailable"), std::string::npos); + request.is_cancelled = []() -> bool { throw std::runtime_error("cancel failure"); }; + EXPECT_EQ(RrtConnect{}.plan(request).status, JointPathStatus::ValidationError); +} + +TEST(RrtConnectTest, IncludesValidationTimeInBudget) +{ + auto request = freeSpaceRequest(); + request.is_state_valid = [](const auto&) { + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + return true; + }; + auto cfg = defaultRrtConnectConfig(); + cfg.mutable_rrt_connect()->set_timeout_s(0.005); + const auto planner = JointPathPlannerFactory::create(cfg); + ASSERT_NE(planner, nullptr); + const auto result = planner->plan(request); + EXPECT_EQ(result.status, JointPathStatus::TimedOut); + EXPECT_TRUE(result.waypoints.empty()); +} + +TEST(RrtConnectTest, DoesNotReusePreviousSolution) +{ + const auto planner = JointPathPlannerFactory::create(defaultRrtConnectConfig()); + ASSERT_NE(planner, nullptr); + auto request = freeSpaceRequest(); + ASSERT_TRUE(planner->plan(request).ok()); + request.is_state_valid = [](const auto&) { return false; }; + const auto result = planner->plan(request); + EXPECT_EQ(result.status, JointPathStatus::InvalidStart); + EXPECT_TRUE(result.waypoints.empty()); +} + +TEST(JointPathPlannerFactoryTest, RejectsMissingOrUnknownAlgorithm) +{ + config::JointPathConfig cfg; + EXPECT_EQ(JointPathPlannerFactory::create(cfg), nullptr); + cfg.mutable_rrt_connect(); + EXPECT_EQ(JointPathPlannerFactory::create(cfg), nullptr); + cfg.set_algorithm(static_cast(999)); + EXPECT_EQ(JointPathPlannerFactory::create(cfg), nullptr); +} + +TEST(JointPathPlannerFactoryTest, LoadsArmConfigAndAppliesResolution) +{ + config::RobotArmConfig arm; + ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"pb( + motion { + joint_path { + algorithm: RRT_CONNECT + rrt_connect { + timeout_s: 1.0 + range_rad: 0.05 + collision_check_step_rad: 0.001 + } + } + } + )pb", &arm)); + const auto planner = JointPathPlannerFactory::create(arm.motion().joint_path()); + ASSERT_NE(planner, nullptr); + const auto request = freeSpaceRequest(1); + const auto result = planner->plan(request); + expectValidPath(result, request); + // Covering the 1.4 rad path at 0.001 rad resolution needs at least 1400 + // checks. The default 0.02 rad resolution would not satisfy this bound. + EXPECT_GE(result.validity_checks, 1400U); +} + +} // namespace +} // namespace cmvr + +int main(int argc, char** argv) +{ + // Set once, before creating any OMPL RNG. Never change process-wide seeds + // inside the production planner. + ompl::RNG::setSeed(42); + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/cmvr-es/algorithms/smoother/CMakeLists.txt b/cmvr-es/algorithms/smoother/CMakeLists.txt new file mode 100644 index 00000000..63e2faf5 --- /dev/null +++ b/cmvr-es/algorithms/smoother/CMakeLists.txt @@ -0,0 +1,11 @@ +add_library(joint_trajectory_smoother SHARED + bspline/src/bspline_smoother.cpp) +target_include_directories(joint_trajectory_smoother PUBLIC "${PROJECT_SOURCE_DIR}/cmvr-es") +target_link_libraries(joint_trajectory_smoother PUBLIC cmvr_es::curves cmvr_es::proto) +add_library(cmvr_es::joint_trajectory_smoother ALIAS joint_trajectory_smoother) +install(TARGETS joint_trajectory_smoother LIBRARY DESTINATION lib) + +add_executable(bspline_smoother_test + bspline/test/bspline_smoother_test.cpp) +target_link_libraries(bspline_smoother_test PRIVATE + cmvr_es::joint_trajectory_smoother gtest gtest_main) diff --git a/cmvr-es/algorithms/smoother/bspline/include/bspline_smoother.h b/cmvr-es/algorithms/smoother/bspline/include/bspline_smoother.h new file mode 100644 index 00000000..ed2b0db1 --- /dev/null +++ b/cmvr-es/algorithms/smoother/bspline/include/bspline_smoother.h @@ -0,0 +1,23 @@ +#pragma once + +#include "algorithms/smoother/joint_trajectory_smoother.h" + +namespace cmvr::device { + +class BSplineSmoother final : public JointTrajectorySmoother { +public: + explicit BSplineSmoother(double control_point_spacing_rad = 0.05); + + bool init() override; + + bool smooth(const std::vector>& waypoints, + const MotionOptions& limits, + double sample_period_s, + JointTrajectory& output) const override; + +private: + double control_point_spacing_rad_; + bool initialized_{false}; +}; + +} // namespace cmvr::device diff --git a/cmvr-es/algorithms/smoother/bspline/src/bspline_smoother.cpp b/cmvr-es/algorithms/smoother/bspline/src/bspline_smoother.cpp new file mode 100644 index 00000000..8b6833a1 --- /dev/null +++ b/cmvr-es/algorithms/smoother/bspline/src/bspline_smoother.cpp @@ -0,0 +1,128 @@ +#include "algorithms/smoother/bspline/include/bspline_smoother.h" + +#include +#include +#include +#include + +#include "curves/bspline/include/quintic_bspline.h" +#include "common/base/logging/logger.h" + +namespace cmvr::device { + +BSplineSmoother::BSplineSmoother(const double control_point_spacing_rad) + : control_point_spacing_rad_(control_point_spacing_rad) +{ +} + +bool BSplineSmoother::init() +{ + initialized_ = std::isfinite(control_point_spacing_rad_) && control_point_spacing_rad_ > 0.0; + return initialized_; +} + +bool BSplineSmoother::smooth( + const std::vector>& waypoints, + const MotionOptions& limits, + const double sample_period_s, + JointTrajectory& output) const +{ + output.clear(); + const auto begin = std::chrono::steady_clock::now(); + if (!initialized_ || waypoints.size() < 2 || waypoints.front().empty() || + !std::isfinite(limits.velocity) || limits.velocity <= 0.0 || + !std::isfinite(limits.acceleration) || limits.acceleration <= 0.0 || + !std::isfinite(limits.jerk) || limits.jerk <= 0.0 || + !std::isfinite(sample_period_s) || sample_period_s <= 0.0) { + CMVR_LOG(ERROR) << "[BSplineSmoother] invalid path or motion limits"; + return false; + } + const auto dof = waypoints.front().size(); + if (!limits.joint_velocity_limits.empty() && limits.joint_velocity_limits.size() != dof) { + CMVR_LOG(ERROR) << "[BSplineSmoother] joint velocity limit count does not match DOF"; + return false; + } + + try { + std::vector velocity_limits(dof, limits.velocity); + for (std::size_t j = 0; j < limits.joint_velocity_limits.size(); ++j) { + const double limit = limits.joint_velocity_limits[j]; + if (!std::isfinite(limit) || limit <= 0.0) return false; + velocity_limits[j] = std::min(limits.velocity, limit); + } + const auto spline = QuinticBSpline::create( + waypoints, velocity_limits, std::vector(dof, limits.acceleration), + std::vector(dof, limits.jerk), sample_period_s, + limits.cancellation_requested, control_point_spacing_rad_); + const double duration = spline->timeInterval()[1]; + const double count = std::ceil(duration / sample_period_s); + if (!std::isfinite(count) || count < 1.0 || count > 1000000) { + CMVR_LOG(ERROR) << "[BSplineSmoother] sampling exceeds one million intervals"; + return false; + } + + // Derivative-control convex hulls bound the entire curve, not just its samples. + const auto v_bounds = spline->derivativeBounds(1); + const auto a_bounds = spline->derivativeBounds(2); + const auto j_bounds = spline->derivativeBounds(3); + if (!v_bounds.allFinite() || !a_bounds.allFinite() || !j_bounds.allFinite()) return false; + double v_utilization = 0.0, a_utilization = 0.0, j_utilization = 0.0; + for (std::size_t j = 0; j < dof; ++j) { + v_utilization = std::max(v_utilization, v_bounds[j] / velocity_limits[j]); + a_utilization = std::max(a_utilization, a_bounds[j] / limits.acceleration); + j_utilization = std::max(j_utilization, j_bounds[j] / limits.jerk); + } + if (v_utilization > 1.0 + 1e-6 || a_utilization > 1.0 + 1e-6 || + j_utilization > 1.0 + 1e-6) { + CMVR_LOG(ERROR) << "[BSplineSmoother] derivative bounds exceed motion limits"; + return false; + } + + JointTrajectory samples; + samples.reserve(static_cast(count) + 1); + const auto as_vector = [](const Eigen::VectorXd& value) { + return std::vector(value.data(), value.data() + value.size()); + }; + for (std::size_t i = 0; i <= static_cast(count); ++i) { + if (limits.cancellation_requested && limits.cancellation_requested()) return false; + JointTrajectoryPoint point; + point.time_s = i == static_cast(count) + ? duration : std::min(i * sample_period_s, duration); + point.position = as_vector(spline->q(point.time_s)); + point.velocity = as_vector(spline->qd(point.time_s)); + point.acceleration = as_vector(spline->qdd(point.time_s)); + point.jerk = as_vector(spline->qddd(point.time_s)); + for (std::size_t j = 0; j < dof; ++j) { + if (!std::isfinite(point.position[j]) || !std::isfinite(point.velocity[j]) || + !std::isfinite(point.acceleration[j]) || !std::isfinite(point.jerk[j]) || + std::abs(point.velocity[j]) > velocity_limits[j] + 1e-6 || + std::abs(point.acceleration[j]) > limits.acceleration + 1e-6 || + std::abs(point.jerk[j]) > limits.jerk + 1e-6) { + CMVR_LOG(ERROR) << "[BSplineSmoother] invalid sample: point=" + << i << ", joint=" << j; + return false; + } + } + samples.push_back(std::move(point)); + if (samples.back().time_s == duration) break; + } + output = std::move(samples); + CMVR_LOG(INFO) << "[BSplineSmoother] planning_time_ms=" + << std::chrono::duration( + std::chrono::steady_clock::now() - begin).count() + << ", trajectory_time_s=" << duration + << ", path=quintic_bspline, control_points=" << spline->controlPoints().cols() + << ", v_bound_utilization=" << v_utilization + << ", a_bound_utilization=" << a_utilization + << ", j_bound_utilization=" << j_utilization; + return true; + } catch (const std::exception& e) { + CMVR_LOG(ERROR) << "[BSplineSmoother] " << e.what(); + return false; + } catch (...) { + CMVR_LOG(ERROR) << "[BSplineSmoother] planning callback failed"; + return false; + } +} + +} // namespace cmvr::device diff --git a/cmvr-es/algorithms/smoother/bspline/test/bspline_smoother_test.cpp b/cmvr-es/algorithms/smoother/bspline/test/bspline_smoother_test.cpp new file mode 100644 index 00000000..f5246884 --- /dev/null +++ b/cmvr-es/algorithms/smoother/bspline/test/bspline_smoother_test.cpp @@ -0,0 +1,519 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "algorithms/smoother/bspline/include/bspline_smoother.h" +#include "algorithms/smoother/joint_trajectory_validation.h" +#include "curves/bspline/include/quintic_bspline.h" + +namespace cmvr::device { +namespace { + +constexpr std::size_t kDof = 7; + +JointTrajectory makeRecordedTrajectory(const std::size_t point_count) +{ + JointTrajectory trajectory; + trajectory.reserve(point_count); + for (std::size_t i = 0; i < point_count; ++i) { + const double s = static_cast(i) / + static_cast(point_count - 1); + JointTrajectoryPoint point; + point.time_s = static_cast(i) * 0.002; + point.position = { + 0.40 * s, + -0.25 * s + 0.03 * std::sin(3.141592653589793 * s), + 0.20 * s * s, + 0.30 * std::sin(1.5707963267948966 * s), + -0.12 * s, + 0.15 * s, + -0.08 * std::sin(3.141592653589793 * s), + }; + point.velocity.assign(kDof, 0.0); + trajectory.push_back(std::move(point)); + } + return trajectory; +} + +double maximumPositionError(const std::vector& lhs, + const std::vector& rhs) +{ + if (lhs.size() != rhs.size()) { + return std::numeric_limits::infinity(); + } + double maximum = 0.0; + for (std::size_t i = 0; i < lhs.size(); ++i) { + maximum = std::max(maximum, std::abs(lhs[i] - rhs[i])); + } + return maximum; +} + +void writeTrajectoryCsv(const char* name, const JointTrajectory& trajectory) +{ + const char* directory = std::getenv("CMVR_PATH_TEST_CSV_DIR"); + if (!directory || !*directory || trajectory.empty()) return; + std::error_code error; + std::filesystem::create_directories(directory, error); + ASSERT_FALSE(error) << error.message(); + std::ofstream output(std::filesystem::path(directory) / (std::string(name) + ".csv")); + ASSERT_TRUE(output.is_open()); + output << "time_s"; + for (std::size_t j = 0; j < trajectory.front().position.size(); ++j) { + output << ",q" << j + 1 << "_rad,v" << j + 1 << "_rad_s,a" << j + 1 + << "_rad_s2,j" << j + 1 << "_rad_s3"; + } + output << '\n' << std::setprecision(17); + for (const auto& point : trajectory) { + output << point.time_s; + for (std::size_t j = 0; j < point.position.size(); ++j) { + output << ',' << point.position[j] << ',' << point.velocity[j] + << ',' << point.acceleration[j] << ',' << point.jerk[j]; + } + output << '\n'; + } + ASSERT_TRUE(output.good()); +} + +void expectConsistentTrajectory(const JointTrajectory& trajectory, + const MotionOptions& options) +{ + ASSERT_GT(trajectory.size(), 2u); + const auto dof = trajectory.front().position.size(); + double jerk_error_squared = 0.0, maximum_jerk = 0.0; + std::size_t derivative_samples = 0; + for (std::size_t i = 0; i < trajectory.size(); ++i) { + const auto& point = trajectory[i]; + ASSERT_EQ(point.position.size(), dof); + ASSERT_EQ(point.velocity.size(), dof); + ASSERT_EQ(point.acceleration.size(), dof); + ASSERT_EQ(point.jerk.size(), dof); + ASSERT_TRUE(std::isfinite(point.time_s)); + for (std::size_t j = 0; j < dof; ++j) { + ASSERT_TRUE(std::isfinite(point.position[j])); + ASSERT_TRUE(std::isfinite(point.velocity[j])); + ASSERT_TRUE(std::isfinite(point.acceleration[j])); + ASSERT_TRUE(std::isfinite(point.jerk[j])); + const double velocity_limit = options.joint_velocity_limits.empty() + ? options.velocity : std::min(options.velocity, options.joint_velocity_limits[j]); + EXPECT_LE(std::abs(point.velocity[j]), velocity_limit + 1e-6); + EXPECT_LE(std::abs(point.acceleration[j]), options.acceleration + 1e-6); + EXPECT_LE(std::abs(point.jerk[j]), options.jerk + 1e-6); + maximum_jerk = std::max(maximum_jerk, std::abs(point.jerk[j])); + if (i == 0) continue; + const auto& previous = trajectory[i - 1]; + const double dt = point.time_s - previous.time_s; + ASSERT_GT(dt, 0.0); + // Check that the reported derivatives describe the executed positions. + EXPECT_NEAR(point.position[j] - previous.position[j], + 0.5 * (point.velocity[j] + previous.velocity[j]) * dt, + options.jerk * dt * dt * dt / 12.0 + 1e-9); + EXPECT_NEAR(point.velocity[j] - previous.velocity[j], + 0.5 * (point.acceleration[j] + previous.acceleration[j]) * dt, + options.jerk * dt * dt / 2.0 + 1e-9); + EXPECT_LE(std::abs(point.acceleration[j] - previous.acceleration[j]), + options.jerk * dt + 1e-7); + if (dt > 1e-9) { + const double error = (point.acceleration[j] - previous.acceleration[j]) / dt - + 0.5 * (point.jerk[j] + previous.jerk[j]); + jerk_error_squared += error * error; + ++derivative_samples; + } + } + } + // Compare analytic jerk with interval-average acceleration changes. + ASSERT_GT(derivative_samples, 0u); + EXPECT_LE(std::sqrt(jerk_error_squared / derivative_samples), 0.05 * maximum_jerk + 1e-6); + for (const auto* endpoint : {&trajectory.front(), &trajectory.back()}) { + for (const double velocity : endpoint->velocity) EXPECT_NEAR(velocity, 0.0, 1e-9); + for (const double acceleration : endpoint->acceleration) EXPECT_NEAR(acceleration, 0.0, 1e-8); + } +} + +TEST(BSplineSmootherTest, PreservesLineWithAnalyticLimitsAndJerkScaling) +{ + BSplineSmoother smoother(0.05); + ASSERT_TRUE(smoother.init()); + const auto& initialized = smoother; + const std::vector start{0.12, -0.2, 0.4, 0.15}; + const std::vector target{0.42, -0.35, 0.475, 0.15}; + MotionOptions options; + options.velocity = 0.6; + options.acceleration = 1.2; + options.joint_velocity_limits = {0.4, 0.2, 0.12, 0.3}; + double normal_duration = 0.0; + for (int scenario = 0; scenario < 3; ++scenario) { + SCOPED_TRACE(scenario); + options.jerk = scenario == 1 ? 0.1 : 100.0; + const double scaling = scenario == 2 ? 0.5 : 1.0; + JointTrajectory trajectory; + MotionOptions effective_limits = options; + effective_limits.velocity *= scaling; + for (auto& limit : effective_limits.joint_velocity_limits) limit *= scaling; + ASSERT_TRUE(initialized.smooth({start, target}, effective_limits, 0.001, trajectory)); + ASSERT_GT(trajectory.size(), 2u); + expectConsistentTrajectory(trajectory, effective_limits); + const char* names[]{"smooth_line", "smooth_line_low_jerk", "smooth_line_scaled_limits"}; + writeTrajectoryCsv(names[scenario], trajectory); + EXPECT_LT(maximumPositionError(trajectory.front().position, start), 1e-12); + EXPECT_LT(maximumPositionError(trajectory.back().position, target), 1e-12); + if (scenario == 0) normal_duration = trajectory.back().time_s; + else EXPECT_GT(trajectory.back().time_s, normal_duration); + + double previous_progress = 0.0; + int previous_sign = 0, acceleration_reversals = 0; + for (const auto& point : trajectory) { + const double progress = (point.position[0] - start[0]) / + (target[0] - start[0]); + EXPECT_GE(progress, previous_progress - 1e-12); + EXPECT_GE(progress, -1e-12); + EXPECT_LE(progress, 1.0 + 1e-12); + previous_progress = progress; + for (std::size_t j = 0; j < start.size(); ++j) { + EXPECT_NEAR(point.position[j], start[j] + + progress * (target[j] - start[j]), 1e-12); + EXPECT_GE(point.position[j], std::min(start[j], target[j]) - 1e-12); + EXPECT_LE(point.position[j], std::max(start[j], target[j]) + 1e-12); + } + // Rest-to-rest motion on one joint-space line needs one acceleration reversal. + if (std::abs(point.acceleration[0]) > 1e-7) { + const int sign = point.acceleration[0] > 0.0 ? 1 : -1; + if (previous_sign && previous_sign != sign) ++acceleration_reversals; + previous_sign = sign; + } + EXPECT_NEAR(point.velocity.back(), 0.0, 1e-12); + EXPECT_NEAR(point.acceleration.back(), 0.0, 1e-12); + EXPECT_NEAR(point.jerk.back(), 0.0, 1e-12); + } + EXPECT_EQ(acceleration_reversals, 1); + } +} + +TEST(BSplineSmootherTest, RejectsInvalidInputsAndHonorsCancellation) +{ + BSplineSmoother smoother(0.05); + ASSERT_TRUE(smoother.init()); + const std::vector> path{{0.0, 0.0}, {0.3, -0.1}}; + MotionOptions options; + options.velocity = 0.4; + options.acceleration = 0.8; + options.jerk = 30.0; + const double nan = std::numeric_limits::quiet_NaN(); + const double inf = std::numeric_limits::infinity(); + JointTrajectory trajectory; + const auto reject = [&](const std::vector>& waypoints, + const MotionOptions& limits, const double period = 0.001) { + trajectory.resize(1); + EXPECT_FALSE(smoother.smooth(waypoints, limits, period, trajectory)); + EXPECT_TRUE(trajectory.empty()); + }; + reject({}, options); + reject({path.front()}, options); + reject({{}, {}}, options); + reject({path.front(), {0.3}}, options); + for (const double invalid : {nan, inf}) { + reject({{invalid, 0.0}, path.back()}, options); + reject({path.front(), {0.3, invalid}}, options); + } + for (const double invalid : {0.0, -1.0, nan, inf}) { + SCOPED_TRACE(invalid); + for (int field = 0; field < 3; ++field) { + MotionOptions bad = options; + if (field == 0) bad.velocity = invalid; + if (field == 1) bad.acceleration = invalid; + if (field == 2) bad.jerk = invalid; + reject(path, bad); + } + reject(path, options, invalid); + BSplineSmoother bad_spacing(invalid); + EXPECT_FALSE(bad_spacing.init()); + } + for (const auto& invalid : std::vector>{ + {1.0}, {1.0, 0.0}, {1.0, -1.0}, {nan, 1.0}, {inf, 1.0}}) { + MotionOptions bad = options; + bad.joint_velocity_limits = invalid; + reject(path, bad); + } + options.cancellation_requested = [] { return true; }; + reject(path, options); +} + +TEST(JointTrajectoryValidationTest, RejectsInvalidOutputTrajectory) +{ + MotionOptions options; + options.velocity = 0.15; + options.acceleration = 5.0; + + JointTrajectory trajectory = makeRecordedTrajectory(10); + trajectory[5].velocity[2] = options.velocity + 0.01; + EXPECT_FALSE(validateJointTrajectory(trajectory, kDof, options)); + + trajectory[5].velocity[2] = 0.0; + trajectory[5].time_s = trajectory[4].time_s; + EXPECT_FALSE(validateJointTrajectory(trajectory, kDof, options)); +} + +void writeBSplineCsv(const char* name, const cmvr::QuinticBSpline& spline) +{ + if (!std::getenv("CMVR_PATH_TEST_CSV_DIR")) return; + const double duration = spline.timeInterval()[1]; + const auto count = static_cast(std::ceil(duration / 0.001)); + JointTrajectory samples; + samples.reserve(count + 1); + for (std::size_t i = 0; i <= count; ++i) { + JointTrajectoryPoint point; + point.time_s = duration * static_cast(i) / static_cast(count); + const auto q = spline.q(point.time_s), v = spline.qd(point.time_s); + const auto a = spline.qdd(point.time_s), j = spline.qddd(point.time_s); + point.position.assign(q.data(), q.data() + q.size()); + point.velocity.assign(v.data(), v.data() + v.size()); + point.acceleration.assign(a.data(), a.data() + a.size()); + point.jerk.assign(j.data(), j.data() + j.size()); + samples.push_back(std::move(point)); + } + writeTrajectoryCsv(name, samples); +} + +TEST(QuinticBSplineTest, AnalyticDerivativesAndJointLimits) +{ + const std::vector>> paths{ + {{0.0, 0.0, 0.0}, {0.3, -0.15, 0.075}}, + {{0.0, 0.0, 0.0}, {0.025, 0.006, -0.003}, + {0.35, 0.18, -0.07}, {0.8, 0.05, 0.1}}}; + const std::vector velocity{0.3, 0.15, 0.08}; + const std::vector acceleration{0.8, 0.5, 0.3}; + const std::vector jerk{30.0, 8.0, 2.0}; + for (std::size_t scenario = 0; scenario < paths.size(); ++scenario) { + SCOPED_TRACE(scenario); + const auto curve = cmvr::QuinticBSpline::create( + paths[scenario], velocity, acceleration, jerk, 0.01); + ASSERT_TRUE(curve); + const double duration = curve->timeInterval()[1]; + ASSERT_TRUE(std::isfinite(duration)); + ASSERT_GT(duration, 0.0); + EXPECT_DOUBLE_EQ(curve->timeInterval()[0], 0.0); + for (const double time : {0.0, duration}) { + const auto& endpoint = time == 0.0 ? paths[scenario].front() : paths[scenario].back(); + for (int axis = 0; axis < 3; ++axis) { + EXPECT_NEAR(curve->q(time)[axis], endpoint[axis], 1e-12); + EXPECT_NEAR(curve->qd(time)[axis], 0.0, 1e-12); + EXPECT_NEAR(curve->qdd(time)[axis], 0.0, 1e-12); + } + } + const auto vb = curve->derivativeBounds(1), ab = curve->derivativeBounds(2); + const auto jb = curve->derivativeBounds(3); + for (int axis = 0; axis < 3; ++axis) { + EXPECT_LE(vb[axis], velocity[axis] + 1e-12); + EXPECT_LE(ab[axis], acceleration[axis] + 1e-12); + EXPECT_LE(jb[axis], jerk[axis] + 1e-12); + } + for (int sample = 0; sample <= 2000; ++sample) { + const double time = duration * sample / 2000.0; + EXPECT_TRUE(curve->q(time).allFinite()); + EXPECT_TRUE((curve->qd(time).cwiseAbs().array() <= vb.array() + 1e-10).all()); + EXPECT_TRUE((curve->qdd(time).cwiseAbs().array() <= ab.array() + 1e-10).all()); + EXPECT_TRUE((curve->qddd(time).cwiseAbs().array() <= jb.array() + 1e-10).all()); + } + // Differentiate the evaluated curves, independently of their stored derivative controls. + const double h = duration * 1e-6; + for (int sample = 1; sample < 100; ++sample) { + const double time = duration * sample / 100.0; + EXPECT_LT(((curve->q(time + h) - curve->q(time - h)) / (2 * h) - + curve->qd(time)).cwiseAbs().maxCoeff(), 2e-6); + EXPECT_LT(((curve->qd(time + h) - curve->qd(time - h)) / (2 * h) - + curve->qdd(time)).cwiseAbs().maxCoeff(), 2e-6); + EXPECT_LT(((curve->qdd(time + h) - curve->qdd(time - h)) / (2 * h) - + curve->qddd(time)).cwiseAbs().maxCoeff(), 2e-5); + } + const auto knots = curve->knotTimes(); + ASSERT_GE(knots.size(), 2u); + for (std::size_t k = 1; k + 1 < knots.size(); ++k) { + const double epsilon = 1e-7 * std::min(knots[k] - knots[k - 1], knots[k + 1] - knots[k]); + ASSERT_GT(epsilon, 0.0); + EXPECT_LT((curve->qddd(knots[k] + epsilon) - + curve->qddd(knots[k] - epsilon)).cwiseAbs().maxCoeff(), + 1e-4 * std::max(1.0, jb.maxCoeff())); + } + writeBSplineCsv(scenario == 0 ? "bspline_two_waypoint" : "bspline_uneven_waypoint", *curve); + } +} + +TEST(QuinticBSplineTest, UnevenCollinearWaypointsDoNotIntroduceSpeedRipple) +{ + const std::vector start{0.12, -0.2, 0.4}, delta{0.8, -0.4, 0.2}; + std::vector> waypoints; + for (const double progress : {0.0, 0.002, 0.03, 0.4, 0.83, 1.0}) { + std::vector point = start; + for (int axis = 0; axis < 3; ++axis) point[axis] += progress * delta[axis]; + waypoints.push_back(std::move(point)); + } + const auto curve = cmvr::QuinticBSpline::create( + waypoints, {0.4, 0.3, 0.2}, {0.8, 0.6, 0.4}, {30.0, 20.0, 10.0}, 0.01); + const auto reference = cmvr::QuinticBSpline::create( + {waypoints.front(), waypoints.back()}, {0.4, 0.3, 0.2}, + {0.8, 0.6, 0.4}, {30.0, 20.0, 10.0}, 0.01); + const double duration = curve->timeInterval()[1]; + EXPECT_NEAR(duration, reference->timeInterval()[1], 1e-10); + int acceleration_sign = 0, acceleration_reversals = 0; + const double threshold = 1e-5 * curve->derivativeBounds(2)[0]; + for (int sample = 0; sample <= 2000; ++sample) { + const double u = sample / 2000.0, time = duration * u; + const auto q = curve->q(time), v = curve->qd(time), a = curve->qdd(time); + EXPECT_LT((q - reference->q(time)).cwiseAbs().maxCoeff(), 1e-10); + EXPECT_LT((v - reference->qd(time)).cwiseAbs().maxCoeff(), 1e-9); + EXPECT_GE(v[0], -1e-12); + if (sample > 40 && sample < 1960) EXPECT_GT(v[0], 1e-6); + // A straight path has the independent closed-form rest-to-rest quintic solution. + const double progress = u * u * u * (10.0 - 15.0 * u + 6.0 * u * u); + const double speed = 30.0 * u * u * (1.0 - u) * (1.0 - u) / duration; + const double accel = 60.0 * u * (1.0 - u) * (1.0 - 2.0 * u) / (duration * duration); + const double jerk = (60.0 - 360.0 * u + 360.0 * u * u) / (duration * duration * duration); + for (int axis = 0; axis < 3; ++axis) { + EXPECT_NEAR(q[axis], start[axis] + delta[axis] * progress, 1e-10); + EXPECT_NEAR(v[axis], delta[axis] * speed, 1e-9); + EXPECT_NEAR(a[axis], delta[axis] * accel, 1e-8); + EXPECT_NEAR(curve->qddd(time)[axis], delta[axis] * jerk, 1e-7); + } + for (int axis = 1; axis < 3; ++axis) { + EXPECT_NEAR((q[axis] - start[axis]) * delta[0], (q[0] - start[0]) * delta[axis], 1e-12); + EXPECT_NEAR(v[axis] * delta[0], v[0] * delta[axis], 1e-12); + } + if (std::abs(a[0]) > threshold) { + const int sign = a[0] > 0.0 ? 1 : -1; + if (acceleration_sign != 0 && sign != acceleration_sign) ++acceleration_reversals; + acceleration_sign = sign; + } + } + EXPECT_EQ(acceleration_reversals, 1); + writeBSplineCsv("bspline_six_waypoint", *curve); +} + +TEST(QuinticBSplineTest, UniformTimeStretchScalesAllDerivatives) +{ + const std::vector> path{{0.0, 0.0}, {0.25, 0.3}, {0.7, -0.1}}; + const auto normal = cmvr::QuinticBSpline::create( + path, {0.4, 0.2}, {0.8, 0.6}, {30.0, 5.0}, 0.01); + const double normal_duration = normal->timeInterval()[1]; + const auto slow = cmvr::QuinticBSpline::create( + path, {0.4, 0.2}, {0.8, 0.6}, {30.0, 5.0}, 2 * normal_duration); + const double slow_duration = slow->timeInterval()[1]; + const double ratio = slow_duration / normal_duration; + EXPECT_GE(ratio, 2.0 - 1e-12); + for (int sample = 0; sample <= 100; ++sample) { + const double t = normal_duration * sample / 100.0, ts = slow_duration * sample / 100.0; + EXPECT_LT((normal->q(t) - slow->q(ts)).cwiseAbs().maxCoeff(), 1e-12); + EXPECT_LT((normal->qd(t) - ratio * slow->qd(ts)).cwiseAbs().maxCoeff(), 1e-11); + EXPECT_LT((normal->qdd(t) - ratio * ratio * slow->qdd(ts)).cwiseAbs().maxCoeff(), 1e-10); + EXPECT_LT((normal->qddd(t) - ratio * ratio * ratio * slow->qddd(ts)).cwiseAbs().maxCoeff(), 1e-9); + } +} + +TEST(QuinticBSplineTest, JerkSweepPreservesGeometryAndLimits) +{ + std::vector> line; + for (const double progress : {0.0, 0.002, 0.03, 0.4, 0.83, 1.0}) { + line.push_back({0.12 + 0.8 * progress, -0.2 - 0.4 * progress, + 0.4 + 0.2 * progress}); + } + const std::vector>> paths{ + line, + {{0.0, 0.0, 0.0}, {0.025, 0.006, -0.003}, + {0.35, 0.18, -0.07}, {0.8, 0.05, 0.1}}}; + const std::vector velocity(3, 0.65), acceleration(3, 1.7); + for (std::size_t scenario = 0; scenario < paths.size(); ++scenario) { + SCOPED_TRACE(scenario); + const auto reference = cmvr::QuinticBSpline::create( + paths[scenario], velocity, acceleration, std::vector(3, 100.0), 0.01); + const double reference_duration = reference->timeInterval()[1]; + double previous_duration = std::numeric_limits::infinity(); + for (const int jerk_limit : {1, 5, 30, 100}) { + SCOPED_TRACE(jerk_limit); + const auto curve = cmvr::QuinticBSpline::create( + paths[scenario], velocity, acceleration, + std::vector(3, jerk_limit), 0.01); + const double duration = curve->timeInterval()[1]; + EXPECT_LE(duration, previous_duration + 1e-12); + if (jerk_limit == 1) EXPECT_GT(duration, reference_duration); + previous_duration = duration; + EXPECT_LE(curve->derivativeBounds(1).maxCoeff(), 0.65 + 1e-12); + EXPECT_LE(curve->derivativeBounds(2).maxCoeff(), 1.7 + 1e-12); + EXPECT_LE(curve->derivativeBounds(3).maxCoeff(), jerk_limit + 1e-12); + // Changing the jerk constraint stretches time; it must not alter + // the geometric curve or its normalized analytic derivatives. + const double ratio = duration / reference_duration; + for (int sample = 0; sample <= 100; ++sample) { + const double progress = sample / 100.0; + const double t = duration * progress, tr = reference_duration * progress; + EXPECT_LT((curve->q(t) - reference->q(tr)).cwiseAbs().maxCoeff(), 1e-12); + EXPECT_LT((ratio * curve->qd(t) - reference->qd(tr)).cwiseAbs().maxCoeff(), 1e-10); + EXPECT_LT((ratio * ratio * curve->qdd(t) - reference->qdd(tr)).cwiseAbs().maxCoeff(), 1e-9); + EXPECT_LT((ratio * ratio * ratio * curve->qddd(t) - reference->qddd(tr)).cwiseAbs().maxCoeff(), 1e-8); + } + const std::string name = std::string(scenario == 0 ? "bspline_line_j" : "bspline_bent_j") + + (jerk_limit < 10 ? "00" : jerk_limit < 100 ? "0" : "") + std::to_string(jerk_limit); + writeBSplineCsv(name.c_str(), *curve); + } + } +} + +TEST(QuinticBSplineTest, DuplicateAndStationaryWaypoints) +{ + const std::vector> path{{0.1, -0.2}, {0.3, 0.1}, {0.5, 0.0}}; + const auto clean = cmvr::QuinticBSpline::create(path, {0.3, 0.2}, {0.8, 0.6}, {10.0, 5.0}, 0.01); + const auto duplicates = cmvr::QuinticBSpline::create( + {path[0], path[0], path[1], path[1], path[2], path[2]}, + {0.3, 0.2}, {0.8, 0.6}, {10.0, 5.0}, 0.01); + EXPECT_NEAR(clean->timeInterval()[1], duplicates->timeInterval()[1], 1e-12); + for (int i = 0; i <= 100; ++i) { + const double time = clean->timeInterval()[1] * i / 100.0; + EXPECT_LT((clean->q(time) - duplicates->q(time)).cwiseAbs().maxCoeff(), 1e-12); + } + const auto stationary = cmvr::QuinticBSpline::create( + {path[0], path[0], path[0]}, {0.3, 0.2}, {0.8, 0.6}, {10.0, 5.0}, 0.125); + EXPECT_DOUBLE_EQ(stationary->timeInterval()[1], 0.125); + for (const double time : {0.0, 0.06, 0.125}) { + EXPECT_NEAR(stationary->q(time)[0], 0.1, 1e-14); + EXPECT_NEAR(stationary->q(time)[1], -0.2, 1e-14); + EXPECT_DOUBLE_EQ(stationary->qd(time).norm(), 0.0); + EXPECT_DOUBLE_EQ(stationary->qdd(time).norm(), 0.0); + EXPECT_DOUBLE_EQ(stationary->qddd(time).norm(), 0.0); + } +} + +TEST(QuinticBSplineTest, RejectsInvalidInputsAndHonorsCancellation) +{ + using Spline = cmvr::QuinticBSpline; + const std::vector> path{{0.0, 0.0}, {0.2, -0.1}}; + const std::vector limits{1.0, 1.0}; + const double nan = std::numeric_limits::quiet_NaN(); + const double inf = std::numeric_limits::infinity(); + EXPECT_THROW(Spline::create({}, limits, limits, limits, 0.01), std::invalid_argument); + EXPECT_THROW(Spline::create({{}, {}}, {}, {}, {}, 0.01), std::invalid_argument); + EXPECT_THROW(Spline::create({{0.0, 0.0}, {0.2}}, limits, limits, limits, 0.01), std::invalid_argument); + for (const double invalid : {nan, inf}) { + EXPECT_THROW(Spline::create({{0.0, 0.0}, {invalid, 0.1}}, limits, limits, limits, 0.01), std::invalid_argument); + } + for (int order = 0; order < 3; ++order) { + for (const auto& invalid : std::vector>{{1.0}, {1.0, 0.0}, {1.0, -1.0}, {nan, 1.0}, {inf, 1.0}}) { + SCOPED_TRACE(order); + EXPECT_THROW(Spline::create(path, order == 0 ? invalid : limits, + order == 1 ? invalid : limits, order == 2 ? invalid : limits, 0.01), std::invalid_argument); + } + } + for (const double invalid : {0.0, -0.1, nan, inf}) { + EXPECT_THROW(Spline::create(path, limits, limits, limits, invalid), std::invalid_argument); + } + EXPECT_THROW(Spline::create(path, limits, limits, limits, 0.01, [] { return true; }), std::runtime_error); +} + +} // namespace +} // namespace cmvr::device diff --git a/cmvr-es/algorithms/smoother/joint_trajectory_smoother.h b/cmvr-es/algorithms/smoother/joint_trajectory_smoother.h new file mode 100644 index 00000000..3d8ebded --- /dev/null +++ b/cmvr-es/algorithms/smoother/joint_trajectory_smoother.h @@ -0,0 +1,24 @@ +#pragma once + +#include + +#include "common/types/arm/arm_types.h" + +namespace cmvr::device { + +class JointTrajectorySmoother { +public: + virtual ~JointTrajectorySmoother() = default; + + virtual bool init() = 0; + + // Generate a timed, rest-to-rest trajectory from a joint-space path. + // Limits already include the caller's speed scaling. Smoothing may change + // the geometric path; the caller must recheck joint bounds and collisions. + virtual bool smooth(const std::vector>& waypoints, + const MotionOptions& limits, + double sample_period_s, + JointTrajectory& output) const = 0; +}; + +} // namespace cmvr::device diff --git a/cmvr-es/algorithms/smoother/joint_trajectory_smoother_factory.h b/cmvr-es/algorithms/smoother/joint_trajectory_smoother_factory.h new file mode 100644 index 00000000..54b522a6 --- /dev/null +++ b/cmvr-es/algorithms/smoother/joint_trajectory_smoother_factory.h @@ -0,0 +1,28 @@ +#pragma once + +#include + +#include "algorithms/smoother/bspline/include/bspline_smoother.h" +#include "cmvr/config/joint_motion_config.pb.h" + +namespace cmvr::device { + +class JointTrajectorySmootherFactory { +public: + static std::shared_ptr create( + const config::JointTrajectorySmootherConfig& cfg) + { + if (!cfg.has_quintic_bspline()) { + return nullptr; + } + const auto& spline = cfg.quintic_bspline(); + auto smoother = std::make_shared( + spline.has_control_point_spacing_rad() ? spline.control_point_spacing_rad() : 0.05); + if (!smoother->init()) { + return nullptr; + } + return smoother; + } +}; + +} // namespace cmvr::device diff --git a/cmvr-es/algorithms/motion_planner/arm_motion/joint_motion/joint_motion_planner.h b/cmvr-es/algorithms/smoother/joint_trajectory_validation.h similarity index 70% rename from cmvr-es/algorithms/motion_planner/arm_motion/joint_motion/joint_motion_planner.h rename to cmvr-es/algorithms/smoother/joint_trajectory_validation.h index a2f77c51..f0dbffdc 100644 --- a/cmvr-es/algorithms/motion_planner/arm_motion/joint_motion/joint_motion_planner.h +++ b/cmvr-es/algorithms/smoother/joint_trajectory_validation.h @@ -1,5 +1,4 @@ -#ifndef CMVR_ES_JOINT_MOTION_PLANNER_H -#define CMVR_ES_JOINT_MOTION_PLANNER_H +#pragma once #include #include @@ -10,46 +9,24 @@ namespace cmvr::device { -class JointMotionPlanner { -public: - virtual ~JointMotionPlanner() = default; - - virtual bool init() = 0; - - virtual bool planMoveJ(const std::vector& start, - const JointPositionCommand& target, - const MotionOptions& options, - double speed_scaling, - JointTrajectory& trajectory) = 0; - - virtual bool planReplay(const std::vector& current_position, - const JointTrajectory& recorded_trajectory, - const MotionOptions& options, - JointTrajectory& replay_trajectory) = 0; - - bool validateJointTrajectory(const JointTrajectory& trajectory, - std::size_t expected_dof, - const MotionOptions& limits) const; -}; - -inline bool JointMotionPlanner::validateJointTrajectory( +inline bool validateJointTrajectory( const JointTrajectory& trajectory, const std::size_t expected_dof, - const MotionOptions& limits) const + const MotionOptions& limits) { if (trajectory.size() < 2 || expected_dof == 0) { - CMVR_LOG(ERROR) << "[JointMotionPlanner] trajectory must contain at least " + CMVR_LOG(ERROR) << "[JointTrajectoryValidation] trajectory must contain at least " "two points and have a non-zero DOF"; return false; } if (!std::isfinite(limits.velocity) || limits.velocity <= 0.0 || !std::isfinite(limits.acceleration) || limits.acceleration <= 0.0) { - CMVR_LOG(ERROR) << "[JointMotionPlanner] velocity or acceleration limit is invalid"; + CMVR_LOG(ERROR) << "[JointTrajectoryValidation] velocity or acceleration limit is invalid"; return false; } if (!limits.joint_velocity_limits.empty() && limits.joint_velocity_limits.size() != expected_dof) { - CMVR_LOG(ERROR) << "[JointMotionPlanner] joint velocity limit count does not match DOF"; + CMVR_LOG(ERROR) << "[JointTrajectoryValidation] joint velocity limit count does not match DOF"; return false; } @@ -68,7 +45,7 @@ inline bool JointMotionPlanner::validateJointTrajectory( if (!std::isfinite(point.time_s) || point.position.size() != expected_dof || point.velocity.size() != expected_dof) { - CMVR_LOG(ERROR) << "[JointMotionPlanner] invalid trajectory point at index=" << i; + CMVR_LOG(ERROR) << "[JointTrajectoryValidation] invalid trajectory point at index=" << i; return false; } @@ -76,7 +53,7 @@ inline bool JointMotionPlanner::validateJointTrajectory( if (i > 0) { dt = point.time_s - trajectory[i - 1].time_s; if (!std::isfinite(dt) || dt <= 0.0) { - CMVR_LOG(ERROR) << "[JointMotionPlanner] trajectory time is not increasing at index=" + CMVR_LOG(ERROR) << "[JointTrajectoryValidation] trajectory time is not increasing at index=" << i; return false; } @@ -85,7 +62,7 @@ inline bool JointMotionPlanner::validateJointTrajectory( for (std::size_t joint = 0; joint < expected_dof; ++joint) { if (!std::isfinite(point.position[joint]) || !std::isfinite(point.velocity[joint])) { - CMVR_LOG(ERROR) << "[JointMotionPlanner] non-finite trajectory value at point=" + CMVR_LOG(ERROR) << "[JointTrajectoryValidation] non-finite trajectory value at point=" << i << ", joint=" << joint; return false; } @@ -95,13 +72,13 @@ inline bool JointMotionPlanner::validateJointTrajectory( ? limits.velocity : limits.joint_velocity_limits[joint]; if (!std::isfinite(velocity_limit) || velocity_limit <= 0.0) { - CMVR_LOG(ERROR) << "[JointMotionPlanner] invalid velocity limit for joint=" + CMVR_LOG(ERROR) << "[JointTrajectoryValidation] invalid velocity limit for joint=" << joint; return false; } maximum_velocity = std::max(maximum_velocity, velocity); if (velocity > velocity_limit + kVelocityTolerance) { - CMVR_LOG(ERROR) << "[JointMotionPlanner] velocity limit exceeded at point=" + CMVR_LOG(ERROR) << "[JointTrajectoryValidation] velocity limit exceeded at point=" << i << ", joint=" << joint << ", actual=" << velocity << ", limit=" << velocity_limit; @@ -119,20 +96,22 @@ inline bool JointMotionPlanner::validateJointTrajectory( maximum_acceleration, std::abs(acceleration)); if (std::abs(acceleration) > limits.acceleration + kAccelerationTolerance) { - CMVR_LOG(ERROR) << "[JointMotionPlanner] acceleration limit exceeded at point=" + CMVR_LOG(ERROR) << "[JointTrajectoryValidation] acceleration limit exceeded at point=" << i << ", joint=" << joint << ", actual=" << std::abs(acceleration) << ", limit=" << limits.acceleration; return false; } if (i > 1) { + // Interval-average derivatives are located at interval midpoints. + const double midpoint_dt = 0.5 * (point.time_s - trajectory[i - 2].time_s); maximum_position_acceleration = std::max( maximum_position_acceleration, std::abs(position_velocity - - previous_position_velocity[joint]) / dt); + previous_position_velocity[joint]) / midpoint_dt); maximum_jerk = std::max( maximum_jerk, - std::abs(acceleration - previous_acceleration[joint]) / dt); + std::abs(acceleration - previous_acceleration[joint]) / midpoint_dt); } previous_position_velocity[joint] = position_velocity; previous_acceleration[joint] = acceleration; @@ -140,7 +119,7 @@ inline bool JointMotionPlanner::validateJointTrajectory( } } - CMVR_LOG(INFO) << "[JointMotionPlanner] trajectory validated" + CMVR_LOG(INFO) << "[JointTrajectoryValidation] trajectory validated" << ", points=" << trajectory.size() << ", max_velocity_rad_s=" << maximum_velocity << ", max_discrete_acceleration_rad_s2=" << maximum_acceleration @@ -151,6 +130,5 @@ inline bool JointMotionPlanner::validateJointTrajectory( return true; } -} // namespace cmvr::device -#endif // CMVR_ES_JOINT_MOTION_PLANNER_H +} // namespace cmvr::device diff --git a/cmvr-es/common/math/qp_solver.h b/cmvr-es/common/math/qp_solver.h index d8d913fd..99494b4d 100644 --- a/cmvr-es/common/math/qp_solver.h +++ b/cmvr-es/common/math/qp_solver.h @@ -92,7 +92,9 @@ public: QPSolverImpl() = default; ~QPSolverImpl() = default; - void SetupImpl(int n_var, int n_const, double time_limit = 2e-3); + void SetupImpl(int n_var, int n_const, double time_limit = 2e-3, + double absolute_tolerance = 1e-3, double relative_tolerance = 1e-3, + bool polish = false); void InitFunctionImpl(); void AddCostFunctionImpl(const Eigen::MatrixXd &A, const Eigen::VectorXd &b); void SetCostFunctionImpl(const Eigen::MatrixXd &A, const Eigen::VectorXd &b); @@ -135,13 +137,18 @@ private: Eigen::Matrix primal_variable_for_warmstart_; }; -inline void QPSolverImpl::SetupImpl(int n_var, int n_const, double time_limit) { +inline void QPSolverImpl::SetupImpl(int n_var, int n_const, double time_limit, + double absolute_tolerance, double relative_tolerance, + bool polish) { n_var_ = n_var; n_const_ = n_const; solver_.settings()->setWarmStart(true); solver_.settings()->setVerbosity(false); solver_.settings()->setTimeLimit(time_limit); + solver_.settings()->setAbsoluteTolerance(absolute_tolerance); + solver_.settings()->setRelativeTolerance(relative_tolerance); + solver_.settings()->setPolish(polish); solver_.data()->setNumberOfVariables(n_var_); solver_.data()->setNumberOfConstraints(n_const_); @@ -324,7 +331,9 @@ public: QPSolver(); ~QPSolver(); - void Setup(int n_var, int n_const, double time_limit = 2e-3); + void Setup(int n_var, int n_const, double time_limit = 2e-3, + double absolute_tolerance = 1e-3, double relative_tolerance = 1e-3, + bool polish = false); void InitFunction(); @@ -363,8 +372,10 @@ inline QPSolver::QPSolver() { inline QPSolver::~QPSolver() = default; -inline void QPSolver::Setup(int n_var, int n_const, double time_limit) { - impl_->SetupImpl(n_var, n_const, time_limit); +inline void QPSolver::Setup(int n_var, int n_const, double time_limit, + double absolute_tolerance, double relative_tolerance, + bool polish) { + impl_->SetupImpl(n_var, n_const, time_limit, absolute_tolerance, relative_tolerance, polish); } inline void QPSolver::InitFunction() { diff --git a/cmvr-es/common/math/transform_math.h b/cmvr-es/common/math/transform_math.h index 4f38ee62..ba590ee5 100644 --- a/cmvr-es/common/math/transform_math.h +++ b/cmvr-es/common/math/transform_math.h @@ -5,7 +5,6 @@ #include -#include "algorithms/motion_planner/base_motion/cartesian_velocity/twist_limiter/include/cartesian_twist_limiter.h" #include "common/types/arm/arm_types.h" namespace cmvr::common::math { @@ -83,12 +82,6 @@ inline device::CartesianVelocity vectorToVelocity(const Eigen::Matrix #include +#include "environment/include/robot_model.h" + namespace cmvr::device { enum class ArmErrorCode { @@ -72,8 +74,8 @@ struct SpeedLOptions { // Requested linear jerk (m/s^3), capped by the arm's configured maximum. // Unset uses that maximum. std::optional linear_jerk; - // Unset follows the arm config. False preserves the original streaming - // direction-following policy used by PBVS; true enables fixed-axis reversal. + // Unset follows the arm config. True crosses zero on same-axis reversals; + // false stops first near a reversal. Direction changes are smoothed in 3D. std::optional continuous_linear_reversal; // Capture the first applied command's measured TCP position and target // direction in Base. Useful for distance-based motion without caller FK. @@ -96,32 +98,6 @@ struct CartesianWrench { double tz{0.0}; }; -struct JointLimit { - double lower{0.0}; - double upper{0.0}; - double max_velocity{0.0}; - double max_acceleration{0.0}; - double max_torque{0.0}; -}; - -struct RobotModel { - std::string name; - std::string manufacturer; - std::string serial_number; - std::size_t dof{0}; - std::vector joint_names; - std::vector joint_limits; - double max_tcp_speed{0.0}; - double max_tcp_acceleration{0.0}; - double max_payload{0.0}; - - bool valid() const - { - return dof > 0 && joint_names.size() == dof && - (joint_limits.empty() || joint_limits.size() == dof); - } -}; - struct JointGroupState { std::vector position; std::vector velocity; @@ -139,6 +115,9 @@ struct JointTrajectoryPoint { double time_s{0.0}; std::vector position; std::vector velocity; + // Analytic derivatives; empty for trajectories without these derivatives. + std::vector acceleration; + std::vector jerk; }; using JointTrajectory = std::vector; @@ -185,12 +164,21 @@ struct MotionOptions { double velocity{0.0}; double acceleration{0.0}; double blend_radius{0.0}; - double jerk{5.0}; + double jerk{300.0}; std::vector joint_velocity_limits; bool asynchronous{false}; // Optional cooperative cancellation used by synchronous ActionQueue // motion. Drivers must not retain this callback after the command returns. std::function cancellation_requested; + // MoveJ/MoveP: called once with the validated trajectory, before execution. + // Runs synchronously; copy the data here and perform file I/O after motion. + std::function trajectory_callback; + // Optional MoveP constraint on the TCP pose in Base coordinates. Checked + // during joint-path search and discrete smoothed-trajectory validation. + // Runs synchronously and must return quickly; false rejects the sampled + // state. This checks the TCP only, not the complete robot geometry. + // Drivers must reject unsupported constraints and never retain this callback. + std::function is_tcp_pose_valid; }; struct ServoOptions { diff --git a/cmvr-es/config/devices/arm/arm.pb.txt b/cmvr-es/config/devices/arm/arm.pb.txt index 59b24597..f5540dc2 100644 --- a/cmvr-es/config/devices/arm/arm.pb.txt +++ b/cmvr-es/config/devices/arm/arm.pb.txt @@ -57,6 +57,25 @@ arm { } motion { + joint_path { + algorithm: RRT_CONNECT + rrt_connect { + timeout_s: 2.0 + range_rad: 0.2 + collision_check_step_rad: 0.02 + } + collision_checker { + urdf_path: "model/xiaoyan_description/dual_arm_collision.urdf" + ignored_pairs { first: "R_WRIST_P_S" second: "R_WRIST_R_S" } + } + minimum_distance_m: 0.01 + } + joint_trajectory_smoother { + sample_period_s: 0.001 + quintic_bspline { + control_point_spacing_rad: 0.05 + } + } move_j { # MoveJ 轨迹完成后等待关节稳定的最长时间,单位为秒。 settle_timeout_s: 2.0 @@ -66,12 +85,6 @@ arm { settle_velocity_tolerance_rad_s: 0.02 # 位置和速度连续满足条件的采样次数。 settle_stable_sample_count: 3 - toppra_joint_motion_planner { - path_type: TOPPRA_PATH_TYPE_QUINTIC - sample_period_s: 0.001 - grid_size: 150 - high_grid_size: 300 - } } move_l { @@ -116,9 +129,17 @@ arm { angular_jerk_max: 12.0 linear_target_replan_threshold: 1e-4 angular_target_replan_threshold: 1e-4 - linear_reverse_cos_threshold: -0.8660254037844386 - linear_reverse_switch_speed_threshold: 1e-3 enforce_joint_acceleration_limits: true + adaptive_speed { + # 启用接近关节限位时的提前降速;降低后的目标仍经过 S 曲线平滑。 + # 关闭此开关不影响失解后的制动。 + enable: true + # 预判时间,单位秒;0.15 即 150 ms,实际窗口还会考虑 S 曲线停止时间。 + lookahead_s: 0.15 + # 允许速度低于原目标的 10% 时,平滑停稳后报错;0 关闭此阈值。 + # 这是停止阈值,不会强行维持最低速度,也不限制启动阶段的瞬时速度。 + min_speed_ratio: 0.10 + } line_deviation_check { enable: true line_deviation_warn_m: 0.01 @@ -217,12 +238,23 @@ arm { } motion { - move_j { - toppra_joint_motion_planner { - path_type: TOPPRA_PATH_TYPE_QUINTIC - sample_period_s: 0.001 - grid_size: 150 - high_grid_size: 300 + joint_path { + algorithm: RRT_CONNECT + rrt_connect { + timeout_s: 2.0 + range_rad: 0.2 + collision_check_step_rad: 0.02 + } + collision_checker { + urdf_path: "model/xiaoyan_description/dual_arm_collision.urdf" + ignored_pairs { first: "L_WRIST_P_S" second: "L_WRIST_R_S" } + } + minimum_distance_m: 0.01 + } + joint_trajectory_smoother { + sample_period_s: 0.001 + quintic_bspline { + control_point_spacing_rad: 0.05 } } @@ -268,9 +300,17 @@ arm { angular_jerk_max: 12.0 linear_target_replan_threshold: 1e-4 angular_target_replan_threshold: 1e-4 - linear_reverse_cos_threshold: -0.8660254037844386 - linear_reverse_switch_speed_threshold: 1e-3 enforce_joint_acceleration_limits: true + adaptive_speed { + # 启用接近关节限位时的提前降速;降低后的目标仍经过 S 曲线平滑。 + # 关闭此开关不影响失解后的制动。 + enable: true + # 预判时间,单位秒;0.15 即 150 ms,实际窗口还会考虑 S 曲线停止时间。 + lookahead_s: 0.15 + # 允许速度低于原目标的 10% 时,平滑停稳后报错;0 关闭此阈值。 + # 这是停止阈值,不会强行维持最低速度,也不限制启动阶段的瞬时速度。 + min_speed_ratio: 0.10 + } line_deviation_check { enable: true line_deviation_warn_m: 0.01 diff --git a/cmvr-es/config/devices/arm/arm_gen2_mujoco.pb.txt b/cmvr-es/config/devices/arm/arm_gen2_mujoco.pb.txt index f5c8d8f5..f16cdbe8 100644 --- a/cmvr-es/config/devices/arm/arm_gen2_mujoco.pb.txt +++ b/cmvr-es/config/devices/arm/arm_gen2_mujoco.pb.txt @@ -56,6 +56,26 @@ arm { } motion { + joint_path { + algorithm: RRT_CONNECT + rrt_connect { + timeout_s: 2.0 + range_rad: 0.2 + collision_check_step_rad: 0.02 + } + collision_checker { + urdf_path: "model/gen2/collision/robot_collision.urdf" + ignored_pairs { first: "arm_link_5_2" second: "arm_link_7_2" } + ignored_pairs { first: "body_link" second: "arm_link_2_2" } + } + minimum_distance_m: 0.01 + } + joint_trajectory_smoother { + sample_period_s: 0.001 + quintic_bspline { + control_point_spacing_rad: 0.05 + } + } move_j { # MoveJ 轨迹完成后等待关节稳定的最长时间,单位为秒。 settle_timeout_s: 2.0 @@ -65,12 +85,6 @@ arm { settle_velocity_tolerance_rad_s: 0.02 # 位置和速度连续满足条件的采样次数。 settle_stable_sample_count: 3 - toppra_joint_motion_planner { - path_type: TOPPRA_PATH_TYPE_QUINTIC - sample_period_s: 0.001 - grid_size: 150 - high_grid_size: 300 - } } move_l { @@ -115,9 +129,17 @@ arm { angular_jerk_max: 12.0 linear_target_replan_threshold: 1e-4 angular_target_replan_threshold: 1e-4 - linear_reverse_cos_threshold: -0.8660254037844386 - linear_reverse_switch_speed_threshold: 1e-3 enforce_joint_acceleration_limits: true + adaptive_speed { + # 启用接近关节限位时的提前降速;降低后的目标仍经过 S 曲线平滑。 + # 关闭此开关不影响失解后的制动。 + enable: true + # 预判时间,单位秒;0.15 即 150 ms,实际窗口还会考虑 S 曲线停止时间。 + lookahead_s: 0.15 + # 允许速度低于原目标的 10% 时,平滑停稳后报错;0 关闭此阈值。 + # 这是停止阈值,不会强行维持最低速度,也不限制启动阶段的瞬时速度。 + min_speed_ratio: 0.10 + } line_deviation_check { enable: true line_deviation_warn_m: 0.01 diff --git a/cmvr-es/config/devices/arm/arm_mujoco.pb.txt b/cmvr-es/config/devices/arm/arm_mujoco.pb.txt index 6acc138b..d682461f 100644 --- a/cmvr-es/config/devices/arm/arm_mujoco.pb.txt +++ b/cmvr-es/config/devices/arm/arm_mujoco.pb.txt @@ -57,7 +57,28 @@ arm { } motion { + joint_path { + algorithm: RRT_CONNECT + rrt_connect { + timeout_s: 2.0 + range_rad: 0.2 + collision_check_step_rad: 0.02 + } + collision_checker { + urdf_path: "model/xiaoyan_description/dual_arm_collision.urdf" + ignored_pairs { first: "R_WRIST_P_S" second: "R_WRIST_R_S" } + } + minimum_distance_m: 0.01 + } + joint_trajectory_smoother { + sample_period_s: 0.001 + quintic_bspline { + control_point_spacing_rad: 0.05 + } + } move_j { + # 轨迹关节位置限位检查的数值容差,单位 rad;0 表示严格检查。 + joint_limit_tolerance_rad: 0.00001 # MoveJ 轨迹完成后等待关节稳定的最长时间,单位为秒。 settle_timeout_s: 2.0 # MoveJ 完成时允许的最大关节位置误差,单位为弧度。 @@ -66,12 +87,6 @@ arm { settle_velocity_tolerance_rad_s: 0.02 # 位置和速度连续满足条件的采样次数。 settle_stable_sample_count: 3 - toppra_joint_motion_planner { - path_type: TOPPRA_PATH_TYPE_QUINTIC - sample_period_s: 0.001 - grid_size: 150 - high_grid_size: 300 - } } move_l { @@ -116,9 +131,17 @@ arm { angular_jerk_max: 12.0 linear_target_replan_threshold: 1e-4 angular_target_replan_threshold: 1e-4 - linear_reverse_cos_threshold: -0.8660254037844386 - linear_reverse_switch_speed_threshold: 1e-3 enforce_joint_acceleration_limits: true + adaptive_speed { + # 启用接近关节限位时的提前降速;降低后的目标仍经过 S 曲线平滑。 + # 关闭此开关不影响失解后的制动。 + enable: true + # 预判时间,单位秒;0.15 即 150 ms,实际窗口还会考虑 S 曲线停止时间。 + lookahead_s: 0.15 + # 允许速度低于原目标的 10% 时,平滑停稳后报错;0 关闭此阈值。 + # 这是停止阈值,不会强行维持最低速度,也不限制启动阶段的瞬时速度。 + min_speed_ratio: 0.10 + } line_deviation_check { enable: true line_deviation_warn_m: 0.01 diff --git a/cmvr-es/config/devices/arm/arm_mujoco_qp.pb.txt b/cmvr-es/config/devices/arm/arm_mujoco_qp.pb.txt index 26b59ef0..ee8aa674 100644 --- a/cmvr-es/config/devices/arm/arm_mujoco_qp.pb.txt +++ b/cmvr-es/config/devices/arm/arm_mujoco_qp.pb.txt @@ -58,6 +58,25 @@ arm { } motion { + joint_path { + algorithm: RRT_CONNECT + rrt_connect { + timeout_s: 2.0 + range_rad: 0.2 + collision_check_step_rad: 0.02 + } + collision_checker { + urdf_path: "model/xiaoyan_description/dual_arm_collision.urdf" + ignored_pairs { first: "R_WRIST_P_S" second: "R_WRIST_R_S" } + } + minimum_distance_m: 0.01 + } + joint_trajectory_smoother { + sample_period_s: 0.001 + quintic_bspline { + control_point_spacing_rad: 0.05 + } + } move_j { # MoveJ 轨迹完成后等待关节稳定的最长时间,单位为秒。 settle_timeout_s: 2.0 @@ -67,12 +86,6 @@ arm { settle_velocity_tolerance_rad_s: 0.02 # 位置和速度连续满足条件的采样次数。 settle_stable_sample_count: 3 - toppra_joint_motion_planner { - path_type: TOPPRA_PATH_TYPE_QUINTIC - sample_period_s: 0.001 - grid_size: 150 - high_grid_size: 300 - } } move_l { @@ -111,15 +124,23 @@ arm { pinocchio_cartesian_motion_planner { linear_velocity_max: 2.0 linear_acceleration_max: 15.0 - linear_jerk_max: 60.0 + linear_jerk_max: 500.0 angular_velocity_max: 1.0 angular_acceleration_max: 5.0 angular_jerk_max: 12.0 linear_target_replan_threshold: 1e-4 angular_target_replan_threshold: 1e-4 - linear_reverse_cos_threshold: -0.8660254037844386 - linear_reverse_switch_speed_threshold: 1e-3 enforce_joint_acceleration_limits: true + adaptive_speed { + # 启用接近关节限位时的提前降速;降低后的目标仍经过 S 曲线平滑。 + # 关闭此开关不影响失解后的制动。 + enable: true + # 预判时间,单位秒;0.15 即 150 ms,实际窗口还会考虑 S 曲线停止时间。 + lookahead_s: 0.15 + # 允许速度低于原目标的 10% 时,平滑停稳后报错;0 关闭此阈值。 + # 这是停止阈值,不会强行维持最低速度,也不限制启动阶段的瞬时速度。 + min_speed_ratio: 0.10 + } line_deviation_check { enable: true line_deviation_warn_m: 0.005 diff --git a/cmvr-es/config/devices/arm/arm_qp.pb.txt b/cmvr-es/config/devices/arm/arm_qp.pb.txt index 6ad6d6d7..249a5493 100644 --- a/cmvr-es/config/devices/arm/arm_qp.pb.txt +++ b/cmvr-es/config/devices/arm/arm_qp.pb.txt @@ -58,6 +58,25 @@ arm { } motion { + joint_path { + algorithm: RRT_CONNECT + rrt_connect { + timeout_s: 2.0 + range_rad: 0.2 + collision_check_step_rad: 0.02 + } + collision_checker { + urdf_path: "model/xiaoyan_description/dual_arm_collision.urdf" + ignored_pairs { first: "R_WRIST_P_S" second: "R_WRIST_R_S" } + } + minimum_distance_m: 0.01 + } + joint_trajectory_smoother { + sample_period_s: 0.001 + quintic_bspline { + control_point_spacing_rad: 0.05 + } + } move_j { # MoveJ 轨迹完成后等待关节稳定的最长时间,单位为秒。 settle_timeout_s: 2.0 @@ -67,12 +86,6 @@ arm { settle_velocity_tolerance_rad_s: 0.02 # 位置和速度连续满足条件的采样次数。 settle_stable_sample_count: 3 - toppra_joint_motion_planner { - path_type: TOPPRA_PATH_TYPE_QUINTIC - sample_period_s: 0.001 - grid_size: 150 - high_grid_size: 300 - } } move_l { @@ -111,15 +124,23 @@ arm { pinocchio_cartesian_motion_planner { linear_velocity_max: 0.8 linear_acceleration_max: 10.0 - linear_jerk_max: 60.0 + linear_jerk_max: 200.0 angular_velocity_max: 1.0 angular_acceleration_max: 5.0 angular_jerk_max: 12.0 linear_target_replan_threshold: 1e-4 angular_target_replan_threshold: 1e-4 - linear_reverse_cos_threshold: -0.8660254037844386 - linear_reverse_switch_speed_threshold: 1e-3 enforce_joint_acceleration_limits: true + adaptive_speed { + # 启用接近关节限位时的提前降速;降低后的目标仍经过 S 曲线平滑。 + # 关闭此开关不影响失解后的制动。 + enable: true + # 预判时间,单位秒;0.15 即 150 ms,实际窗口还会考虑 S 曲线停止时间。 + lookahead_s: 0.15 + # 允许速度低于原目标的 10% 时,平滑停稳后报错;0 关闭此阈值。 + # 这是停止阈值,不会强行维持最低速度,也不限制启动阶段的瞬时速度。 + min_speed_ratio: 0.10 + } line_deviation_check { enable: true line_deviation_warn_m: 0.01 diff --git a/cmvr-es/config/devices/arm/ethercat_dual_arm.pb.txt b/cmvr-es/config/devices/arm/ethercat_dual_arm.pb.txt index ef6171c4..c5a1094e 100644 --- a/cmvr-es/config/devices/arm/ethercat_dual_arm.pb.txt +++ b/cmvr-es/config/devices/arm/ethercat_dual_arm.pb.txt @@ -57,6 +57,25 @@ arm { } motion { + joint_path { + algorithm: RRT_CONNECT + rrt_connect { + timeout_s: 2.0 + range_rad: 0.2 + collision_check_step_rad: 0.02 + } + collision_checker { + urdf_path: "model/xiaoyan_description/dual_arm_collision.urdf" + ignored_pairs { first: "R_WRIST_P_S" second: "R_WRIST_R_S" } + } + minimum_distance_m: 0.01 + } + joint_trajectory_smoother { + sample_period_s: 0.001 + quintic_bspline { + control_point_spacing_rad: 0.05 + } + } move_j { # MoveJ 轨迹完成后等待关节稳定的最长时间,单位为秒。 settle_timeout_s: 2.0 @@ -66,12 +85,6 @@ arm { settle_velocity_tolerance_rad_s: 0.02 # 位置和速度连续满足条件的采样次数。 settle_stable_sample_count: 3 - toppra_joint_motion_planner { - path_type: TOPPRA_PATH_TYPE_QUINTIC - sample_period_s: 0.001 - grid_size: 150 - high_grid_size: 300 - } } move_l { @@ -116,9 +129,17 @@ arm { angular_jerk_max: 12.0 linear_target_replan_threshold: 1e-4 angular_target_replan_threshold: 1e-4 - linear_reverse_cos_threshold: -0.8660254037844386 - linear_reverse_switch_speed_threshold: 1e-3 enforce_joint_acceleration_limits: true + adaptive_speed { + # 启用接近关节限位时的提前降速;降低后的目标仍经过 S 曲线平滑。 + # 关闭此开关不影响失解后的制动。 + enable: true + # 预判时间,单位秒;0.15 即 150 ms,实际窗口还会考虑 S 曲线停止时间。 + lookahead_s: 0.15 + # 允许速度低于原目标的 10% 时,平滑停稳后报错;0 关闭此阈值。 + # 这是停止阈值,不会强行维持最低速度,也不限制启动阶段的瞬时速度。 + min_speed_ratio: 0.10 + } line_deviation_check { enable: true line_deviation_warn_m: 0.01 @@ -217,12 +238,23 @@ arm { } motion { - move_j { - toppra_joint_motion_planner { - path_type: TOPPRA_PATH_TYPE_QUINTIC - sample_period_s: 0.001 - grid_size: 150 - high_grid_size: 300 + joint_path { + algorithm: RRT_CONNECT + rrt_connect { + timeout_s: 2.0 + range_rad: 0.2 + collision_check_step_rad: 0.02 + } + collision_checker { + urdf_path: "model/xiaoyan_description/dual_arm_collision.urdf" + ignored_pairs { first: "L_WRIST_P_S" second: "L_WRIST_R_S" } + } + minimum_distance_m: 0.01 + } + joint_trajectory_smoother { + sample_period_s: 0.001 + quintic_bspline { + control_point_spacing_rad: 0.05 } } @@ -268,9 +300,17 @@ arm { angular_jerk_max: 12.0 linear_target_replan_threshold: 1e-4 angular_target_replan_threshold: 1e-4 - linear_reverse_cos_threshold: -0.8660254037844386 - linear_reverse_switch_speed_threshold: 1e-3 enforce_joint_acceleration_limits: true + adaptive_speed { + # 启用接近关节限位时的提前降速;降低后的目标仍经过 S 曲线平滑。 + # 关闭此开关不影响失解后的制动。 + enable: true + # 预判时间,单位秒;0.15 即 150 ms,实际窗口还会考虑 S 曲线停止时间。 + lookahead_s: 0.15 + # 允许速度低于原目标的 10% 时,平滑停稳后报错;0 关闭此阈值。 + # 这是停止阈值,不会强行维持最低速度,也不限制启动阶段的瞬时速度。 + min_speed_ratio: 0.10 + } line_deviation_check { enable: true line_deviation_warn_m: 0.01 diff --git a/cmvr-es/config/manager/device_manager.pb.txt b/cmvr-es/config/manager/device_manager.pb.txt index 49439ea8..8889676b 100644 --- a/cmvr-es/config/manager/device_manager.pb.txt +++ b/cmvr-es/config/manager/device_manager.pb.txt @@ -6,42 +6,42 @@ device_manager { id: "mujoco_world" type: DEVICE_TYPE_MUJOCO_WORLD config_file: "devices/mujoco/right_arm_eye_to_hand_world.pb.txt" - enable: false + enable: true } devices { id: "right_arm_mujoco_motors" type: DEVICE_TYPE_MOTOR_SYSTEM config_file: "devices/motor/mujoco_motors.pb.txt" - enable: false + enable: true } devices { id: "mujoco_right_arm" type: DEVICE_TYPE_ROBOT_ARM config_file: "devices/arm/arm_mujoco_qp.pb.txt" - enable: false + enable: true } devices { id: "mujoco_viewer" type: DEVICE_TYPE_MUJOCO_VIEWER config_file: "devices/mujoco/mujoco_viewer.pb.txt" - enable: false + enable: true } devices { id: "mujoco_hand_cam" type: DEVICE_TYPE_CAMERA config_file: "devices/camera/camera.pb.txt" - enable: false + enable: true } devices { id: "mujoco_external_touch_cam" type: DEVICE_TYPE_CAMERA config_file: "devices/camera/camera.pb.txt" - enable: false + enable: true } devices { @@ -77,7 +77,7 @@ device_manager { id: "mujoco_zero_touch_dexhand" type: DEVICE_TYPE_DEXHAND config_file: "devices/dexhand/dexhand.pb.txt" - enable: false + enable: true } devices { diff --git a/cmvr-es/config/manager/task_manager.pb.txt b/cmvr-es/config/manager/task_manager.pb.txt index 387eebcc..1cc961c0 100644 --- a/cmvr-es/config/manager/task_manager.pb.txt +++ b/cmvr-es/config/manager/task_manager.pb.txt @@ -4,7 +4,7 @@ task_manager { type: TASK_TYPE_TOUCH_SCREEN run_mode: TASK_RUN_MODE_PERIODIC_STEP control_period_s: 0.001 - config_file: "tasks/touch_screen_task/touch_screen_task.pb.txt" + config_file: "tasks/touch_screen_task/touch_screen_task_mujoco.pb.txt" enable: true } tasks { @@ -27,6 +27,6 @@ task_manager { type: TASK_TYPE_QUIC_EDGE run_mode: TASK_RUN_MODE_BLOCKING_SERVICE config_file: "tasks/quic_edge_task/quic_edge_task.pb.txt" - enable: true + enable: false } } diff --git a/cmvr-es/config/tasks/touch_screen_task/touch_screen_task.pb.txt b/cmvr-es/config/tasks/touch_screen_task/touch_screen_task.pb.txt index 69820cdd..ad8af832 100644 --- a/cmvr-es/config/tasks/touch_screen_task/touch_screen_task.pb.txt +++ b/cmvr-es/config/tasks/touch_screen_task/touch_screen_task.pb.txt @@ -14,8 +14,11 @@ touch_screen_task { } initialization { + # 开始前使用 MoveJ 回到初始关节位置。 before_start: false + # 正常完成后使用 MoveP 回到初始关节位置。 after_finish: true + after_failure: true joint_positions { joint_name: "R_SHOULDER_P" rad: -0.338732 } joint_positions { joint_name: "R_SHOULDER_R" rad: 1.265943 } joint_positions { joint_name: "R_SHOULDER_Y" rad: 1.572396 } @@ -25,9 +28,9 @@ touch_screen_task { joint_positions { joint_name: "R_WRIST_R" rad: 0.1347 } velocity: 1.0 acceleration: 2.0 - # 当前关节位置误差小于该值时跳过初始化 MoveJ,单位为弧度。 + # 当前关节位置误差小于该值时跳过初始位置回位,单位为弧度。 skip_position_tolerance_rad: 0.01 - # 当前关节速度小于该值时才允许跳过初始化 MoveJ,单位为弧度/秒。 + # 当前关节速度小于该值时才允许跳过初始位置回位,单位为弧度/秒。 skip_velocity_tolerance_rad_s: 0.1 } @@ -88,15 +91,15 @@ touch_screen_task { stable_frames: 2 # 对齐及到位暂停各自的超时时间(秒);暂停从对齐成功时重新计时。 timeout_s: 20.0 - # 到位后暂停;暂停超时结束任务,after_finish 为 true 时尝试回初始位置。 + # 到位后暂停;暂停超时结束任务,after_failure 为 true 时尝试回初始位置。 pause_when_reached: false } touch { speed_l { - twist_tool { x: 0.0 y: -0.08 z: 0.0 rx: 0.0 ry: 0.0 rz: 0.0 } + twist_tool { x: 0.0 y: -0.04 z: 0.0 rx: 0.0 ry: 0.0 rz: 0.0 } acceleration: 5.0 - linear_jerk: 10.0 + linear_jerk: 50.0 max_distance_m: 0.03 } tactile { @@ -109,9 +112,9 @@ touch_screen_task { } retract { - twist_tool { x: 0.0 y: 0.08 z: 0.0 rx: 0.0 ry: 0.0 rz: 0.0 } + twist_tool { x: 0.0 y: 0.04 z: 0.0 rx: 0.0 ry: 0.0 rz: 0.0 } acceleration: 8.0 - linear_jerk: 40.0 # m/s^3,约束接触后的减速和连续换向。 + linear_jerk: 100.0 # m/s^3,约束接触后的减速和连续换向。 # TCP 后退目标距离,单位为米。 distance_m: 0.01 } diff --git a/cmvr-es/config/tasks/touch_screen_task/touch_screen_task_mujoco.pb.txt b/cmvr-es/config/tasks/touch_screen_task/touch_screen_task_mujoco.pb.txt index 5bacf38f..c0f79928 100644 --- a/cmvr-es/config/tasks/touch_screen_task/touch_screen_task_mujoco.pb.txt +++ b/cmvr-es/config/tasks/touch_screen_task/touch_screen_task_mujoco.pb.txt @@ -14,8 +14,11 @@ touch_screen_task { } initialization { + # 开始前使用 MoveJ 回到初始关节位置。 before_start: true + # 正常完成后使用 MoveP 回到初始关节位置。 after_finish: true + after_failure: true joint_positions { joint_name: "R_SHOULDER_P" rad: -0.2423 } joint_positions { joint_name: "R_SHOULDER_R" rad: 1.2929 } joint_positions { joint_name: "R_SHOULDER_Y" rad: 1.61 } @@ -25,9 +28,9 @@ touch_screen_task { joint_positions { joint_name: "R_WRIST_R" rad: -0.08 } velocity: 2.0 acceleration: 3.0 - # 当前关节位置误差小于该值时跳过初始化 MoveJ,单位为弧度。 + # 当前关节位置误差小于该值时跳过初始位置回位,单位为弧度。 skip_position_tolerance_rad: 0.001 - # 当前关节速度小于该值时才允许跳过初始化 MoveJ,单位为弧度/秒。 + # 当前关节速度小于该值时才允许跳过初始位置回位,单位为弧度/秒。 skip_velocity_tolerance_rad_s: 0.01 } @@ -51,6 +54,17 @@ touch_screen_task { } } + approach { + # MoveP 复用 alignment.target,position_offset_G 表达在屏幕 G 坐标系。 + enable: true + velocity: 0.65 # rad/s + acceleration: 1.7 # rad/s^2 + jerk: 30.0 # rad/s^3 + timeout_s: 10.0 + # TCP 沿屏幕外法向的最小距离,仅检查 TCP,不覆盖整臂碰撞。 + minimum_clearance_m: 0.01 + } + alignment { calibration { # TCP P 相对于屏幕 Hand Tag H 的目标姿态 @@ -97,15 +111,15 @@ touch_screen_task { stable_frames: 5 # 对齐及到位暂停各自的超时时间(秒);暂停从对齐成功时重新计时。 timeout_s: 20.0 - # 到位后暂停;暂停超时结束任务,after_finish 为 true 时尝试回初始位置。 + # 到位后暂停;暂停超时结束任务,after_failure 为 true 时尝试回初始位置。 pause_when_reached: false } touch { speed_l { - twist_tool { x: 0.0 y: -0.04 z: 0.0 rx: 0.0 ry: 0.0 rz: 0.0 } - acceleration: 6.0 - linear_jerk: 60.0 # m/s^3,接近阶段请求值,受机械臂 linear_jerk_max 限制。 + twist_tool { x: 0.0 y: -0.02 z: 0.0 rx: 0.0 ry: 0.0 rz: 0.0 } + acceleration: 10.0 + linear_jerk: 100.0 # m/s^3,接近阶段请求值,受机械臂 linear_jerk_max 限制。 max_distance_m: 0.02 } tactile { @@ -118,10 +132,10 @@ touch_screen_task { } retract { - twist_tool { x: 0.0 y: 0.06 z: 0.0 rx: 0.0 ry: 0.0 rz: 0.0 } - acceleration: 4.0 - linear_jerk: 60.0 # m/s^3,保持仿真机械臂原有的 jerk 上限。 + twist_tool { x: 0.0 y: 0.08 z: 0.0 rx: 0.0 ry: 0.0 rz: 0.0 } + acceleration: 10.0 + linear_jerk: 500.0 # m/s^3,保持仿真机械臂原有的 jerk 上限。 # TCP 后退目标距离,单位为米。 - distance_m: 0.05 + distance_m: 0.02 } } diff --git a/cmvr-es/curves/CMakeLists.txt b/cmvr-es/curves/CMakeLists.txt new file mode 100644 index 00000000..1bc714de --- /dev/null +++ b/cmvr-es/curves/CMakeLists.txt @@ -0,0 +1,10 @@ +find_package(Eigen3 CONFIG REQUIRED) + +add_library(curves SHARED + bspline/src/quintic_bspline.cpp + s_curve/src/s_curve.cpp +) +target_include_directories(curves PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/..") +target_link_libraries(curves PUBLIC Eigen3::Eigen) +add_library(cmvr_es::curves ALIAS curves) +install(TARGETS curves LIBRARY DESTINATION lib) diff --git a/cmvr-es/curves/bspline/include/quintic_bspline.h b/cmvr-es/curves/bspline/include/quintic_bspline.h new file mode 100644 index 00000000..08ae3d8c --- /dev/null +++ b/cmvr-es/curves/bspline/include/quintic_bspline.h @@ -0,0 +1,56 @@ +#pragma once + +#include +#include +#include +#include + +#include + +namespace cmvr { + +// A time-domain degree-five B-spline with analytic derivatives. The input +// polyline guides the control points; intermediate waypoints are not exact +// interpolation constraints. The caller must collision-check the resulting +// curve, which can cut corners of the input path. +class QuinticBSpline final { +public: + // Limits are positive per-joint magnitudes in rad/s, rad/s^2 and rad/s^3. + // Duration is uniformly increased until derivative control-point bounds + // satisfy all limits. Start/end positions are exact, with zero v and a. + // control_point_spacing_rad sets the positive joint-space reference spacing. + // Invalid input throws invalid_argument; cancellation/numerical failure + // throws runtime_error. A stationary path uses minimum_duration_s. + static std::shared_ptr create( + const std::vector>& waypoints, + const std::vector& velocity_limits, + const std::vector& acceleration_limits, + const std::vector& jerk_limits, + double minimum_duration_s, + const std::function& cancelled = {}, + double control_point_spacing_rad = 0.05); + + Eigen::RowVector2d timeInterval() const; + // Finite times are clamped to the trajectory interval. NaN/Inf are invalid. + Eigen::VectorXd q(double t) const; + Eigen::VectorXd qd(double t) const; + Eigen::VectorXd qdd(double t) const; + Eigen::VectorXd qddd(double t) const; + std::vector knotTimes() const; + + // Conservative absolute bounds over the whole trajectory, orders 0..3. + Eigen::VectorXd derivativeBounds(int order) const; + // Each column is one control point. Knots use normalized time [0, 1]. + const Eigen::MatrixXd& controlPoints() const { return controls_[0]; } + const std::vector& knots() const { return knots_[0]; } + +private: + QuinticBSpline() = default; + Eigen::VectorXd evaluate(double t, int order) const; + + std::array controls_; + std::array, 4> knots_; + double duration_s_{0.0}; +}; + +} // namespace cmvr diff --git a/cmvr-es/curves/bspline/src/quintic_bspline.cpp b/cmvr-es/curves/bspline/src/quintic_bspline.cpp new file mode 100644 index 00000000..c92d86b8 --- /dev/null +++ b/cmvr-es/curves/bspline/src/quintic_bspline.cpp @@ -0,0 +1,264 @@ +#include "curves/bspline/include/quintic_bspline.h" + +#include +#include +#include +#include + +namespace cmvr { +namespace { + +constexpr int kDegree = 5; +constexpr std::size_t kMaxControlPoints = 10000; +constexpr double kSmoothstepMaximumSlope = 1.875; +constexpr double kDurationMargin = 1.001; + +void checkCancelled(const std::function& cancelled) +{ + if (cancelled && cancelled()) { + throw std::runtime_error("B-spline planning cancelled"); + } +} + +void validateLimits(const std::vector& limits, std::size_t dof) +{ + if (limits.size() != dof || + !std::all_of(limits.begin(), limits.end(), [](double value) { + return std::isfinite(value) && value > 0.0; + })) { + throw std::invalid_argument("B-spline limits must be positive, finite and match the DOF"); + } +} + +// The degree-five blossom of 10u^3-15u^4+6u^5 is e3-3e4+6e5, +// where ek is the elementary symmetric polynomial of the five arguments. +// Thus a straight reference path reproduces one global minimum-jerk quintic, +// rather than acquiring speed ripples from a uniform spatial control polygon. +double smoothstepControl(const std::vector& knots, std::size_t index) +{ + const bool mirror = knots[index + 3] > 0.5; + std::array elementary{}; + elementary[0] = 1.0; + for (int argument = 1; argument <= kDegree; ++argument) { + const double value = mirror ? 1.0 - knots[index + argument] : knots[index + argument]; + for (int order = argument; order >= 1; --order) { + elementary[order] += value * elementary[order - 1]; + } + } + const double progress = elementary[3] - 3.0 * elementary[4] + 6.0 * elementary[5]; + return std::clamp(mirror ? 1.0 - progress : progress, 0.0, 1.0); +} + +} // namespace + +std::shared_ptr QuinticBSpline::create( + const std::vector>& waypoints, + const std::vector& velocity_limits, + const std::vector& acceleration_limits, + const std::vector& jerk_limits, + double minimum_duration_s, + const std::function& cancelled, + double control_point_spacing_rad) +{ + if (waypoints.empty() || waypoints.size() > kMaxControlPoints || + waypoints.front().empty() || !std::isfinite(minimum_duration_s) || + minimum_duration_s <= 0.0) { + throw std::invalid_argument("B-spline requires a nonempty path and positive finite duration"); + } + if (!std::isfinite(control_point_spacing_rad) || control_point_spacing_rad <= 0.0) { + throw std::invalid_argument("B-spline control-point spacing must be positive and finite"); + } + const auto dof = waypoints.front().size(); + if (dof > static_cast(std::numeric_limits::max())) { + throw std::invalid_argument("B-spline DOF is too large"); + } + validateLimits(velocity_limits, dof); + validateLimits(acceleration_limits, dof); + validateLimits(jerk_limits, dof); + checkCancelled(cancelled); + + std::vector vertices; + std::vector chord_lengths; + vertices.reserve(waypoints.size()); + chord_lengths.reserve(waypoints.size()); + double length = 0.0; + for (const auto& waypoint : waypoints) { + checkCancelled(cancelled); + if (waypoint.size() != dof || + !std::all_of(waypoint.begin(), waypoint.end(), [](double value) { + return std::isfinite(value); + })) { + throw std::invalid_argument("B-spline waypoints must be finite and have matching DOF"); + } + Eigen::VectorXd vertex = Eigen::Map( + waypoint.data(), static_cast(dof)); + if (!vertices.empty()) { + const Eigen::VectorXd delta = vertex - vertices.back(); + const double distance = delta.stableNorm(); + if (!std::isfinite(distance)) { + throw std::invalid_argument("B-spline path length is not finite"); + } + if (distance == 0.0) { + continue; + } + length += distance; + if (!std::isfinite(length)) { + throw std::invalid_argument("B-spline path length is not finite"); + } + } + vertices.push_back(std::move(vertex)); + chord_lengths.push_back(length); + } + + // Three equal controls at each clamped endpoint impose q'=q''=0 without + // stopping at any of the interior reference points. + // Check the floating-point count before conversion, including tiny spacing. + const long double interval_count = std::ceil( + static_cast(length) * kSmoothstepMaximumSlope / control_point_spacing_rad); + if (!std::isfinite(interval_count) || interval_count > kMaxControlPoints - kDegree) { + throw std::invalid_argument("B-spline path exceeds the control-point limit"); + } + const auto intervals = std::max(1, static_cast(interval_count)); + const auto control_count = intervals + kDegree; + auto trajectory = std::shared_ptr(new QuinticBSpline); + auto& knots = trajectory->knots_[0]; + knots.assign(control_count + kDegree + 1, 0.0); + for (std::size_t i = kDegree + 1; i < control_count; ++i) { + knots[i] = static_cast(i - kDegree) / intervals; + } + std::fill(knots.begin() + static_cast(control_count), knots.end(), 1.0); + + auto& controls = trajectory->controls_[0]; + controls.resize(static_cast(dof), static_cast(control_count)); + for (int i = 0; i < 3; ++i) { + controls.col(i) = vertices.front(); + controls.col(static_cast(control_count) - 1 - i) = vertices.back(); + } + std::size_t segment = 1; + for (std::size_t i = 3; i + 3 < control_count; ++i) { + checkCancelled(cancelled); + const double distance = length * smoothstepControl(knots, i); + while (segment + 1 < vertices.size() && chord_lengths[segment] < distance) { + ++segment; + } + const double alpha = std::clamp( + (distance - chord_lengths[segment - 1]) / + (chord_lengths[segment] - chord_lengths[segment - 1]), + 0.0, 1.0); + controls.col(static_cast(i)) = + vertices[segment - 1] + alpha * (vertices[segment] - vertices[segment - 1]); + } + + // Differentiating a B-spline gives another B-spline: fewer controls, lower + // degree, and the first/last knot removed at each derivative order. + for (int order = 1; order <= 3; ++order) { + const auto& previous_controls = trajectory->controls_[order - 1]; + const auto& previous_knots = trajectory->knots_[order - 1]; + const int previous_degree = kDegree - order + 1; + auto& derivative_controls = trajectory->controls_[order]; + derivative_controls.resize(previous_controls.rows(), previous_controls.cols() - 1); + trajectory->knots_[order].assign(previous_knots.begin() + 1, previous_knots.end() - 1); + for (Eigen::Index i = 0; i < derivative_controls.cols(); ++i) { + checkCancelled(cancelled); + const double span = previous_knots[i + previous_degree + 1] - previous_knots[i + 1]; + derivative_controls.col(i) = + (previous_controls.col(i + 1) - previous_controls.col(i)) * (previous_degree / span); + } + if (!derivative_controls.allFinite()) { + throw std::runtime_error("B-spline derivatives are not finite"); + } + } + + // The derivative curve lies in the convex hull of its derivative controls, + // so these bounds hold continuously, including between controller samples. + long double required_duration = 0.0L; + for (int order = 1; order <= 3; ++order) { + const auto& limits = order == 1 ? velocity_limits : + order == 2 ? acceleration_limits : jerk_limits; + const Eigen::VectorXd bounds = trajectory->controls_[order].cwiseAbs().rowwise().maxCoeff(); + for (Eigen::Index joint = 0; joint < bounds.size(); ++joint) { + const long double ratio = static_cast(bounds[joint]) / limits[joint]; + const long double duration = order == 1 ? ratio : + order == 2 ? std::sqrt(ratio) : std::cbrt(ratio); + required_duration = std::max(required_duration, duration); + } + } + const long double duration = std::max( + static_cast(minimum_duration_s), required_duration * kDurationMargin); + if (!std::isfinite(duration) || duration > std::numeric_limits::max()) { + throw std::runtime_error("B-spline duration is not representable"); + } + trajectory->duration_s_ = static_cast(duration); + checkCancelled(cancelled); + return trajectory; +} + +Eigen::RowVector2d QuinticBSpline::timeInterval() const +{ + return {0.0, duration_s_}; +} + +Eigen::VectorXd QuinticBSpline::evaluate(double t, int order) const +{ + if (!std::isfinite(t)) { + throw std::invalid_argument("B-spline evaluation time must be finite"); + } + const auto& controls = controls_[order]; + const auto& knots = knots_[order]; + const int degree = kDegree - order; + const double u = std::clamp(t, 0.0, duration_s_) / duration_s_; + Eigen::VectorXd result; + if (u <= 0.0) { + result = controls.col(0); + } else if (u >= 1.0) { + result = controls.col(controls.cols() - 1); + } else { + const auto span = static_cast( + std::upper_bound(knots.begin(), knots.end(), u) - knots.begin() - 1); + Eigen::MatrixXd work = controls.middleCols(span - degree, degree + 1); + for (int level = 1; level <= degree; ++level) { + for (int j = degree; j >= level; --j) { + const auto left = span - degree + j; + const double alpha = (u - knots[left]) / + (knots[span + j - level + 1] - knots[left]); + work.col(j) = work.col(j - 1) + alpha * (work.col(j) - work.col(j - 1)); + } + } + result = work.col(degree); + } + for (int derivative = 0; derivative < order; ++derivative) { + result /= duration_s_; + } + return result; +} + +Eigen::VectorXd QuinticBSpline::q(double t) const { return evaluate(t, 0); } +Eigen::VectorXd QuinticBSpline::qd(double t) const { return evaluate(t, 1); } +Eigen::VectorXd QuinticBSpline::qdd(double t) const { return evaluate(t, 2); } +Eigen::VectorXd QuinticBSpline::qddd(double t) const { return evaluate(t, 3); } + +std::vector QuinticBSpline::knotTimes() const +{ + std::vector times; + for (double knot : knots_[0]) { + const double time = knot * duration_s_; + if (times.empty() || time != times.back()) { + times.push_back(time); + } + } + return times; +} + +Eigen::VectorXd QuinticBSpline::derivativeBounds(int order) const +{ + if (order < 0 || order > 3) { + throw std::invalid_argument("B-spline derivative order must be between zero and three"); + } + Eigen::VectorXd bounds = controls_[order].cwiseAbs().rowwise().maxCoeff(); + for (int derivative = 0; derivative < order; ++derivative) { + bounds /= duration_s_; + } + return bounds; +} + +} // namespace cmvr diff --git a/cmvr-es/algorithms/motion_planner/base_motion/motion_profile/s_curve/include/s_curve.h b/cmvr-es/curves/s_curve/include/s_curve.h similarity index 59% rename from cmvr-es/algorithms/motion_planner/base_motion/motion_profile/s_curve/include/s_curve.h rename to cmvr-es/curves/s_curve/include/s_curve.h index bc796ada..ee1d323d 100644 --- a/cmvr-es/algorithms/motion_planner/base_motion/motion_profile/s_curve/include/s_curve.h +++ b/cmvr-es/curves/s_curve/include/s_curve.h @@ -3,7 +3,7 @@ // /** * @file s_curve.h - * @brief 严格点到点位置 S 曲线轨迹生成器 + * @brief 位置与速度 S 曲线的数学计算 * * 实现标准 7 段式位置 S 曲线速度剖面: * 1. 加加速度上升段(加速度逐渐增大) @@ -14,7 +14,8 @@ * 6. 匀减速段 * 7. 加加速度上升段(减速度逐渐降到 0) * - * 本类只负责严格点到点 profile 规划与采样,不负责实时目标跟踪。 + * 同时支持三段式速度切换剖面。只负责剖面计算与按时间采样, + * 不保存运行状态,不负责实时目标更新、周期推进或反馈同步。 */ #pragma once @@ -70,7 +71,45 @@ struct SCurveProfile }; /** - * @brief 严格点到点位置 S 曲线规划器 + * @brief 单次速度切换的 S 曲线剖面参数 + * + * 本类表示从任意 (v0, a0) 连续规划到 (vf, 0) 的 3 段 jerk-limited profile: + * + * seg1: jerk = j1, duration = t1 + * seg2: jerk = j2, duration = t2 (当前实现 j2 = 0) + * seg3: jerk = j3, duration = t3 + * + * 其中 j1/j3 为 ±j_max,j2 为 0。 + */ +struct SCurveVelocityProfile +{ + double t1; + double t2; + double t3; + + double total_time; + + double j1; + double j2; + double j3; + + double v0; + double a0; + double vf; + + bool valid; + + SCurveVelocityProfile() + : t1(0.0), t2(0.0), t3(0.0) + , total_time(0.0) + , j1(0.0), j2(0.0), j3(0.0) + , v0(0.0), a0(0.0), vf(0.0) + , valid(false) + {} +}; + +/** + * @brief 位置与速度 S 曲线的数学计算和采样,不保存运行状态 */ class SCurve { @@ -81,9 +120,9 @@ public: * @param max_acceleration 最大加速度 (rad/s²) * @param max_jerk 最大加加速度 (rad/s³) */ - SCurve(double max_velocity = 3.0, - double max_acceleration = 10.0, - double max_jerk = 50.0); + SCurve(double max_velocity = 3.0, + double max_acceleration = 10.0, + double max_jerk = 50.0); /** * @brief 设置运动约束 @@ -103,8 +142,9 @@ public: * @param end_velocity 终止速度(默认 0) * @return 计算得到的剖面参数 */ - SCurveProfile calculateProfile(double start_position, double end_position, - double start_velocity = 0.0, double end_velocity = 0.0); + SCurveProfile calculatePositionProfile(double start_position, double end_position, + double start_velocity = 0.0, + double end_velocity = 0.0) const; /** * @brief 给定剖面下,获取时刻 t 的位置 @@ -151,6 +191,36 @@ public: std::vector& velocities, std::vector& accelerations) const; + /** + * @brief 计算单次速度切换剖面 + */ + SCurveVelocityProfile calculateVelocityProfile(double start_velocity, + double end_velocity, + double start_acceleration = 0.0) const; + + /** + * @brief 给定剖面下,获取时刻 t 的速度 + */ + double getVelocityAtTime(const SCurveVelocityProfile& profile, double t) const; + + /** + * @brief 给定剖面下,获取时刻 t 的加速度 + */ + double getAccelerationAtTime(const SCurveVelocityProfile& profile, double t) const; + + /** + * @brief 给定剖面下,获取时刻 t 的 jerk + */ + double getJerkAtTime(const SCurveVelocityProfile& profile, double t) const; + + /** + * @brief 按固定时间间隔生成轨迹点 + */ + void generateTrajectory(const SCurveVelocityProfile& profile, double dt, + std::vector& velocities, + std::vector& accelerations, + std::vector& jerks) const; + private: double max_velocity_; double max_acceleration_; @@ -158,10 +228,35 @@ private: static constexpr double EPSILON = 1e-9; static constexpr double VELOCITY_THRESHOLD = 1e-6; + static constexpr double ACCELERATION_THRESHOLD = 1e-6; double computeSegmentJerk(const SCurveProfile& profile, double t) const; void calculateShortProfile(SCurveProfile& profile) const; void calculateLongProfile(SCurveProfile& profile) const; + + /** + * @brief 判断 profile 是否满足速度上限 + */ + bool isVelocityLimitSatisfied(const SCurveVelocityProfile& profile) const; + + /** + * @brief 计算完整剖面终点状态 + */ + void integrateWholeProfile(const SCurveVelocityProfile& profile, + double& v_end, + double& a_end) const; + + static double clamp(double value, double min_val, double max_val) + { + return std::max(min_val, std::min(max_val, value)); + } + + static double sign(double value) + { + if (value > EPSILON) return 1.0; + if (value < -EPSILON) return -1.0; + return 0.0; + } }; } // namespace cmvr diff --git a/cmvr-es/algorithms/motion_planner/base_motion/motion_profile/s_curve/src/s_curve.cpp b/cmvr-es/curves/s_curve/src/s_curve.cpp similarity index 62% rename from cmvr-es/algorithms/motion_planner/base_motion/motion_profile/s_curve/src/s_curve.cpp rename to cmvr-es/curves/s_curve/src/s_curve.cpp index 720becab..3f34f338 100644 --- a/cmvr-es/algorithms/motion_planner/base_motion/motion_profile/s_curve/src/s_curve.cpp +++ b/cmvr-es/curves/s_curve/src/s_curve.cpp @@ -4,11 +4,11 @@ /** - * @file s_curve_generator.cpp - * @brief S 曲线轨迹生成器实现 + * @file s_curve.cpp + * @brief 位置与速度 S 曲线数学实现 */ -#include "algorithms/motion_planner/base_motion/motion_profile/s_curve/include/s_curve.h" +#include "curves/s_curve/include/s_curve.h" #include #include #include @@ -35,8 +35,8 @@ void SCurve::getConstraints(double& max_velocity, double& max_acceleration, doub max_jerk = max_jerk_; } -SCurveProfile SCurve::calculateProfile(double start_position, double end_position, - double start_velocity, double end_velocity) +SCurveProfile SCurve::calculatePositionProfile(double start_position, double end_position, + double start_velocity, double end_velocity) const { SCurveProfile profile; profile.j_max = max_jerk_; @@ -539,4 +539,336 @@ void SCurve::generateTrajectory(const SCurveProfile& profile, double dt, } } +double SCurve::getVelocityAtTime(const SCurveVelocityProfile& profile, double t) const +{ + if (!profile.valid) { + return profile.v0; + } + + if (t <= 0.0) { + return profile.v0; + } + if (t >= profile.total_time) { + return profile.vf; + } + + double v = profile.v0; + double a = profile.a0; + + auto process_segment = [&](double dt, double jerk) { + v += a * dt + 0.5 * jerk * dt * dt; + a += jerk * dt; + }; + + // seg1 + if (t <= profile.t1) { + process_segment(t, profile.j1); + return v; + } + process_segment(profile.t1, profile.j1); + + // seg2 + const double t_after_1 = t - profile.t1; + if (t_after_1 <= profile.t2) { + process_segment(t_after_1, profile.j2); + return v; + } + process_segment(profile.t2, profile.j2); + + // seg3 + const double t_after_2 = t_after_1 - profile.t2; + process_segment(t_after_2, profile.j3); + return v; } + +double SCurve::getAccelerationAtTime(const SCurveVelocityProfile& profile, double t) const +{ + if (!profile.valid) { + return profile.a0; + } + + if (t <= 0.0) { + return profile.a0; + } + if (t >= profile.total_time) { + return 0.0; + } + + double a = profile.a0; + + auto process_segment = [&](double dt, double jerk) { + a += jerk * dt; + }; + + // seg1 + if (t <= profile.t1) { + process_segment(t, profile.j1); + return a; + } + process_segment(profile.t1, profile.j1); + + // seg2 + const double t_after_1 = t - profile.t1; + if (t_after_1 <= profile.t2) { + process_segment(t_after_1, profile.j2); + return a; + } + process_segment(profile.t2, profile.j2); + + // seg3 + const double t_after_2 = t_after_1 - profile.t2; + process_segment(t_after_2, profile.j3); + return a; +} + +double SCurve::getJerkAtTime(const SCurveVelocityProfile& profile, double t) const +{ + if (!profile.valid) { + return 0.0; + } + + if (t <= 0.0 || t >= profile.total_time) { + return 0.0; + } + + if (t <= profile.t1) { + return profile.j1; + } + if (t <= profile.t1 + profile.t2) { + return profile.j2; + } + return profile.j3; +} + +void SCurve::integrateWholeProfile(const SCurveVelocityProfile& profile, + double& v_end, + double& a_end) const +{ + double v = profile.v0; + double a = profile.a0; + + auto process_segment = [&](double dt, double jerk) { + v += a * dt + 0.5 * jerk * dt * dt; + a += jerk * dt; + }; + + process_segment(profile.t1, profile.j1); + process_segment(profile.t2, profile.j2); + process_segment(profile.t3, profile.j3); + + v_end = v; + a_end = a; +} + +bool SCurve::isVelocityLimitSatisfied(const SCurveVelocityProfile& profile) const +{ + if (!profile.valid) { + return true; + } + + std::vector check_times; + check_times.reserve(8); + + check_times.push_back(0.0); + check_times.push_back(profile.t1); + check_times.push_back(profile.t1 + profile.t2); + check_times.push_back(profile.total_time); + + // seg1 内部若 acceleration 过零,则 velocity 可能在段内出现极值 + if (std::abs(profile.j1) > EPSILON && profile.t1 > EPSILON) { + const double tz = -profile.a0 / profile.j1; + if (tz > EPSILON && tz < profile.t1 - EPSILON) { + check_times.push_back(tz); + } + } + + for (double t : check_times) { + const double v = getVelocityAtTime(profile, t); + if (std::abs(v) > max_velocity_ + 1e-7) { + return false; + } + } + + return true; +} + +SCurveVelocityProfile SCurve::calculateVelocityProfile(double start_velocity, + double end_velocity, + double start_acceleration) const +{ + SCurveVelocityProfile best; + best.v0 = clamp(start_velocity, -max_velocity_, max_velocity_); + best.a0 = clamp(start_acceleration, -max_acceleration_, max_acceleration_); + best.vf = clamp(end_velocity, -max_velocity_, max_velocity_); + + if (max_jerk_ <= EPSILON || max_acceleration_ <= EPSILON) { + // 退化情况:这里不做特殊退化规划,直接返回 invalid + return best; + } + + const double v0 = best.v0; + const double a0 = best.a0; + const double vf = best.vf; + + // 目标方向坐标:尽量统一到“signed frame 下 Δv >= 0” + double s = sign(vf - v0); + if (std::abs(vf - v0) <= VELOCITY_THRESHOLD) { + s = 1.0; + } + + const double dv = s * (vf - v0); // >= 0 + const double a0s = s * a0; // signed frame 下的初始 acceleration + const double j = max_jerk_; + const double amax = max_acceleration_; + + auto normalize_nonnegative = [](double x) { + return (x < 0.0 && x > -1e-10) ? 0.0 : x; + }; + + auto try_candidate = [&](double t1, double t2, double t3, + double j1s, double j2s, double j3s) { + t1 = normalize_nonnegative(t1); + t2 = normalize_nonnegative(t2); + t3 = normalize_nonnegative(t3); + + if (t1 < 0.0 || t2 < 0.0 || t3 < 0.0) { + return; + } + + SCurveVelocityProfile cand; + cand.t1 = t1; + cand.t2 = t2; + cand.t3 = t3; + cand.total_time = t1 + t2 + t3; + + cand.j1 = s * j1s; + cand.j2 = s * j2s; + cand.j3 = s * j3s; + + cand.v0 = v0; + cand.a0 = a0; + cand.vf = vf; + cand.valid = true; + + double vend = 0.0; + double aend = 0.0; + integrateWholeProfile(cand, vend, aend); + + if (std::abs(vend - vf) > 1e-5) { + return; + } + if (std::abs(aend) > 1e-5) { + return; + } + if (!isVelocityLimitSatisfied(cand)) { + return; + } + + if (!best.valid || cand.total_time < best.total_time) { + best = cand; + } + }; + + // ---------------- UDU 三角形(无平台) ---------------- + { + // Δv = (2A^2 - a0^2)/(2j) + const double A2 = 0.5 * (2.0 * j * dv + a0s * a0s); + if (A2 >= -1e-10) { + const double A = std::sqrt(std::max(0.0, A2)); + if (A <= amax + 1e-10 && A >= a0s - 1e-10) { + const double t1 = (A - a0s) / j; + const double t2 = 0.0; + const double t3 = A / j; + try_candidate(t1, t2, t3, +j, 0.0, -j); + } + } + } + + // ---------------- UDU 梯形(有平台) ---------------- + { + const double A = amax; + if (A > EPSILON && A >= a0s - 1e-10) { + const double base = (2.0 * A * A - a0s * a0s) / (2.0 * j); + const double t1 = (A - a0s) / j; + const double t2 = (dv - base) / A; + const double t3 = A / j; + try_candidate(t1, t2, t3, +j, 0.0, -j); + } + } + + // ---------------- DUD 三角形(无平台) ---------------- + { + // Δv = (a0^2 - 2B^2)/(2j) + const double B2 = 0.5 * (a0s * a0s - 2.0 * j * dv); + if (B2 >= -1e-10) { + const double B = std::sqrt(std::max(0.0, B2)); + if (B <= amax + 1e-10 && B >= -a0s - 1e-10) { + const double t1 = (a0s + B) / j; + const double t2 = 0.0; + const double t3 = B / j; + try_candidate(t1, t2, t3, -j, 0.0, +j); + } + } + } + + // ---------------- DUD 梯形(有平台) ---------------- + { + const double B = amax; + if (B > EPSILON && B >= -a0s - 1e-10) { + const double base = (a0s * a0s - 2.0 * B * B) / (2.0 * j); + const double t1 = (a0s + B) / j; + const double t2 = (base - dv) / B; + const double t3 = B / j; + try_candidate(t1, t2, t3, -j, 0.0, +j); + } + } + + // 已到终点附近 + if (!best.valid && + std::abs(vf - v0) <= VELOCITY_THRESHOLD && + std::abs(a0) <= ACCELERATION_THRESHOLD) { + best.valid = false; + best.total_time = 0.0; + best.v0 = v0; + best.a0 = a0; + best.vf = vf; + } + + return best; +} + +void SCurve::generateTrajectory(const SCurveVelocityProfile& profile, double dt, + std::vector& velocities, + std::vector& accelerations, + std::vector& jerks) const +{ + velocities.clear(); + accelerations.clear(); + jerks.clear(); + + if (!profile.valid || profile.total_time <= 0.0 || dt <= 0.0) { + velocities.push_back(profile.v0); + accelerations.push_back(profile.a0); + jerks.push_back(0.0); + return; + } + + const int num_points = static_cast(std::ceil(profile.total_time / dt)) + 1; + velocities.reserve(num_points); + accelerations.reserve(num_points); + jerks.reserve(num_points); + + for (double t = 0.0; t <= profile.total_time; t += dt) { + velocities.push_back(getVelocityAtTime(profile, t)); + accelerations.push_back(getAccelerationAtTime(profile, t)); + jerks.push_back(getJerkAtTime(profile, t)); + } + + if (velocities.empty() || std::abs(velocities.back() - profile.vf) > VELOCITY_THRESHOLD) { + velocities.push_back(profile.vf); + accelerations.push_back(0.0); + jerks.push_back(0.0); + } +} + +} // namespace cmvr diff --git a/cmvr-es/devices/arm/motor_robot_arm/CMakeLists.txt b/cmvr-es/devices/arm/motor_robot_arm/CMakeLists.txt index a3270cd1..fd43d15a 100644 --- a/cmvr-es/devices/arm/motor_robot_arm/CMakeLists.txt +++ b/cmvr-es/devices/arm/motor_robot_arm/CMakeLists.txt @@ -1,5 +1,6 @@ add_library(motor_robot_arm SHARED src/motor_robot_arm.cpp + src/speed_l_executor.cpp ) target_include_directories(motor_robot_arm PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) @@ -10,7 +11,9 @@ target_link_libraries(motor_robot_arm PRIVATE cmvr_es::algorithms::arm_motion cmvr_es::ik_solver - cmvr_es::algorithms::arm_control + cmvr_es::joint_path_planner + cmvr_es::joint_trajectory_smoother + cmvr_es::collision_checker cmvr_es::device::motor_manager cmvr_es::device::mujoco_motor_driver glog @@ -19,11 +22,24 @@ target_link_libraries(motor_robot_arm add_library(cmvr_es::device::motor_robot_arm ALIAS motor_robot_arm) install(TARGETS motor_robot_arm LIBRARY DESTINATION lib) +add_executable(speed_l_executor_test src/speed_l_executor_test.cpp) +target_link_libraries(speed_l_executor_test PRIVATE + cmvr_es::device::motor_robot_arm gtest gtest_main pthread) + add_executable(speedl_reversal_mujoco_test src/speedl_reversal_mujoco_test.cpp) target_link_libraries(speedl_reversal_mujoco_test PRIVATE cmvr_es::device::motor_robot_arm cmvr_es::device::motor_manager cmvr_es::device::mujoco_motor_driver cmvr_es::proto pthread) +add_executable(rrt_connect_mujoco_test src/rrt_connect_mujoco_test.cpp) +target_compile_definitions(rrt_connect_mujoco_test PRIVATE + CMVR_ES_SOURCE_DIR="${PROJECT_SOURCE_DIR}") +target_link_libraries(rrt_connect_mujoco_test PRIVATE + cmvr_es::device::motor_robot_arm cmvr_es::device::motor_manager + cmvr_es::ik_solver + cmvr_es::mujoco_world cmvr_es::mujoco_viewer + gtest gtest_main pthread) + add_executable(motor_robot_arm_mujoco_test src/motor_robot_arm_mujoco_test.cpp ) diff --git a/cmvr-es/devices/arm/motor_robot_arm/SPEEDL_REVERSAL.md b/cmvr-es/devices/arm/motor_robot_arm/SPEEDL_REVERSAL.md index 561872b9..2789848c 100644 --- a/cmvr-es/devices/arm/motor_robot_arm/SPEEDL_REVERSAL.md +++ b/cmvr-es/devices/arm/motor_robot_arm/SPEEDL_REVERSAL.md @@ -1,12 +1,35 @@ # speedL 连续换向与 MuJoCo 验证 -触控接近和回撤的同轴线速度换向使用固定轴上的有符号 S 曲线,从当前速度和加速度直接规划到反向目标。过零时保留加速度,不重置规划器。该模式下非同轴变向先停止再换轴;角速度仍使用原有策略。 +触控接近和回撤的同轴线速度换向使用固定轴上的有符号 S 曲线,从当前速度和加速度直接规划到反向目标。过零时保留加速度,不重置规划器。非同轴转向使用三维速度过渡,保持速度与加速度连续,并检查整个过渡的速度、加速度、jerk 模长上界。非连续模式与角速度近反向时,仍先停稳再反向。 -`SpeedLPlannerConfig.continuous_linear_reversal` 默认 true;`SpeedLOptions.continuous_linear_reversal` 可按命令覆盖。触控任务的 PBVS 对齐明确设为 false,保持原有的小角度方向跟随和低速换轴行为;接近及回撤设为 true。固定轴模式不适合方向不断变化的视觉对齐:小方向变化会累积到换轴阈值,导致反复停走。设为 false 也可用于与旧换向策略做同条件比较。运动中退出固定轴模式时会保留实际运动方向和加速度。 +`SpeedLPlannerConfig.continuous_linear_reversal` 默认 true;`SpeedLOptions.continuous_linear_reversal` 可按命令覆盖。触控任务的 PBVS 对齐明确设为 false,接近及回撤设为 true。两种模式的非同轴转向都使用受限向量过渡,不再直接转动速度方向或累积小角度后周期性停车。连续旋转的 Tool 目标可能存在跟随滞后;受限规划不承诺瞬时到达新方向。运动中切换模式保留实际速度和加速度。旧换向余弦阈值与切轴速度阈值配置已删除。 -`MotorRobotArm::speedL(velocity, SpeedLOptions, duration, frame)` 可以为本条命令指定 `linear_jerk`(m/s³)。未指定时使用机器人配置的 jerk;普通 `speedL(velocity, acceleration, duration, frame)` 仍可直接使用。控制线程将速度、加速度、jerk 作为同一命令读取。正常停止的收尾操作检查命令版本,避免清除之后提交的运动命令。 +`MotorRobotArm::speedL(velocity, SpeedLOptions, duration, frame)` 可以为本条命令指定 `linear_jerk`(m/s³)。未指定时使用机器人配置的 jerk;普通 `speedL(velocity, acceleration, duration, frame)` 转发到这一入口。控制线程将速度、加速度、jerk 作为同一命令读取,新命令到达时原子更新限值和换向策略。运行中的新限值请求被拒绝时,执行器使用上一次有效参数提交一次零目标停止;恢复停止也失败才走直接零速收尾,并记录失败日志。`speedL()` 提交是异步的,周期线程里的拒绝通过日志报告。正常停止收尾和失败处理都检查命令版本,避免清除之后提交的运动命令。 -机械臂的 `SpeedLPlannerConfig` 提供规划上限:速度保持按配置限幅;线加速度、角加速度分别取请求 `acceleration` 与各自配置上限的较小值;线性 jerk 取请求值与 `linear_jerk_max` 的较小值。省略 jerk 时使用配置上限。普通 `stopL` 的加速度也遵循此规则。未配置或无效的上限继续使用规划器默认值(线性 0.55/5/10,角向 1/5/12)。 +`SpeedLExecutor` 位于 `devices/arm/motor_robot_arm`,由 `MotorRobotArm` 创建和持有,随机械臂停止、关闭或析构结束周期线程;Task 通过机械臂的 `speedL` / `stopL` 接口使用它,不管理执行器生命周期。配置中的 `speed_l_controller.cartesian_velocity_controller` 字段继续保持兼容。 + +调用职责:`MotorRobotArm` 检查机械臂状态并提供电机读写;`SpeedLExecutor` 管理命令、控制周期和停止;`PinocchioCartesianVelocityPlanner` 将平滑后的末端速度映射为关节速度并做限位、偏差检查;`SCurvePlanner` 管理方向及 S 曲线运行状态,`SCurve` 只做数学计算。执行器统一处理周期和停止阈值的默认值。 + +笛卡尔规划接口位于 `algorithms/planner/cartesian/`:`cartesian_trajectory_planner.h` 定义 MoveL 接口,独立的 `cartesian_velocity_planner.h` 定义 speedL 在线接口,`cartesian_motion_planner_factory.h` 提供工厂。Pinocchio 实现在其 `pinocchio/` 子目录,`SCurvePlanner` 在其 `s_curve/` 子目录;数学核心 `SCurve` 留在 `curves/s_curve/`。关节路径规划另放在 `algorithms/planner/joint/`。类名、职责与调用方式保持不变,库和测试目标仍由 `algorithms/planner/CMakeLists.txt` 统一定义,构建输出位置保持不变。 + +```cpp +#include "algorithms/planner/cartesian/cartesian_velocity_planner.h" +#include "algorithms/planner/cartesian/cartesian_motion_planner_factory.h" +``` + +执行器只依赖 `CartesianVelocityPlanner` 在线接口,MoveL 接口保留在现有 `CartesianTrajectoryPlanner` 中。新命令调用一次 `submit(target, options, frame)`,每拍调用 `step(dt, q, qd)`;两者均由控制线程串行调用。`CartesianVelocityStep` 一次返回状态、关节速度命令、平滑后的 Base 目标 twist 和按需捕获的参考;失败时命令为空、twist 为零、参考无效。目标 twist 是关节限幅前的笛卡尔规划目标,不是实测 TCP 速度。旧的限值更新、独立捕获和规划器缓存 getter 接口已删除。 + +`PinocchioCartesianTrajectoryPlanner` 只实现 MoveL;`PinocchioCartesianVelocityPlanner` 只实现 speedL,独立持有在线目标和 SCurvePlanner。两个接口互不继承,`CartesianMotionPlannerFactory::createMoveL()` 和 `createSpeedL()` 分别创建并配置对应实例。两者共享机械臂的运动学求解器,机械臂切换到 MoveL 前先停止并等待速度控制线程退出。现有 protobuf 字段名保持兼容。 + +`SCurvePlanner` 初始化后每周期调用 `plan(target, frame, dt, base_R_tool)`;零目标表示平滑停止,相同目标继续已有曲线。`getAccelerationBase()` 是最终命令的区间平均加速度,`getJerkBase()` 按相邻区间中心时间差分,支持周期变化。没有反馈同步或独立停止状态入口。机械臂急停由 `MotorRobotArm` 关闭执行器并调用电机 quick stop。 + +`SCurvePlanner` 的限值必须为有限数且大于 1e-9,周期必须至少为 1e-9 秒,重规划阈值必须为有限非负数;非法初始速度、目标、周期、坐标系或 Tool 旋转矩阵中的非有限数会在修改状态前抛出 `std::invalid_argument`。Pinocchio 适配层把错误转为配置失败或 `InvalidArgument`。protobuf 限值与阈值为零时保留默认值,负数和非有限值拒绝。初始化速度超过上限会拒绝,不能只截断内部标量。动态降低限值时,若当前速度、加速度已超过新上限,或无法验证后续曲线满足新上限,拒绝更新并保留完整旧状态;不直接截断当前速度、加速度。标量曲线计算无解或产生非有限结果时抛出 `std::runtime_error`,适配层返回 `CommandFailed`。方向过渡候选未通过时继续推进已经验证的原曲线,再尝试新目标,不会冻结当前非零加速度。 + +参考捕获使用首次成功 `step` 的 TCP 位姿,Tool 目标由规划器锁定为该拍的 Base 方向;后续周期不重新旋转这一已锁定目标。执行器只在电机发送成功且命令版本仍匹配时发布参考。未请求捕获的 Tool 目标仍随每拍 Tool 坐标系转换。发送回调只接收关节速度,不再传递已由规划器处理的加速度。 + +每个规划周期合并计算当前 TCP 位姿和 Jacobian,当前直线偏差检查复用该位姿。启用直线偏差检查且正在平移时,仍单独计算预测下一周期的 FK 并复检。执行器复用关节状态和输出缓冲区。 + +机械臂的 `SpeedLPlannerConfig` 提供规划上限:速度保持按配置限幅;线加速度、角加速度分别取请求 `acceleration` 与各自配置上限的较小值;线性 jerk 取请求值与 `linear_jerk_max` 的较小值。省略 jerk 时使用配置上限。普通 `stopL` 的加速度也遵循此规则。未配置的上限使用规划器默认值(线性 0.55/5/10,角向 1/5/12),非法数值明确拒绝。 例如机械臂配置加速度 5、jerk 10 时,回撤请求 60/60 实际按 5/10 规划,请求 3/6 则按 3/6 规划。任务参数不能提高机械臂上限。 @@ -66,14 +89,16 @@ touch { `max_forward_mm` 是反向调用前采样点之后,实际 TCP 沿前进轴的最大正位移;`peak_at_ms` 是到达该最远点的时间;`actual_reverse_ms` 要求至少连续 5 次采样的轴向速度小于 -0.0001 m/s;`return_to_origin_ms` 是确认反向后返回调用时位置的时间。Tool 模式的 CSV 速度字段也表示沿锁定前进轴的投影。 -测试要求换向前实际速度为正、之后产生反向速度并退回起点,且控制器未提前退出;使用起点锁存时还要求参考有效。失败返回非零。该自由空间实验不包含屏幕接触、触觉延迟或硅胶形变,不能把返回起点时间直接当作屏幕抬起事件时间。 +测试要求换向前实际速度为正、之后产生反向速度并退回起点,且执行器未提前退出;使用起点锁存时还要求参考有效。停止后要求执行器退出 busy、TCP 实测线速度低于 0.01 m/s,再依次执行 `moveL`、恢复 `speedL`、停止和 `moveJ`,验证模式切换。`MODE_SWITCH` 日志记录 MoveL 位置误差、恢复运动的实际位移和停止残速。失败返回非零。该自由空间实验不包含屏幕接触、触觉延迟或硅胶形变,不能把返回起点时间直接当作屏幕抬起事件时间。 + +现有 `motor_robot_arm_mujoco_test` 默认打开可视化窗口;设置 `CMVR_MUJOCO_HEADLESS=1` 可在不创建窗口的情况下运行相同的 MoveJ、MoveL 和 speedL 仿真检查。 ## 回归测试 -构建并运行 `cartesian_twist_limiter_reversal_test`、`s_curve_velocity_planner_stop_test` 和 `cartesian_velocity_controller_test`。覆盖匀速/加速中换向、速度与 jerk 连续性、恰好过零、普通停止、非同轴转向、负速度反馈、停止/回撤竞争、成功发送后才发布回撤参考及非法参数拒绝。 +构建并运行 `s_curve_planner_reversal_test` 和 `speed_l_executor_test`。覆盖匀速/加速中换向、速度与 jerk 连续性、恰好过零、重复零目标平滑停止、非同轴转向、负速度下切换策略、停止/回撤竞争、成功发送后才发布回撤参考及非法参数拒绝。 -`pinocchio_speedl_limits_test` 使用真实 URDF 和生产规划器,采样输出速度并差分验证实际规划的速度、加速度、jerk 上限;覆盖超限请求、较小请求、省略 jerk、旧接口及停止、独立角加速度限幅和非法请求。测试不初始化电机。 +`pinocchio_speedl_limits_test` 使用真实 URDF 和生产规划器,采样输出速度并差分验证实际规划的速度、加速度、jerk 上限;覆盖超限请求、较小请求、省略 jerk、仅指定加速度及停止、独立角加速度限幅和非法请求。另验证未提交命令及单步失败时不返回旧输出,以及 Tool 参考锁定后与 Base 目标的持续输出一致。测试不初始化电机。 -对齐回归覆盖每 20 ms 小幅更新速度方向:显式关闭固定轴模式后,20 mm/s 的命令不会因方向变化反复降到零;同时验证对齐后启用连续换向仍能平滑过零,以及反向运动中退出固定轴模式不会翻转实际速度。 +对齐回归覆盖每 20 ms 小幅更新方向、单拍 0.01 rad 方向变化、持续旋转 Tool 目标和速度恰在上限的情况,直接对最终速度命令差分检查 a/j 模长,并验证没有周期性降零。另覆盖拒绝不兼容降限后未来轨迹不变、角限值失败不部分更新线限值,以及停止恢复只重试一次。同轴连续换向过零仍保留加速度。 运行时应优先加载当前构建的项目动态库,测试脚本已处理;不要把新可执行文件与 `output/lib` 的旧项目库混用。 diff --git a/cmvr-es/devices/arm/motor_robot_arm/include/motor_robot_arm.h b/cmvr-es/devices/arm/motor_robot_arm/include/motor_robot_arm.h index bd3f5c8d..1c869866 100644 --- a/cmvr-es/devices/arm/motor_robot_arm/include/motor_robot_arm.h +++ b/cmvr-es/devices/arm/motor_robot_arm/include/motor_robot_arm.h @@ -2,6 +2,7 @@ #define CMVR_ES_MOTOR_ROBOT_ARM_H #include +#include #include #include #include @@ -9,14 +10,19 @@ #include #include -#include "algorithms/motion_planner/arm_motion/cartesian_motion/cartesian_motion_planner.h" -#include "algorithms/motion_planner/arm_motion/joint_motion/joint_motion_planner.h" -#include "algorithms/controllers/arm_control/include/cartesian_velocity_controller.h" +#include "algorithms/planner/cartesian/cartesian_trajectory_planner.h" +#include "algorithms/smoother/joint_trajectory_smoother.h" +#include "devices/arm/motor_robot_arm/include/speed_l_executor.h" #include "cmvr/config/arm_config/arm_config.pb.h" #include "devices/arm/robot_arm.h" #include "algorithms/kinematics/ik_solver/common/include/ik_solver.h" #include "motor/manager/include/motor_manager.h" +namespace cmvr { +class JointPathPlanner; +class CollisionChecker; +} + namespace cmvr::device { class MotorRobotArm final : public RobotArm { @@ -33,7 +39,9 @@ public: ArmState getRobotState() const override; JointGroupState getJointState() const override; CartesianPose getTcpPose(FrameType frame = FrameType::Base) const override; - RobotMode getRobotMode() const override { return RobotMode::Idle; } + RobotMode getRobotMode() const override { + return isFault() ? RobotMode::Fault : (busy() ? RobotMode::Running : RobotMode::Idle); + } SafetyMode getSafetyMode() const override; ControlMode getControlMode() const override { return ControlMode::Position; } @@ -46,10 +54,10 @@ public: const JointTrajectory& path, const MotionOptions& options) override; Result setSpeedScaling(double scaling) override; - double getSpeedScaling() const override { return speed_scaling_; } + double getSpeedScaling() const override { return speed_scaling_.load(); } bool isProtectiveStopped() const override { return protective_stopped_.load(); } bool isEmergencyStopped() const override { return emergency_stopped_.load(); } - bool isFault() const override { return false; } + bool isFault() const override; Result moveJ(const JointPositionCommand& target, const MotionOptions& options) override; Result speedJ(const JointVelocityCommand& velocity, double acceleration, double duration) override; @@ -57,6 +65,14 @@ public: Result moveL(const CartesianPose& target, const MotionOptions& options, FrameType frame = FrameType::Base) override; + // IK -> RRTConnect -> quintic B-spline -> cyclic position commands. + // Synchronous; Base is absolute, Tool is relative to the current TCP. + // Joint velocity/acceleration/jerk limits use rad/s, rad/s², rad/s³. + Result moveP(const CartesianPose& target, + const MotionOptions& options, + FrameType frame = FrameType::Base) override; + Result moveP(const JointPositionCommand& target, + const MotionOptions& options) override; Result speedL(const CartesianVelocity& velocity, double acceleration, double duration, @@ -65,6 +81,7 @@ public: Result speedL(const CartesianVelocity& velocity, const SpeedLOptions& options, double duration, FrameType frame = FrameType::Base) override; SpeedLReference getSpeedLReference() const override; + Result getSpeedLResult() const override; Result stopMotion() override; Result startServoMode(const ServoOptions& options) override; @@ -81,7 +98,8 @@ public: Result powerOff() override { return torqueOff(); } Result brakeRelease() override; Result shutdown() override; - Result clearFault() override { return Result::success(); } + Result clearFault() override; + Result recoverSpeedLPlanningFault() override; Result unlockProtectiveStop() override; Result loadProgram(const std::string& program_name) override; Result playProgram() override; @@ -104,18 +122,32 @@ private: std::optional safetyStopResult_(const std::string& command, bool interrupted = false) const; Result quickStopMotors_(); + // Already scaled/planned velocities; never apply speed_scaling_ here. + Result sendJointVelocity_(const JointVelocityCommand& velocity); bool validatePositionCommand_(const JointPositionCommand& cmd, std::string& error) const; bool validateVelocityCommand_(const JointVelocityCommand& cmd, std::string& error) const; std::shared_ptr getMotor_(const std::string& joint_name) const; bool readArmState_(std::vector& q_now, std::vector& qd_now) const; std::vector readJointPosition_() const; Result stopCartesianMotionAndWait_(); - Result waitForJointTarget_(const std::vector& target) const; + // Resolve the goal from the stopped start state while holding mutex_, then + // share path planning, smoothing, validation and execution for both targets. + Result planAndExecuteJointPath_( + const MotionOptions& options, + const std::function&, std::vector&)>& resolve_goal); + Result waitForJointTarget_(const std::vector& target, + const std::function& is_cancelled = {}, + const std::string& command = "moveJ") const; + bool planRecoveryTrajectory_(const std::vector& current_position, + const JointTrajectory& recorded_trajectory, + const MotionOptions& options, + JointTrajectory& replay_trajectory) const; bool configureAlgorithms_(); + bool configureJointPathPlanner_(); bool executeMoveLTrajectory_(const CartesianJointTrajectory& trajectory); - static CartesianVelocityController::Config toCartesianVelocityControllerConfig_( + static SpeedLExecutor::Config toSpeedLExecutorConfig_( const config::CartesianVelocityControllerConfig& config); std::vector moveLJointVelocityLimits_(const std::vector& qd_max) const; static Result unsupported_(const std::string& name); @@ -131,12 +163,16 @@ private: std::shared_ptr motor_manager_{nullptr}; std::shared_ptr ik_solver_{nullptr}; - std::shared_ptr joint_planner_{nullptr}; - std::shared_ptr cartesian_planner_{nullptr}; - std::unique_ptr cartesian_velocity_controller_{nullptr}; + std::shared_ptr trajectory_smoother_; + std::shared_ptr joint_path_planner_; + std::unique_ptr path_collision_checker_; + double joint_trajectory_sample_period_s_{0.001}; + std::shared_ptr cartesian_planner_{nullptr}; + std::unique_ptr speed_l_executor_{nullptr}; - // MoveJ post-trajectory settling criteria. These defaults preserve the + // Joint-motion position-limit tolerance and post-trajectory settling criteria. These defaults preserve the // historical behavior when the optional arm configuration fields are absent. + double move_j_joint_limit_tolerance_rad_{1e-5}; double move_j_settle_timeout_s_{2.0}; double move_j_position_tolerance_rad_{2e-3}; double move_j_velocity_tolerance_rad_s_{2e-2}; @@ -144,7 +180,8 @@ private: mutable std::mutex mutex_; std::atomic busy_{false}; - double speed_scaling_{1.0}; + std::atomic joint_motion_stop_generation_{0}; + std::atomic speed_scaling_{1.0}; std::atomic protective_stopped_{false}; std::atomic emergency_stopped_{false}; std::atomic protective_recovery_active_{false}; diff --git a/cmvr-es/devices/arm/motor_robot_arm/include/speed_l_executor.h b/cmvr-es/devices/arm/motor_robot_arm/include/speed_l_executor.h new file mode 100644 index 00000000..09a6127f --- /dev/null +++ b/cmvr-es/devices/arm/motor_robot_arm/include/speed_l_executor.h @@ -0,0 +1,119 @@ +#ifndef CMVR_ES_SPEED_L_EXECUTOR_H +#define CMVR_ES_SPEED_L_EXECUTOR_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "algorithms/planner/cartesian/cartesian_velocity_planner.h" +#include "common/types/arm/arm_types.h" + +namespace cmvr::device { + +class SpeedLExecutor { +public: + struct Config { + double control_period_s{0.001}; + double stop_twist_norm{1e-9}; + double stop_command_velocity_norm{1e-3}; + double stop_measured_velocity_norm{1e-2}; + double stop_acceleration{0.5}; + double stop_timeout_s{2.0}; + }; + + using ReadStateCallback = std::function& q, std::vector& qd)>; + using SendVelocityCallback = std::function; + using ReadScalingCallback = std::function; + // Optional external clock: begin waits for a cycle and returns its period; + // end releases it, including when planning or I/O fails. + using BeginCycleCallback = std::function; + using EndCycleCallback = std::function; + + SpeedLExecutor(Config config, + std::shared_ptr planner, + std::size_t dof, + ReadStateCallback read_state, + SendVelocityCallback send_velocity, + ReadScalingCallback read_scaling = {}, + BeginCycleCallback begin_cycle = {}, + EndCycleCallback end_cycle = {}); + ~SpeedLExecutor(); + + SpeedLExecutor(const SpeedLExecutor&) = delete; + SpeedLExecutor& operator=(const SpeedLExecutor&) = delete; + + Result speedL(const CartesianVelocity& velocity, const SpeedLOptions& options, + double duration, FrameType frame); + Result stop(std::optional acceleration = std::nullopt); + SpeedLReference getReference() const; + // Reports whether zero output and stationary feedback were confirmed. + // Earlier asynchronous errors remain available through lastResult(). + Result shutdown(); + Result lastResult() const; + bool faulted() const { return faulted_.load(); } + Result clearFault(); + // Automatic recovery is limited to planning failures with no I/O or stop + // failure. A fresh zero command and stationary feedback are required. + Result clearPlanningFault(); + // Include failures from arm-level stopping performed outside this worker. + void recordStopFailure(const Result& result); + + bool busy() const { return busy_.load(); } + double stopTimeoutS() const { return config_.stop_timeout_s; } + CartesianVelocity getCommandTwistBase() const; + +private: + void workerLoop_(); + void setStopTargetLocked_(double acceleration); + Result finish_(); + Result readState_(std::vector& q, std::vector& qd) const; + Result sendVelocity_(const JointVelocityCommand& velocity) const; + Result clearFault_(bool planning_only); + void recordFailureLocked_(const Result& result, bool planning_failure = false); + void finishCommand_(); + + static double velocityNorm_(const std::vector& velocity); + static double twistNorm_(const CartesianVelocity& velocity); + +private: + Config config_; + std::shared_ptr planner_; + std::size_t dof_{0}; + ReadStateCallback read_state_; + SendVelocityCallback send_velocity_; + ReadScalingCallback read_scaling_; + BeginCycleCallback begin_cycle_; + EndCycleCallback end_cycle_; + + std::thread worker_; + std::mutex lifecycle_mutex_; + mutable std::mutex mutex_; + std::condition_variable cv_; + std::atomic stop_requested_{false}; + bool command_active_{false}; + bool finishing_{false}; + bool reset_required_{true}; + CartesianVelocity target_twist_{}; + FrameType target_frame_{FrameType::Base}; + SpeedLOptions target_options_{}; + SpeedLReference reference_{}; + CartesianVelocity command_twist_snapshot_{}; + std::uint64_t command_version_{0}; + std::atomic busy_{false}; + std::atomic faulted_{false}; + bool planning_fault_{false}; + Result pending_stop_reason_{Result::success()}; + Result last_result_{Result::success()}; + Result shutdown_result_{Result::success()}; +}; + +} // namespace cmvr::device + +#endif // CMVR_ES_SPEED_L_EXECUTOR_H diff --git a/cmvr-es/devices/arm/motor_robot_arm/src/motor_robot_arm.cpp b/cmvr-es/devices/arm/motor_robot_arm/src/motor_robot_arm.cpp index f19328b2..f8cde2be 100644 --- a/cmvr-es/devices/arm/motor_robot_arm/src/motor_robot_arm.cpp +++ b/cmvr-es/devices/arm/motor_robot_arm/src/motor_robot_arm.cpp @@ -5,20 +5,26 @@ #include #include #include +#include #include #include #include -#include "algorithms/motion_planner/arm_motion/cartesian_motion/cartesian_motion_planner_factory.h" -#include "algorithms/motion_planner/arm_motion/joint_motion/joint_motion_planner_factory.h" +#include "algorithms/planner/cartesian/cartesian_motion_planner_factory.h" +#include "algorithms/smoother/joint_trajectory_smoother_factory.h" +#include "algorithms/smoother/joint_trajectory_validation.h" +#include "algorithms/planner/joint/joint_path_planner_factory.h" +#include "algorithms/collision_detection/include/collision_checker.h" #include "algorithms/kinematics/ik_solver/ik_solver_factory.h" #include "algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_dls_ik_solver.h" #include "common/base/protobuf_utils.h" +#include "common/config/config_files.h" #include "common/base/string_utils.h" #include "common/base/logging/logger.h" #include "common/math/transform_math.h" #include "motor/abstract_motor.h" #include "motor/manager/include/motor_manager.h" +#include "simulate/mujoco/mujoco_world/include/mujoco_world.h" namespace cmvr::device { @@ -78,8 +84,8 @@ MotorRobotArm::MotorRobotArm(const config::RobotArmConfig& cfg) MotorRobotArm::~MotorRobotArm() { - if (cartesian_velocity_controller_) { - cartesian_velocity_controller_->shutdown(); + if (speed_l_executor_) { + speed_l_executor_->shutdown(); } } @@ -149,31 +155,47 @@ ArmState MotorRobotArm::getRobotState() const state.moving = busy(); state.protective_stopped = protective_stopped; state.emergency_stopped = emergency_stopped; - state.speed_scaling = speed_scaling_; - state.robot_mode = RobotMode::Idle; + state.speed_scaling = speed_scaling_.load(); + state.robot_mode = getRobotMode(); + state.fault = isFault(); state.safety_mode = getSafetyMode(); state.control_mode = ControlMode::Position; state.actual_joint_state = getJointState(); - state.actual_tcp_pose = getTcpPose(); - state.actual_tcp_velocity = getSpeedLCommandTwistBase(); + auto solver = std::dynamic_pointer_cast(ik_solver_); + const auto& q = state.actual_joint_state.position; + const auto& qd = state.actual_joint_state.velocity; + Eigen::Matrix4d pose; + Eigen::MatrixXd jacobian; + Eigen::Matrix3d rotation; + if (solver && q.size() == getDof() && qd.size() == getDof() && + std::all_of(qd.begin(), qd.end(), [](double v) { return std::isfinite(v); }) && + solver->computePoseAndJacobianBaseAtQ(q, true, pose, jacobian, rotation)) { + state.actual_tcp_pose = common::math::matrixToPose(pose); + const Eigen::Matrix twist = jacobian * + Eigen::Map(qd.data(), static_cast(qd.size())); + state.actual_tcp_velocity = common::math::vectorToVelocity(twist); + } else { + state.fault = true; + state.robot_mode = RobotMode::Fault; + } return state; } JointGroupState MotorRobotArm::getJointState() const { JointGroupState state; - state.position.reserve(joint_names_.size()); - state.velocity.reserve(joint_names_.size()); - state.effort.reserve(joint_names_.size()); + std::vector> motors; + motors.reserve(joint_names_.size()); for (const auto& joint_name : joint_names_) { auto motor = getMotor_(joint_name); if (!motor) { - continue; + return state; } - state.position.push_back(motor->getQ()); - state.velocity.push_back(motor->getQd()); - state.effort.push_back(0.0); + motors.push_back(std::move(motor)); } + if (!motor_manager_ || !motor_manager_->readFeedbacksAtomic(motors, state.position, state.velocity)) + return {}; + state.effort.assign(motors.size(), 0.0); return state; } @@ -188,8 +210,11 @@ CartesianPose MotorRobotArm::getTcpPose(const FrameType frame) const if (!readArmState_(q_now, qd_now)) { return {}; } - Eigen::Matrix4d transform = Eigen::Matrix4d::Identity(); - if (!ik_solver_->fk(q_now, transform, true)) { + auto solver = std::dynamic_pointer_cast(ik_solver_); + Eigen::Matrix4d transform; + Eigen::MatrixXd jacobian; + Eigen::Matrix3d rotation; + if (!solver || !solver->computePoseAndJacobianBaseAtQ(q_now, true, transform, jacobian, rotation)) { return {}; } return common::math::matrixToPose(transform); @@ -203,7 +228,7 @@ SafetyMode MotorRobotArm::getSafetyMode() const if (protective_stopped_.load()) { return SafetyMode::ProtectiveStop; } - return SafetyMode::Normal; + return isFault() ? SafetyMode::Fault : SafetyMode::Normal; } Result MotorRobotArm::torqueOn() @@ -269,13 +294,12 @@ Result MotorRobotArm::calibrateZeroQ(const std::string& joint_name) Result MotorRobotArm::emergencyStop() { - if (cartesian_velocity_controller_) { - cartesian_velocity_controller_->shutdown(); - } protective_recovery_cancel_requested_.store(true); protective_stopped_.store(false); emergency_stopped_.store(true); - return quickStopMotors_(); + const auto stopped = quickStopMotors_(); + const auto joined = speed_l_executor_ ? speed_l_executor_->shutdown() : Result::success(); + return stopped.ok() ? joined : stopped; } Result MotorRobotArm::protectiveStop() @@ -283,14 +307,168 @@ Result MotorRobotArm::protectiveStop() if (emergency_stopped_.load()) { return Result::success(); } - if (cartesian_velocity_controller_) { - cartesian_velocity_controller_->shutdown(); - } protective_recovery_cancel_requested_.store(true); protective_stopped_.store(true); - return quickStopMotors_(); + const auto stopped = quickStopMotors_(); + const auto joined = speed_l_executor_ ? speed_l_executor_->shutdown() : Result::success(); + return stopped.ok() ? joined : stopped; } +bool MotorRobotArm::planRecoveryTrajectory_( + const std::vector& current_position, + const JointTrajectory& recorded_trajectory, + const MotionOptions& options, + JointTrajectory& replay_trajectory) const +{ + replay_trajectory.clear(); + if (current_position.empty() || recorded_trajectory.size() < 2 || + options.velocity <= 0.0 || + options.acceleration <= 0.0 || !std::isfinite(options.velocity) || + !std::isfinite(options.acceleration)) { + CMVR_LOG(ERROR) << "[MotorRobotArm][planRecoveryTrajectory] invalid trajectory or options"; + return false; + } + + const std::size_t dof = current_position.size(); + if (!options.joint_velocity_limits.empty() && + options.joint_velocity_limits.size() != dof) { + CMVR_LOG(ERROR) << "[MotorRobotArm][planRecoveryTrajectory] invalid DOF or joint limits"; + return false; + } + for (const double position : current_position) { + if (!std::isfinite(position)) { + CMVR_LOG(ERROR) << "[MotorRobotArm][planRecoveryTrajectory] non-finite current position"; + return false; + } + } + for (std::size_t i = 0; i < recorded_trajectory.size(); ++i) { + const auto& point = recorded_trajectory[i]; + if (!std::isfinite(point.time_s) || point.position.size() != dof || + (i > 0 && point.time_s <= recorded_trajectory[i - 1].time_s)) { + CMVR_LOG(ERROR) << "[MotorRobotArm][planRecoveryTrajectory] invalid recorded point: " + << i; + return false; + } + for (std::size_t joint = 0; joint < dof; ++joint) { + if (!std::isfinite(point.position[joint])) { + CMVR_LOG(ERROR) << "[MotorRobotArm][planRecoveryTrajectory] non-finite recorded point: " + << i; + return false; + } + } + } + + std::vector velocity_limits = options.joint_velocity_limits; + if (velocity_limits.empty()) { + velocity_limits.assign(dof, options.velocity); + } + for (std::size_t joint = 0; joint < velocity_limits.size(); ++joint) { + const double limit = velocity_limits[joint]; + if (!std::isfinite(limit) || limit <= 0.0) { + CMVR_LOG(ERROR) << "[MotorRobotArm][planRecoveryTrajectory] invalid joint velocity limit"; + return false; + } + } + + const double ramp_duration_s = std::max( + joint_trajectory_sample_period_s_, options.velocity / options.acceleration); + replay_trajectory.reserve(recorded_trajectory.size() + 2); + replay_trajectory.push_back(JointTrajectoryPoint{ + 0.0, current_position, std::vector(dof, 0.0)}); + + double replay_time_s = ramp_duration_s; + replay_trajectory.push_back(JointTrajectoryPoint{ + replay_time_s, + recorded_trajectory.back().position, + std::vector(dof, 0.0)}); + for (std::size_t i = recorded_trajectory.size() - 1; i > 0; --i) { + replay_time_s += recorded_trajectory[i].time_s - + recorded_trajectory[i - 1].time_s; + replay_trajectory.push_back(JointTrajectoryPoint{ + replay_time_s, + recorded_trajectory[i - 1].position, + std::vector(dof, 0.0)}); + } + replay_time_s += ramp_duration_s; + replay_trajectory.push_back(JointTrajectoryPoint{ + replay_time_s, + recorded_trajectory.front().position, + std::vector(dof, 0.0)}); + + const auto update_velocities = [&] { + for (auto& point : replay_trajectory) { + std::fill(point.velocity.begin(), point.velocity.end(), 0.0); + } + for (std::size_t i = 1; i + 1 < replay_trajectory.size(); ++i) { + const double dt = replay_trajectory[i + 1].time_s - + replay_trajectory[i - 1].time_s; + for (std::size_t joint = 0; joint < dof; ++joint) { + replay_trajectory[i].velocity[joint] = + (replay_trajectory[i + 1].position[joint] - + replay_trajectory[i - 1].position[joint]) / dt; + } + } + }; + + for (int iteration = 0; iteration < 3; ++iteration) { + update_velocities(); + double required_scale = 1.0; + std::vector previous_position_velocity(dof, 0.0); + for (std::size_t i = 0; i < replay_trajectory.size(); ++i) { + const auto& point = replay_trajectory[i]; + for (std::size_t joint = 0; joint < dof; ++joint) { + required_scale = std::max( + required_scale, + std::abs(point.velocity[joint]) / velocity_limits[joint]); + if (i == 0) { + continue; + } + + const double dt = point.time_s - + replay_trajectory[i - 1].time_s; + const double position_velocity = + (point.position[joint] - + replay_trajectory[i - 1].position[joint]) / dt; + const double acceleration = + (point.velocity[joint] - + replay_trajectory[i - 1].velocity[joint]) / dt; + required_scale = std::max( + required_scale, + std::abs(position_velocity) / velocity_limits[joint]); + required_scale = std::max( + required_scale, + std::sqrt(std::abs(acceleration) / + options.acceleration)); + if (i > 1) { + const double position_acceleration = + (position_velocity - + previous_position_velocity[joint]) / dt; + required_scale = std::max( + required_scale, + std::sqrt(std::abs(position_acceleration) / + options.acceleration)); + } + previous_position_velocity[joint] = position_velocity; + } + } + + if (required_scale <= 1.0 + 1e-9) { + break; + } + required_scale *= 1.001; + for (auto& point : replay_trajectory) { + point.time_s *= required_scale; + } + } + update_velocities(); + if (!validateJointTrajectory(replay_trajectory, dof, options)) { + replay_trajectory.clear(); + return false; + } + return true; +} + + Result MotorRobotArm::recoverProtectiveStop( const JointTrajectory& path, const MotionOptions& options) @@ -349,15 +527,9 @@ Result MotorRobotArm::recoverProtectiveStop( AtomicFlagGuard recovery_guard{protective_recovery_active_}; protective_recovery_cancel_requested_.store(false); - if (!joint_planner_) { - return Result::failure( - ArmErrorCode::RobotNotReady, - "protective recovery planner is not initialized"); - } - JointTrajectory recovery_trajectory; const auto planning_start = std::chrono::steady_clock::now(); - if (!joint_planner_->planReplay( + if (!planRecoveryTrajectory_( readJointPosition_(), path, options, recovery_trajectory)) { return Result::failure( ArmErrorCode::CommandFailed, @@ -460,17 +632,19 @@ Result MotorRobotArm::unlockProtectiveStop() Result MotorRobotArm::quickStopMotors_() { + Result result = Result::success(); for (const auto& joint_name : joint_names_) { auto motor = getMotor_(joint_name); if (!motor) { - return Result::failure(ArmErrorCode::RobotNotReady, "motor not found for joint: " + joint_name); + if (result.ok()) result = Result::failure(ArmErrorCode::RobotNotReady, "motor not found for joint: " + joint_name); + continue; } if (!motor->quickStop()) { - return Result::failure(ArmErrorCode::CommandFailed, - "failed to quick stop motor for joint: " + joint_name); + if (result.ok()) result = Result::failure(ArmErrorCode::CommandFailed, + "failed to quick stop motor for joint: " + joint_name); } } - return Result::success(); + return result; } bool MotorRobotArm::safetyStopRequested_() const @@ -498,15 +672,16 @@ std::optional MotorRobotArm::safetyStopResult_( Result MotorRobotArm::setSpeedScaling(const double scaling) { - if (scaling < 0.0 || scaling > 1.0) { + if (!std::isfinite(scaling) || scaling < 0.0 || scaling > 1.0) { return Result::failure(ArmErrorCode::InvalidArgument, "speed scaling must be in [0, 1]"); } - speed_scaling_ = scaling; + speed_scaling_.store(scaling); return Result::success(); } Result MotorRobotArm::moveJ(const JointPositionCommand& target, const MotionOptions& options) { + const auto stop_generation = joint_motion_stop_generation_.load(); if (const auto stopped = safetyStopResult_("moveJ")) { return *stopped; } @@ -514,11 +689,11 @@ Result MotorRobotArm::moveJ(const JointPositionCommand& target, const MotionOpti if (!validatePositionCommand_(target, error)) { return Result::failure(ArmErrorCode::InvalidArgument, error); } - if (!joint_planner_) { - return Result::failure(ArmErrorCode::RobotNotReady, "joint planner is not initialized"); + if (!trajectory_smoother_) { + return Result::failure(ArmErrorCode::RobotNotReady, "joint trajectory smoother is not initialized"); } - // speedL runs in a worker thread and sends speedJ commands. A moveJ + // speedL runs in a worker thread and sends joint velocity commands. A moveJ // trajectory writes cyclic-position commands directly, so allowing both // paths to run concurrently can overwrite the motor mode/target and cause // a short surge at the transition. Finish the Cartesian worker before @@ -533,14 +708,91 @@ Result MotorRobotArm::moveJ(const JointPositionCommand& target, const MotionOpti BusyGuard busy_guard{busy_}; std::lock_guard lock(mutex_); + Eigen::VectorXd lower, upper, joint_velocity; + if (!ik_solver_ || !ik_solver_->getJointPositionLimits(lower, upper) || + !ik_solver_->getJointVelocityLimits(joint_velocity) || + lower.size() != dof_ || upper.size() != dof_ || joint_velocity.size() != dof_) { + return Result::failure(ArmErrorCode::RobotNotReady, "moveJ cannot read joint limits"); + } + MotionOptions limits = options; + if (!options.joint_velocity_limits.empty() && options.joint_velocity_limits.size() != getDof()) { + return Result::failure(ArmErrorCode::InvalidArgument, "moveJ joint velocity limit count does not match DOF"); + } + limits.joint_velocity_limits.resize(getDof()); + for (std::size_t j = 0; j < getDof(); ++j) { + if (!std::isfinite(joint_velocity[j]) || joint_velocity[j] <= 0.0) { + return Result::failure(ArmErrorCode::RobotNotReady, "invalid joint velocity limit"); + } + double velocity = joint_velocity[j]; + if (!options.joint_velocity_limits.empty()) { + const double requested = options.joint_velocity_limits[j]; + if (!std::isfinite(requested) || requested <= 0.0) { + return Result::failure(ArmErrorCode::InvalidArgument, "invalid moveJ joint velocity limit"); + } + velocity = std::min(velocity, requested); + } + limits.joint_velocity_limits[j] = std::min(options.velocity, velocity); + } + const double scaling = speed_scaling_.load(); + if (!std::isfinite(scaling) || scaling <= 0.0 || scaling > 1.0) { + return Result::failure(ArmErrorCode::InvalidArgument, "invalid moveJ speed scaling"); + } + limits.velocity *= scaling; + for (auto& velocity : limits.joint_velocity_limits) velocity *= scaling; + const auto cancelled = [&] { + return safetyStopRequested_() || joint_motion_stop_generation_.load() != stop_generation || + (options.cancellation_requested && options.cancellation_requested()); + }; + limits.cancellation_requested = cancelled; JointTrajectory samples; - if (!joint_planner_->planMoveJ(readJointPosition_(), target, options, speed_scaling_, samples)) { - return Result::failure(ArmErrorCode::CommandFailed, "[MotorRobotArm] moveJ planner failed: " + id_); + if (!trajectory_smoother_->smooth({readJointPosition_(), target.position}, limits, + joint_trajectory_sample_period_s_, samples)) { + if (const auto stopped = safetyStopResult_("moveJ", true)) return *stopped; + if (cancelled()) return Result::failure(ArmErrorCode::CommandRejected, "moveJ cancelled"); + return Result::failure(ArmErrorCode::CommandFailed, "[MotorRobotArm] moveJ smoothing failed: " + id_); } if (samples.size() < 2) { return Result::success(); } + if (!validateJointTrajectory(samples, getDof(), limits)) { + return Result::failure(ArmErrorCode::CommandFailed, "moveJ B-spline violates motion limits"); + } + // Preserve the configured position tolerance, including the measured start. + for (const auto& sample : samples) { + if (sample.position.size() != getDof()) { + return Result::failure(ArmErrorCode::CommandFailed, "moveJ sample size mismatch"); + } + for (std::size_t j = 0; j < getDof(); ++j) { + const double position = sample.position[j]; + if (!std::isfinite(position) || position < lower[j] - move_j_joint_limit_tolerance_rad_ || + position > upper[j] + move_j_joint_limit_tolerance_rad_) { + std::ostringstream message; + message << std::setprecision(12) + << "moveJ B-spline trajectory exceeds joint limits: arm=" << id_ + << ", joint=" << joint_names_[j] << ", time_s=" << sample.time_s + << ", position_rad=" << position << ", lower_rad=" << lower[j] + << ", upper_rad=" << upper[j] + << ", tolerance_rad=" << move_j_joint_limit_tolerance_rad_; + CMVR_LOG(ERROR) << "[MotorRobotArm] " << message.str(); + return Result::failure(ArmErrorCode::CommandFailed, message.str()); + } + } + } + + if (options.trajectory_callback) { + try { + options.trajectory_callback(samples); + } catch (const std::exception& e) { + return Result::failure(ArmErrorCode::CommandFailed, + std::string("moveJ trajectory callback failed: ") + e.what()); + } catch (...) { + return Result::failure(ArmErrorCode::CommandFailed, "moveJ trajectory callback failed"); + } + } + if (cancelled()) { + return Result::failure(ArmErrorCode::CommandRejected, "moveJ cancelled"); + } std::vector> motors; motors.reserve(joint_names_.size()); for (const auto& joint_name : joint_names_) { @@ -559,13 +811,18 @@ Result MotorRobotArm::moveJ(const JointPositionCommand& target, const MotionOpti } const auto t0 = std::chrono::steady_clock::now(); - constexpr double fallback_dt = 0.001; std::vector command_velocity(motors.size(), 0.0); for (std::size_t k = 1; k < samples.size(); ++k) { + const auto& sample = samples[k]; + std::this_thread::sleep_until(t0 + std::chrono::duration_cast( + std::chrono::duration(sample.time_s))); if (const auto stopped = safetyStopResult_("moveJ", true)) { return *stopped; } - const auto& sample = samples[k]; + if (cancelled()) { + quickStopMotors_(); + return Result::failure(ArmErrorCode::CommandRejected, "moveJ cancelled"); + } if (sample.position.size() != motors.size()) { return Result::failure(ArmErrorCode::CommandFailed, "moveJ sample size mismatch"); } @@ -583,13 +840,6 @@ Result MotorRobotArm::moveJ(const JointPositionCommand& target, const MotionOpti return Result::failure(ArmErrorCode::CommandFailed, "failed to submit atomic cyclic position command"); } - if (k + 1 < samples.size()) { - const double next_t = samples[k + 1].time_s > 0.0 - ? samples[k + 1].time_s - : static_cast(k + 1) * fallback_dt; - std::this_thread::sleep_until(t0 + std::chrono::duration_cast( - std::chrono::duration(next_t))); - } } // Repeat the final position with zero velocity before checking feedback. @@ -605,7 +855,7 @@ Result MotorRobotArm::moveJ(const JointPositionCommand& target, const MotionOpti // evaluating feedback-based settling criteria. std::this_thread::sleep_for(std::chrono::milliseconds(1)); - const auto settle_result = waitForJointTarget_(target.position); + const auto settle_result = waitForJointTarget_(target.position, cancelled); if (!settle_result.ok()) { return settle_result; } @@ -616,38 +866,12 @@ Result MotorRobotArm::speedJ(const JointVelocityCommand& velocity, const double acceleration, const double duration) { - (void)acceleration; - if (const auto stopped = safetyStopResult_("speedJ")) { - return *stopped; - } - std::string error; - if (!validateVelocityCommand_(velocity, error)) { - return Result::failure(ArmErrorCode::InvalidArgument, error); - } - - { - std::lock_guard lock(mutex_); - for (std::size_t i = 0; i < joint_names_.size(); ++i) { - auto motor = getMotor_(joint_names_[i]); - if (!motor) { - return Result::failure(ArmErrorCode::RobotNotReady, - "motor not found for joint: " + joint_names_[i]); - } - if (motor->getMode() != msgs::RUN_MODE_CYCLIC_SYNC_VELOCITY) { - if (!motor->setMode(msgs::RUN_MODE_CYCLIC_SYNC_VELOCITY)) { - return Result::failure(ArmErrorCode::CommandFailed, - "failed to set cyclic velocity mode for joint: " + - joint_names_[i]); - } - } - if (!motor->commandCyclicVelocity(velocity.velocity[i] * speed_scaling_)) { - return Result::failure(ArmErrorCode::CommandFailed, - "failed to command cyclic velocity for joint: " + - joint_names_[i]); - } - } - } - + if (const auto stopped = safetyStopResult_("speedJ")) return *stopped; + JointVelocityCommand scaled = velocity; + const double scaling = speed_scaling_.load(); + for (auto& value : scaled.velocity) value *= scaling; + const auto result = sendJointVelocity_(scaled); + if (!result.ok()) return result; if (duration > 0.0) { std::this_thread::sleep_for(std::chrono::duration(duration)); return stopJ(acceleration); @@ -655,8 +879,44 @@ Result MotorRobotArm::speedJ(const JointVelocityCommand& velocity, return Result::success(); } +Result MotorRobotArm::sendJointVelocity_(const JointVelocityCommand& velocity) +{ + if (const auto stopped = safetyStopResult_("velocity command")) { + if (std::all_of(velocity.velocity.begin(), velocity.velocity.end(), + [](double value) { return value == 0.0; })) { + return quickStopMotors_(); + } + return *stopped; + } + std::string error; + if (!validateVelocityCommand_(velocity, error)) + return Result::failure(ArmErrorCode::InvalidArgument, error); + + std::lock_guard lock(mutex_); + std::vector> motors; + motors.reserve(joint_names_.size()); + for (const auto& name : joint_names_) { + auto motor = getMotor_(name); + if (!motor) return Result::failure(ArmErrorCode::RobotNotReady, "motor not found: " + name); + motors.push_back(std::move(motor)); + } + for (const auto& motor : motors) { + if (motor->getMode() != msgs::RUN_MODE_CYCLIC_SYNC_VELOCITY && + !motor->setMode(msgs::RUN_MODE_CYCLIC_SYNC_VELOCITY)) { + (void)quickStopMotors_(); + return Result::failure(ArmErrorCode::CommandFailed, "failed to set cyclic velocity mode"); + } + } + if (!motor_manager_ || !motor_manager_->commandCyclicVelocitiesAtomic(motors, velocity.velocity)) { + (void)quickStopMotors_(); + return Result::failure(ArmErrorCode::CommandFailed, "failed to submit cyclic velocity group"); + } + return Result::success(); +} + Result MotorRobotArm::stopJ(const double acceleration) { + joint_motion_stop_generation_.fetch_add(1); if (safetyStopRequested_()) { return Result::success(); } @@ -723,59 +983,407 @@ Result MotorRobotArm::moveL(const CartesianPose& target, return Result::failure(ArmErrorCode::CommandFailed, "moveL execution failed"); } +Result MotorRobotArm::moveP(const CartesianPose& target, + const MotionOptions& options, + const FrameType frame) +{ + if (const auto stopped = safetyStopResult_("moveP")) return *stopped; + if (frame != FrameType::Base && frame != FrameType::Tool) { + return Result::failure(ArmErrorCode::UnsupportedCommand, + "moveP supports Base and Tool frames only"); + } + for (const double value : {target.x, target.y, target.z, target.rx, target.ry, target.rz}) { + if (!std::isfinite(value)) { + return Result::failure(ArmErrorCode::InvalidArgument, "moveP target must be finite"); + } + } + return planAndExecuteJointPath_(options, [&](const std::vector& start, + std::vector& goal) { + Eigen::Matrix4d target_base = common::math::poseToMatrix(target); + if (frame == FrameType::Tool) { + Eigen::Matrix4d current_tcp; + if (!ik_solver_->fk(start, current_tcp, true)) { + return Result::failure(ArmErrorCode::CommandFailed, "moveP FK failed"); + } + target_base = (current_tcp * target_base).eval(); + } + ik_solver_->update_joints_state(start); + if (!ik_solver_->ik(target_base, goal, true)) { + return Result::failure(ArmErrorCode::OutOfWorkspace, "moveP target IK failed"); + } + return Result::success(); + }); +} + +Result MotorRobotArm::moveP(const JointPositionCommand& target, + const MotionOptions& options) +{ + if (const auto stopped = safetyStopResult_("moveP")) return *stopped; + std::string error; + if (!validatePositionCommand_(target, error)) { + return Result::failure(ArmErrorCode::InvalidArgument, error); + } + if (!std::all_of(target.position.begin(), target.position.end(), + [](double value) { return std::isfinite(value); })) { + return Result::failure(ArmErrorCode::InvalidArgument, "moveP joint target must be finite"); + } + return planAndExecuteJointPath_(options, [&](const std::vector&, + std::vector& goal) { + goal = target.position; + return Result::success(); + }); +} + +Result MotorRobotArm::planAndExecuteJointPath_( + const MotionOptions& options, + const std::function&, std::vector&)>& resolve_goal) +{ + const auto stop_generation = joint_motion_stop_generation_.load(); + if (const auto stopped = safetyStopResult_("moveP")) return *stopped; + if (options.asynchronous || options.blend_radius != 0.0) { + return Result::failure(ArmErrorCode::UnsupportedCommand, + "moveP supports synchronous motion without blending"); + } + const double scaling = speed_scaling_.load(); + if (!std::isfinite(options.velocity) || options.velocity <= 0.0 || + !std::isfinite(options.acceleration) || options.acceleration <= 0.0 || + !std::isfinite(options.jerk) || options.jerk <= 0.0 || + !std::isfinite(scaling) || scaling <= 0.0 || scaling > 1.0 || + (!options.joint_velocity_limits.empty() && options.joint_velocity_limits.size() != getDof())) { + return Result::failure(ArmErrorCode::InvalidArgument, "invalid moveP velocity, acceleration, jerk or speed scaling"); + } + for (const double limit : options.joint_velocity_limits) { + if (!std::isfinite(limit) || limit <= 0.0) { + return Result::failure(ArmErrorCode::InvalidArgument, "invalid moveP joint velocity limit"); + } + } + if (!ik_solver_ || !trajectory_smoother_ || !joint_path_planner_ || !path_collision_checker_) { + return Result::failure(ArmErrorCode::RobotNotReady, "moveP requires motion.joint_path configuration"); + } + if (busy_.exchange(true)) { + return Result::failure(ArmErrorCode::RobotNotReady, "arm is busy"); + } + struct MotionGuard { + std::atomic& busy; + std::function stop; + bool executing{false}; + bool completed{false}; + ~MotionGuard() { + if (executing && !completed) stop(); + busy.store(false); + } + } guard{busy_, [this] { quickStopMotors_(); }}; + + const auto cancelled = [&] { + return safetyStopRequested_() || joint_motion_stop_generation_.load() != stop_generation || + (options.cancellation_requested && options.cancellation_requested()); + }; + const auto interrupted = [&] { + if (const auto stopped = safetyStopResult_("moveP", true)) return *stopped; + return Result::failure(ArmErrorCode::CommandRejected, "moveP cancelled"); + }; + + try { + if (cancelled()) return interrupted(); + const auto cartesian_stop = stopCartesianMotionAndWait_(); + if (!cartesian_stop.ok()) return cartesian_stop; + + // 1. 从停止后的当前关节状态确定目标:关节目标直接使用,TCP 目标求 IK。 + JointPathRequest request; + std::vector velocity_now; + Eigen::VectorXd lower, upper, joint_velocity; + { + std::lock_guard lock(mutex_); + std::vector chain_joints; + if (!readArmState_(request.start, velocity_now) || + !ik_solver_->getChainJointNames(chain_joints) || chain_joints != joint_names_ || + !ik_solver_->getJointPositionLimits(lower, upper) || + !ik_solver_->getJointVelocityLimits(joint_velocity) || + lower.size() != dof_ || upper.size() != dof_ || joint_velocity.size() != dof_) { + return Result::failure(ArmErrorCode::RobotNotReady, "moveP cannot read joint state/limits"); + } + if (!Eigen::Map(request.start.data(), dof_).allFinite()) { + return Result::failure(ArmErrorCode::RobotNotReady, "moveP joint feedback is not finite"); + } + for (std::size_t j = 0; j < getDof(); ++j) { + if (request.start[j] < lower[j] - move_j_joint_limit_tolerance_rad_ || + request.start[j] > upper[j] + move_j_joint_limit_tolerance_rad_) { + return Result::failure(ArmErrorCode::CommandFailed, + "moveP start exceeds joint limits: " + joint_names_[j]); + } + } + const auto resolved = resolve_goal(request.start, request.goal); + if (!resolved.ok()) return resolved; + if (request.goal.size() != getDof()) { + return Result::failure(ArmErrorCode::InvalidArgument, "moveP joint target size mismatch"); + } + for (std::size_t j = 0; j < getDof(); ++j) { + if (!std::isfinite(request.goal[j]) || + request.goal[j] < lower[j] || request.goal[j] > upper[j]) { + return Result::failure(ArmErrorCode::InvalidArgument, + "moveP target exceeds joint limits: " + joint_names_[j]); + } + // Keep targets exact. Only normalize feedback overshoot within + // the configured tolerance so OMPL starts inside its bounds. + request.start[j] = std::clamp(request.start[j], lower[j], upper[j]); + } + } + + // 2. RRT、简化及样条复检共用本臂独立检测器和初始化时冻结的静态场景。 + request.lower_bounds.assign(lower.data(), lower.data() + lower.size()); + request.upper_bounds.assign(upper.data(), upper.data() + upper.size()); + request.is_cancelled = cancelled; + const auto& cfg = cfg_.motion().joint_path(); + CollisionValidationOptions collision_options; + collision_options.minimum_distance_m = cfg.has_minimum_distance_m() ? cfg.minimum_distance_m() : 0.01; + collision_options.joint_step_rad = cfg.rrt_connect().has_collision_check_step_rad() + ? cfg.rrt_connect().collision_check_step_rad() : 0.02; + collision_options.is_cancelled = cancelled; + const auto query_solver = std::dynamic_pointer_cast(ik_solver_); + collision_options.additional_state_valid = [&](const std::vector& q) { + if (!options.is_tcp_pose_valid) return true; + Eigen::Matrix4d tcp_pose_base; + bool fk_ok = false; + if (query_solver) { + // This query owns separate, mutex-protected Pinocchio work data; + // ordinary FK/IK queries may concurrently use the main work data. + Eigen::MatrixXd jacobian; + Eigen::Matrix3d rotation; + fk_ok = query_solver->computePoseAndJacobianBaseAtQ( + q, true, tcp_pose_base, jacobian, rotation); + } else { + std::lock_guard lock(mutex_); + fk_ok = ik_solver_->fk(q, tcp_pose_base, true); + } + if (!fk_ok || !tcp_pose_base.allFinite()) { + throw std::runtime_error("moveP TCP constraint FK failed"); + } + return options.is_tcp_pose_valid(common::math::matrixToPose(tcp_pose_base)); + }; + request.is_state_valid = [&](const std::vector& q) { + return path_collision_checker_->isStateValid(q, collision_options); + }; + const auto path = joint_path_planner_->plan(request); + if (cancelled()) return interrupted(); + if (!path.ok()) { + return Result::failure(path.status == JointPathStatus::TimedOut ? ArmErrorCode::Timeout + : ArmErrorCode::CommandFailed, + "moveP path planning failed: " + path.message); + } + CMVR_LOG(INFO) << "[MotorRobotArm][moveP] planning_time_ms=" + << path.planning_time_s * 1000.0; + if (path.waypoints.size() == 1) return Result::success(); + + // 3. 独立五次 B 样条构造时间轨迹;按解析导数上界统一缩放时间。 + const double period_s = joint_trajectory_sample_period_s_; + if (!std::isfinite(period_s) || period_s <= 0.0) { + return Result::failure(ArmErrorCode::RobotNotReady, "invalid joint trajectory sample period"); + } + const double check_step = collision_options.joint_step_rad; + MotionOptions validation_limits = options; + validation_limits.velocity *= scaling; + validation_limits.joint_velocity_limits.resize(getDof()); + for (std::size_t j = 0; j < getDof(); ++j) { + if (!std::isfinite(joint_velocity[j]) || joint_velocity[j] <= 0.0) { + return Result::failure(ArmErrorCode::RobotNotReady, "invalid joint velocity limit"); + } + double velocity = std::min(options.velocity, joint_velocity[j]); + if (!options.joint_velocity_limits.empty()) { + velocity = std::min(velocity, options.joint_velocity_limits[j]); + } + validation_limits.joint_velocity_limits[j] = + std::min(velocity * scaling, check_step / period_s); + } + const auto trajectory_start = std::chrono::steady_clock::now(); + validation_limits.cancellation_requested = cancelled; + JointTrajectory samples; + if (!trajectory_smoother_->smooth(path.waypoints, validation_limits, period_s, samples)) { + if (cancelled()) return interrupted(); + return Result::failure(ArmErrorCode::CommandFailed, "moveP B-spline planning failed"); + } + const double duration = samples.back().time_s; + CMVR_LOG(INFO) << "[MotorRobotArm][moveP] trajectory_planning_time_ms=" + << std::chrono::duration( + std::chrono::steady_clock::now() - trajectory_start).count() + << ", trajectory_time_s=" << duration << ", path=quintic_bspline"; + + // 运动限值检查后,由碰撞检测器负责整条轨迹的离散复检。 + const auto validation_start = std::chrono::steady_clock::now(); + if (!validateJointTrajectory(samples, getDof(), validation_limits)) { + return Result::failure(ArmErrorCode::CommandFailed, "moveP smoothed trajectory violates motion limits"); + } + for (std::size_t i = 0; i < samples.size(); ++i) { + if (cancelled()) return interrupted(); + const auto& to = samples[i].position; + for (std::size_t j = 0; j < getDof(); ++j) { + if (!std::isfinite(samples[i].acceleration[j]) || !std::isfinite(samples[i].jerk[j]) || + std::abs(samples[i].acceleration[j]) > options.acceleration + 1e-6 || + std::abs(samples[i].jerk[j]) > options.jerk + 1e-6) { + return Result::failure(ArmErrorCode::CommandFailed, + "moveP B-spline violates acceleration/jerk limits: " + joint_names_[j]); + } + if (to[j] < lower[j] - move_j_joint_limit_tolerance_rad_ || + to[j] > upper[j] + move_j_joint_limit_tolerance_rad_) { + return Result::failure(ArmErrorCode::CommandFailed, + "moveP smoothed trajectory exceeds joint limits: " + joint_names_[j]); + } + } + } + const auto collision_check = path_collision_checker_->checkTrajectory(samples, collision_options); + if (cancelled()) return interrupted(); + if (!collision_check.valid) { + return Result::failure(ArmErrorCode::CommandFailed, + "moveP smoothed trajectory failed collision/clearance check: " + collision_check.error); + } + CMVR_LOG(INFO) << "[MotorRobotArm][moveP] validation_time_ms=" + << std::chrono::duration( + std::chrono::steady_clock::now() - validation_start).count() + << ", validity_checks=" << collision_check.validity_checks; + if (options.trajectory_callback) options.trajectory_callback(samples); + + std::vector> motors; + for (const auto& name : joint_names_) { + auto motor = getMotor_(name); + if (!motor) return Result::failure(ArmErrorCode::RobotNotReady, "motor not found: " + name); + motors.push_back(std::move(motor)); + } + if (cancelled()) return interrupted(); + const auto current = readJointPosition_(); + if (current.size() != request.start.size()) { + return Result::failure(ArmErrorCode::RobotNotReady, "moveP joint feedback is unavailable"); + } + for (std::size_t j = 0; j < current.size(); ++j) { + if (!std::isfinite(current[j]) || + std::abs(current[j] - request.start[j]) > move_j_position_tolerance_rad_) { + return Result::failure(ArmErrorCode::CommandRejected, "arm moved during moveP planning"); + } + } + guard.executing = true; + { + std::lock_guard lock(mutex_); + if (cancelled()) return interrupted(); + for (const auto& motor : motors) { + if (motor->getMode() != msgs::RUN_MODE_CYCLIC_SYNC_POSITION && + !motor->setMode(msgs::RUN_MODE_CYCLIC_SYNC_POSITION)) { + return Result::failure(ArmErrorCode::CommandFailed, "moveP failed to set cyclic position mode"); + } + } + } + // 4. 按轨迹的绝对时间发送位置和速度前馈,避免逐周期累计计时误差。 + const auto motion_start = std::chrono::steady_clock::now(); + std::vector position(getDof()), velocity(getDof()); + for (std::size_t k = 1; k < samples.size(); ++k) { + const auto& sample = samples[k]; + const auto deadline = motion_start + + std::chrono::duration_cast( + std::chrono::duration(sample.time_s)); + do { + if (cancelled()) return interrupted(); + std::this_thread::sleep_until(std::min(deadline, + std::chrono::steady_clock::now() + std::chrono::milliseconds(1))); + } while (std::chrono::steady_clock::now() < deadline); + position = sample.position; + velocity = sample.velocity; + if (k + 1 == samples.size()) { + position = request.goal; + std::fill(velocity.begin(), velocity.end(), 0.0); + } + std::lock_guard lock(mutex_); + if (cancelled()) return interrupted(); + if (!motor_manager_->commandCyclicPositionsAtomic(motors, position, velocity)) { + return Result::failure(ArmErrorCode::CommandFailed, "moveP cyclic position command failed"); + } + } + const auto settled = waitForJointTarget_(request.goal, cancelled, "moveP"); + if (!settled.ok()) return settled; + guard.completed = true; + CMVR_LOG(INFO) << "[MotorRobotArm][moveP] waypoints=" << path.waypoints.size() + << ", control_cycles=" << samples.size() - 1; + return Result::success(); + } catch (const std::exception& error) { + if (cancelled()) return interrupted(); + return Result::failure(ArmErrorCode::CommandFailed, std::string("moveP failed: ") + error.what()); + } +} + Result MotorRobotArm::speedL(const CartesianVelocity& velocity, const double acceleration, const double duration, const FrameType frame) { - if (const auto stopped = safetyStopResult_("speedL")) { - return *stopped; - } - if (busy_.load()) { - return Result::failure(ArmErrorCode::RobotNotReady, "arm is busy"); - } - if (!cartesian_velocity_controller_) { - return Result::failure(ArmErrorCode::RobotNotReady, "cartesian velocity controller is not initialized"); - } - return cartesian_velocity_controller_->speedL(velocity, acceleration, duration, frame); + SpeedLOptions options; + options.acceleration = acceleration; + return speedL(velocity, options, duration, frame); } Result MotorRobotArm::stopL(const std::optional acceleration) { - if (!cartesian_velocity_controller_) { + if (!speed_l_executor_) { return Result::success(); } - return cartesian_velocity_controller_->stop(acceleration); + return speed_l_executor_->stop(acceleration); } Result MotorRobotArm::speedL(const CartesianVelocity& velocity, const SpeedLOptions& options, const double duration, const FrameType frame) { if (const auto stopped = safetyStopResult_("speedL")) return *stopped; - if (busy_.load() || !cartesian_velocity_controller_) { + if (busy_.load() || !speed_l_executor_) { return Result::failure(ArmErrorCode::RobotNotReady, "arm is busy or velocity controller is unavailable"); } - return cartesian_velocity_controller_->speedL(velocity, options, duration, frame); + return speed_l_executor_->speedL(velocity, options, duration, frame); } SpeedLReference MotorRobotArm::getSpeedLReference() const { - return cartesian_velocity_controller_ ? cartesian_velocity_controller_->getReference() : SpeedLReference{}; + return speed_l_executor_ ? speed_l_executor_->getReference() : SpeedLReference{}; +} + +Result MotorRobotArm::getSpeedLResult() const +{ + return speed_l_executor_ ? speed_l_executor_->lastResult() : + Result::failure(ArmErrorCode::RobotNotReady, "velocity executor is unavailable"); +} + +bool MotorRobotArm::isFault() const +{ + return speed_l_executor_ && speed_l_executor_->faulted(); +} + +Result MotorRobotArm::clearFault() +{ + return speed_l_executor_ ? speed_l_executor_->clearFault() : Result::success(); +} + +Result MotorRobotArm::recoverSpeedLPlanningFault() +{ + if (const auto stopped = safetyStopResult_("recover speedL planning fault")) return *stopped; + if (!isConnected()) { + return Result::failure(ArmErrorCode::NotConnected, "arm is not connected"); + } + if (busy_.load()) { + return Result::failure(ArmErrorCode::RobotNotReady, "joint motion is still active"); + } + const auto result = speed_l_executor_ ? speed_l_executor_->clearPlanningFault() : Result::success(); + if (const auto stopped = safetyStopResult_("recover speedL planning fault")) return *stopped; + return result; } Result MotorRobotArm::stopMotion() { + joint_motion_stop_generation_.fetch_add(1); const auto cartesian_stop = stopCartesianMotionAndWait_(); - if (!cartesian_stop.ok()) { - return cartesian_stop; - } - return stopJ(0.0); + const auto result = cartesian_stop.ok() ? stopJ(0.0) : cartesian_stop; + if (speed_l_executor_) speed_l_executor_->recordStopFailure(result); + return result; } Result MotorRobotArm::shutdown() { - if (cartesian_velocity_controller_) { - cartesian_velocity_controller_->shutdown(); + joint_motion_stop_generation_.fetch_add(1); + if (speed_l_executor_) { + const auto result = speed_l_executor_->shutdown(); + if (!result.ok()) return result; } return stopJ(0.0); } @@ -950,16 +1558,16 @@ CartesianPose MotorRobotArm::fk(const bool is_tcp) CartesianVelocity MotorRobotArm::getSpeedLCommandTwistBase() const { - if (!cartesian_velocity_controller_) { + if (!speed_l_executor_) { return {}; } - return cartesian_velocity_controller_->getCommandTwistBase(); + return speed_l_executor_->getCommandTwistBase(); } bool MotorRobotArm::busy() const { return busy_.load() || - (cartesian_velocity_controller_ && cartesian_velocity_controller_->busy()); + (speed_l_executor_ && speed_l_executor_->busy()); } bool MotorRobotArm::containsJoint_(const std::string& joint_name) const @@ -1018,28 +1626,30 @@ std::vector MotorRobotArm::readJointPosition_() const Result MotorRobotArm::stopCartesianMotionAndWait_() { - if (!cartesian_velocity_controller_) { + if (!speed_l_executor_) { return Result::success(); } - if (cartesian_velocity_controller_->busy()) { - const auto stop_result = cartesian_velocity_controller_->stop(); + if (speed_l_executor_->busy()) { + const auto stop_result = speed_l_executor_->stop(); if (!stop_result.ok()) { - return stop_result; + // A fault may finish the command between busy() and stop(). Join + // and verify the final zero command instead of returning its old error. + return speed_l_executor_->shutdown(); } const auto deadline = std::chrono::steady_clock::now() + std::chrono::duration( - cartesian_velocity_controller_->stopTimeoutS()); - while (cartesian_velocity_controller_->busy() && + speed_l_executor_->stopTimeoutS()); + while (speed_l_executor_->busy() && std::chrono::steady_clock::now() < deadline) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); } - if (cartesian_velocity_controller_->busy()) { + if (speed_l_executor_->busy()) { // Do not start a position trajectory while the worker can still // issue velocity commands. Shutdown joins it and sends one final // zero-velocity command before reporting the timeout. - cartesian_velocity_controller_->shutdown(); + speed_l_executor_->shutdown(); return Result::failure( ArmErrorCode::Timeout, "timed out waiting for Cartesian velocity motion to stop"); @@ -1048,15 +1658,19 @@ Result MotorRobotArm::stopCartesianMotionAndWait_() // The worker may be idle but still joinable. Joining it here removes any // last command/worker race before the next motion mode is selected. - cartesian_velocity_controller_->shutdown(); - return Result::success(); + // This operation reports whether motion has stopped. A previous planning + // failure remains available through getSpeedLResult()/isFault(), but must + // not reject a position-mode recovery after a successful stop. + return speed_l_executor_->shutdown(); } -Result MotorRobotArm::waitForJointTarget_(const std::vector& target) const +Result MotorRobotArm::waitForJointTarget_(const std::vector& target, + const std::function& is_cancelled, + const std::string& command) const { if (target.size() != joint_names_.size()) { return Result::failure(ArmErrorCode::InvalidArgument, - "moveJ target size mismatch while settling"); + command + " target size mismatch while settling"); } struct JointFeedback { @@ -1070,9 +1684,12 @@ Result MotorRobotArm::waitForJointTarget_(const std::vector& target) con int stable_samples = 0; int max_stable_samples = 0; while (std::chrono::steady_clock::now() < deadline) { - if (const auto stopped = safetyStopResult_("moveJ", true)) { + if (const auto stopped = safetyStopResult_(command, true)) { return *stopped; } + if (is_cancelled && is_cancelled()) { + return Result::failure(ArmErrorCode::CommandRejected, command + " cancelled"); + } bool settled = true; for (std::size_t i = 0; i < joint_names_.size(); ++i) { @@ -1080,7 +1697,7 @@ Result MotorRobotArm::waitForJointTarget_(const std::vector& target) con if (!motor) { return Result::failure( ArmErrorCode::RobotNotReady, - "motor not found while waiting for moveJ target: " + joint_names_[i]); + "motor not found while waiting for " + command + " target: " + joint_names_[i]); } const double position = motor->getQ(); const double velocity = motor->getQd(); @@ -1101,7 +1718,7 @@ Result MotorRobotArm::waitForJointTarget_(const std::vector& target) con std::this_thread::sleep_for(std::chrono::milliseconds(1)); } - CMVR_LOG(ERROR) << "[MotorRobotArm] moveJ target did not settle before timeout: " << id_ + CMVR_LOG(ERROR) << "[MotorRobotArm] " << command << " target did not settle before timeout: " << id_ << ", timeout_s=" << move_j_settle_timeout_s_ << ", sample_count=" << sample_count << ", stable_samples=" << stable_samples @@ -1133,18 +1750,56 @@ Result MotorRobotArm::waitForJointTarget_(const std::vector& target) con << ", velocity_ok=" << (velocity_ok ? "true" : "false"); } return Result::failure(ArmErrorCode::Timeout, - "timed out waiting for moveJ target to settle"); + "timed out waiting for " + command + " target to settle"); +} + +bool MotorRobotArm::configureJointPathPlanner_() +{ + joint_path_planner_.reset(); + path_collision_checker_.reset(); + if (!cfg_.motion().has_joint_path()) return true; + + const auto& cfg = cfg_.motion().joint_path(); + joint_path_planner_ = JointPathPlannerFactory::create(cfg); + const double clearance = cfg.has_minimum_distance_m() ? cfg.minimum_distance_m() : 0.01; + if (!joint_path_planner_ || !std::isfinite(clearance) || clearance < 0.0 || + motor_cfg_.upd_freq() <= 0) { + CMVR_LOG(ERROR) << "[MotorRobotArm] invalid joint_path configuration: " << id_; + return false; + } + auto checker = std::make_unique(); + std::string error; + if (!model_.loadCollisionGeometry( + ConfigHelper::resolveResourceFile(cfg.collision_checker().urdf_path()))) { + return false; + } + if (!checker->init(cfg.collision_checker(), model_, &error)) { + CMVR_LOG(ERROR) << "[MotorRobotArm] joint_path collision checker: " << error; + return false; + } + path_collision_checker_ = std::move(checker); + return true; } bool MotorRobotArm::configureAlgorithms_() { - // Optional settling fields are read once during initialization so every + // Optional limit/settling fields are read once during initialization so every // MoveJ command uses one consistent set of safety criteria. + move_j_joint_limit_tolerance_rad_ = 1e-5; move_j_settle_timeout_s_ = 2.0; move_j_position_tolerance_rad_ = 2e-3; move_j_velocity_tolerance_rad_s_ = 2e-2; move_j_stable_sample_count_ = 3; const auto& move_j_config = cfg_.motion().move_j(); + if (move_j_config.has_joint_limit_tolerance_rad()) { + const double value = move_j_config.joint_limit_tolerance_rad(); + if (!std::isfinite(value) || value < 0.0) { + CMVR_LOG(ERROR) << "[MotorRobotArm] invalid moveJ joint_limit_tolerance_rad: " + << value; + return false; + } + move_j_joint_limit_tolerance_rad_ = value; + } if (move_j_config.has_settle_timeout_s()) { const double value = move_j_config.settle_timeout_s(); if (!std::isfinite(value) || value <= 0.0) { @@ -1191,8 +1846,15 @@ bool MotorRobotArm::configureAlgorithms_() return false; } - joint_planner_ = JointMotionPlannerFactory::create(cfg_.motion().move_j()); - if (!joint_planner_) { + const auto& smoother_config = cfg_.motion().joint_trajectory_smoother(); + joint_trajectory_sample_period_s_ = smoother_config.has_sample_period_s() + ? smoother_config.sample_period_s() : 0.001; + if (!std::isfinite(joint_trajectory_sample_period_s_) || joint_trajectory_sample_period_s_ <= 0.0) { + CMVR_LOG(ERROR) << "[MotorRobotArm] invalid joint trajectory sample period"; + return false; + } + trajectory_smoother_ = JointTrajectorySmootherFactory::create(smoother_config); + if (!trajectory_smoother_) { return false; } @@ -1201,6 +1863,18 @@ bool MotorRobotArm::configureAlgorithms_() return false; } + model_ = ik_solver_->getRobotModel(); + model_.name = id_; + model_.manufacturer = "cmvr"; + if (!model_.valid() || !model_.hasKinematics() || model_.joint_names != joint_names_) { + CMVR_LOG(ERROR) << "[MotorRobotArm] robot model does not match configured joints: " << id_; + return false; + } + + if (!configureJointPathPlanner_()) { + return false; + } + auto pinocchio_solver = std::dynamic_pointer_cast(ik_solver_); if (!pinocchio_solver) { return false; @@ -1208,32 +1882,33 @@ bool MotorRobotArm::configureAlgorithms_() const auto& move_l = cfg_.motion().move_l(); const auto& speed_l = cfg_.motion().speed_l(); - auto cartesian_motion = CartesianMotionPlannerFactory::create(move_l, speed_l, pinocchio_solver); - if (!cartesian_motion) { - return false; - } - const auto* speed_l_config = CartesianMotionPlannerFactory::speedLConfig(speed_l); - const auto* move_l_config = CartesianMotionPlannerFactory::moveLConfig(move_l); - if (!speed_l_config || !move_l_config) { - return false; - } - if (!cartesian_motion->configureMoveL(*move_l_config) || - !cartesian_motion->configureSpeedL(*speed_l_config, getDof())) { + auto cartesian_motion = CartesianMotionPlannerFactory::createMoveL(move_l, pinocchio_solver); + auto cartesian_velocity = CartesianMotionPlannerFactory::createSpeedL(speed_l, pinocchio_solver, getDof()); + if (!cartesian_motion || !cartesian_velocity) { return false; } cartesian_planner_ = cartesian_motion; - cartesian_velocity_controller_ = std::make_unique( - toCartesianVelocityControllerConfig_( + SpeedLExecutor::BeginCycleCallback begin_cycle; + SpeedLExecutor::EndCycleCallback end_cycle; + if (auto world = MotorManager::mujocoWorldFor(motor_system_id_)) { + const auto controller_id = id_; + begin_cycle = [world, controller_id] { return world->beginControlCycle(controller_id); }; + end_cycle = [world, controller_id](bool finished) { world->endControlCycle(controller_id, finished); }; + } + speed_l_executor_ = std::make_unique( + toSpeedLExecutorConfig_( speed_l.speed_l_controller().cartesian_velocity_controller()), - cartesian_planner_, + std::move(cartesian_velocity), getDof(), [this](std::vector& q, std::vector& qd) { return readArmState_(q, qd); }, - [this](const JointVelocityCommand& velocity, const double acceleration) { - return speedJ(velocity, acceleration, 0.0); - }); + [this](const JointVelocityCommand& velocity) { + return sendJointVelocity_(velocity); + }, + [this] { return speed_scaling_.load(); }, + std::move(begin_cycle), std::move(end_cycle)); return true; } @@ -1288,25 +1963,17 @@ bool MotorRobotArm::executeMoveLTrajectory_(const CartesianJointTrajectory& traj return true; } -CartesianVelocityController::Config MotorRobotArm::toCartesianVelocityControllerConfig_( +SpeedLExecutor::Config MotorRobotArm::toSpeedLExecutorConfig_( const config::CartesianVelocityControllerConfig& config) { - CartesianVelocityController::Config result; - result.control_period_s = config.control_period_s() > 0.0 ? config.control_period_s() : result.control_period_s; - result.stop_twist_norm = config.stop_twist_norm() > 0.0 ? config.stop_twist_norm() : result.stop_twist_norm; - result.stop_command_velocity_norm = - config.stop_command_velocity_norm() > 0.0 ? config.stop_command_velocity_norm() - : result.stop_command_velocity_norm; - result.stop_measured_velocity_norm = - config.stop_measured_velocity_norm() > 0.0 ? config.stop_measured_velocity_norm() - : result.stop_measured_velocity_norm; - result.stop_acceleration = - config.stop_acceleration() > 0.0 ? config.stop_acceleration() - : result.stop_acceleration; - if (config.has_stop_timeout_s() && std::isfinite(config.stop_timeout_s()) && - config.stop_timeout_s() > 0.0) { - result.stop_timeout_s = config.stop_timeout_s(); - } + SpeedLExecutor::Config result; + // Defaults and normalization belong to SpeedLExecutor. + result.control_period_s = config.control_period_s(); + result.stop_twist_norm = config.stop_twist_norm(); + result.stop_command_velocity_norm = config.stop_command_velocity_norm(); + result.stop_measured_velocity_norm = config.stop_measured_velocity_norm(); + result.stop_acceleration = config.stop_acceleration(); + result.stop_timeout_s = config.stop_timeout_s(); return result; } diff --git a/cmvr-es/devices/arm/motor_robot_arm/src/motor_robot_arm_gen2_mujoco_test.cpp b/cmvr-es/devices/arm/motor_robot_arm/src/motor_robot_arm_gen2_mujoco_test.cpp index 9feebb00..22a78851 100644 --- a/cmvr-es/devices/arm/motor_robot_arm/src/motor_robot_arm_gen2_mujoco_test.cpp +++ b/cmvr-es/devices/arm/motor_robot_arm/src/motor_robot_arm_gen2_mujoco_test.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -19,6 +20,7 @@ #include #include +#include "common/config/config_files.h" #include "common/io/proto_file_io.h" #include "common/math/transform_math.h" #include "manager/device_manager/include/device_manager.h" @@ -138,6 +140,8 @@ protected: DeviceManager::destroyInstance(); project_root_ = findProjectRoot(); ASSERT_FALSE(project_root_.empty()); + ConfigHelper::setConfigRootFromFile( + (project_root_ / "cmvr-es/config/cmvr_es.pb.txt").string()); config::MujocoWorldRootConfig world_root_config; ASSERT_TRUE(ProtoMessageIo::getProtoFromAsciiFile( @@ -460,17 +464,20 @@ TEST_F(MotorRobotArmGen2MujocoTest, MoveL) TEST_F(MotorRobotArmGen2MujocoTest, SelfCollisionProtectiveStopMoveJMoveLSpeedL) { - MuJocoViewer viewer(world_); - viewer.setupCamera(2.5, -160.0, -20.0); + std::unique_ptr viewer; + if (std::getenv("CMVR_MUJOCO_HEADLESS") == nullptr) { + viewer = std::make_unique(world_); + viewer->setupCamera(2.5, -160.0, -20.0); + } struct CollisionCaseOutcome { std::string name; Result setup_move{Result::failure(ArmErrorCode::UnknownError, "not run")}; Result collision_move{Result::failure(ArmErrorCode::UnknownError, "not run")}; Result recovery{Result::failure(ArmErrorCode::UnknownError, "not run")}; - task::SelfCollisionTaskStatus initial_status; - task::SelfCollisionTaskStatus stop_status; - task::SelfCollisionTaskStatus recovered_status; + safety::SelfCollisionStatus initial_status; + safety::SelfCollisionStatus stop_status; + safety::SelfCollisionStatus recovered_status; CartesianPose start_tcp; CartesianPose final_tcp; std::vector final_position; @@ -553,7 +560,7 @@ TEST_F(MotorRobotArmGen2MujocoTest, SelfCollisionProtectiveStopMoveJMoveLSpeedL) name + " start: " + collision_task.detailStatusString()); } outcome.initial_status = collision_task.latestStatus(); - if (outcome.initial_status.level != task::CollisionSafetyLevel::SAFE) { + if (outcome.initial_status.level != safety::CollisionSafetyLevel::SAFE) { throw std::runtime_error( name + " setup pose is not SAFE: " + collision_task.detailStatusString()); @@ -579,9 +586,24 @@ TEST_F(MotorRobotArmGen2MujocoTest, SelfCollisionProtectiveStopMoveJMoveLSpeedL) }); outcome.collision_move = start_motion(); + const auto simulation_time = [&] { + std::lock_guard lock(world_->mutex()); + return world_->data()->time; + }; + const double wait_start_sim_s = simulation_time(); + const auto wait_start_wall = std::chrono::steady_clock::now(); + // Online control can slow simulation below real time in Debug. + // Bound motion time in simulation, with a wall-clock watchdog. waitFor([&] { - return stop_seen.load() || !monitor_ok.load(); - }, stop_timeout); + return stop_seen.load() || !monitor_ok.load() || + simulation_time() - wait_start_sim_s >= + std::chrono::duration(stop_timeout).count(); + }, stop_timeout * 4); + std::cout << "[MotorRobotArmGen2MujocoTest] collision " << name + << " wait_sim_s=" << simulation_time() - wait_start_sim_s + << ", wait_wall_s=" << std::chrono::duration( + std::chrono::steady_clock::now() - wait_start_wall).count() + << std::endl; if (!stop_seen.load()) { arm_->stopMotion(); monitor_running = false; @@ -689,12 +711,16 @@ TEST_F(MotorRobotArmGen2MujocoTest, SelfCollisionProtectiveStopMoveJMoveLSpeedL) worker_error = error.what(); } - std::this_thread::sleep_for(std::chrono::seconds(3)); - viewer.requestStop(); + if (viewer) { + std::this_thread::sleep_for(std::chrono::seconds(3)); + viewer->requestStop(); + } }); - viewer.setRunning(true); - viewer.run(); + if (viewer) { + viewer->setRunning(true); + viewer->run(); + } scenario.join(); EXPECT_TRUE(worker_error.empty()) << worker_error; @@ -703,16 +729,16 @@ TEST_F(MotorRobotArmGen2MujocoTest, SelfCollisionProtectiveStopMoveJMoveLSpeedL) << outcome.name << ": " << outcome.setup_move.message; EXPECT_TRUE(outcome.task_initialized) << outcome.name; EXPECT_TRUE(outcome.task_started) << outcome.name; - EXPECT_EQ(outcome.initial_status.level, task::CollisionSafetyLevel::SAFE) + EXPECT_EQ(outcome.initial_status.level, safety::CollisionSafetyLevel::SAFE) << outcome.name; EXPECT_TRUE(outcome.monitor_ok) << outcome.name; EXPECT_TRUE(outcome.stop_seen) << outcome.name; - EXPECT_EQ(outcome.stop_status.level, task::CollisionSafetyLevel::STOP) + EXPECT_EQ(outcome.stop_status.level, safety::CollisionSafetyLevel::STOP) << outcome.name; EXPECT_TRUE(outcome.stop_status.stop_latched) << outcome.name; EXPECT_NE(outcome.stop_status.event_id, 0U) << outcome.name; EXPECT_EQ(outcome.stop_status.recovery_state, - task::ProtectiveRecoveryState::AVAILABLE) + safety::ProtectiveRecoveryState::AVAILABLE) << outcome.name; EXPECT_GE(outcome.stop_status.recovery_sample_count, 2U) << outcome.name; @@ -725,7 +751,7 @@ TEST_F(MotorRobotArmGen2MujocoTest, SelfCollisionProtectiveStopMoveJMoveLSpeedL) << outcome.name << ": " << outcome.recovery.message; EXPECT_FALSE(outcome.recovered_status.stop_latched) << outcome.name; EXPECT_EQ(outcome.recovered_status.recovery_state, - task::ProtectiveRecoveryState::SUCCEEDED) + safety::ProtectiveRecoveryState::SUCCEEDED) << outcome.name; EXPECT_GE(outcome.recovered_status.result.minimum_distance_m, 0.025) << outcome.name; diff --git a/cmvr-es/devices/arm/motor_robot_arm/src/motor_robot_arm_mujoco_test.cpp b/cmvr-es/devices/arm/motor_robot_arm/src/motor_robot_arm_mujoco_test.cpp index 82e473f9..e3f928d4 100644 --- a/cmvr-es/devices/arm/motor_robot_arm/src/motor_robot_arm_mujoco_test.cpp +++ b/cmvr-es/devices/arm/motor_robot_arm/src/motor_robot_arm_mujoco_test.cpp @@ -4,18 +4,27 @@ #include #include #include +#include #include +#include #include #include #include +#include +#include #include #include #include #include #include +#include +#include "cmvr/config/touch_screen_task_config/touch_screen_task_config.pb.h" +#include "common/config/config_files.h" #include "common/io/proto_file_io.h" +#include "common/math/proto_geometry.h" +#include "common/math/transform_math.h" #include "devices/motor/manager/include/motor_manager.h" #include "simulate/mujoco/mujoco_viewer/include/mujoco_viewer.h" #include "simulate/mujoco/mujoco_world/include/mujoco_world.h" @@ -85,11 +94,8 @@ void waitFor(Predicate predicate, const std::chrono::milliseconds timeout) struct ScenarioOutcome { Result move_j_initial{Result::failure(ArmErrorCode::UnknownError, "not run")}; Result move_l{Result::failure(ArmErrorCode::UnknownError, "not run")}; - Result speed_l{Result::failure(ArmErrorCode::UnknownError, "not run")}; double move_j_initial_error{std::numeric_limits::infinity()}; double move_l_error{std::numeric_limits::infinity()}; - double speed_l_command_x{0.0}; - double speed_l_delta_x{0.0}; std::string worker_error; }; @@ -128,6 +134,8 @@ protected: { project_root_ = findProjectRoot(); ASSERT_FALSE(project_root_.empty()); + ConfigHelper::setConfigRootFromFile( + (project_root_ / "cmvr-es/config/cmvr_es.pb.txt").string()); config::MujocoWorldRootConfig world_root_config; ASSERT_TRUE(ProtoMessageIo::getProtoFromAsciiFile( @@ -159,12 +167,12 @@ protected: &root_config)); ASSERT_GT(root_config.arm().robot_arms_size(), 0); - config::RobotArmConfig arm_config = root_config.arm().robot_arms(0); + arm_config_ = root_config.arm().robot_arms(0); setKinematicsUrdfPath( - arm_config, + arm_config_, (project_root_ / "model/xiaoyan_description/dual_arm.urdf").string()); - arm_ = std::make_unique(arm_config); + arm_ = std::make_unique(arm_config_); ASSERT_NO_THROW(arm_->init()); } @@ -186,14 +194,35 @@ protected: std::shared_ptr motor_system_; std::shared_ptr world_; std::unique_ptr arm_; + config::RobotArmConfig arm_config_; + void runSpeedL(bool angular); + void runTouchLog(bool adaptive, double min_speed_ratio = 0); + void configureAdaptiveSpeed(bool enable, double min_speed_ratio = 0) { + // Let startup position actuators settle before replacing the arm. Its + // shutdown switches motors to zero velocity and would freeze startup sag. + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + ASSERT_TRUE(arm_->shutdown().ok()); + arm_.reset(); + auto* policy = arm_config_.mutable_motion()->mutable_speed_l() + ->mutable_pinocchio_cartesian_motion_planner()->mutable_adaptive_speed(); + policy->set_enable(enable); + policy->set_lookahead_s(.15); + policy->set_min_speed_ratio(min_speed_ratio); + arm_ = std::make_unique(arm_config_); + ASSERT_TRUE(arm_->init()); + } }; TEST_P(MotorRobotArmMujocoTest, MoveJ) { MotorRobotArm& arm = *arm_; - MuJocoViewer viewer(world_); - viewer.setupCamera(2.5, -160.0, -25.0); + const bool headless = std::getenv("CMVR_MUJOCO_HEADLESS") != nullptr; + std::unique_ptr viewer; + if (!headless) { + viewer = std::make_unique(world_); + viewer->setupCamera(2.5, -160.0, -25.0); + } ScenarioOutcome outcome; std::thread scenario([&] { @@ -220,12 +249,16 @@ TEST_P(MotorRobotArmMujocoTest, MoveJ) outcome.worker_error = error.what(); } - std::this_thread::sleep_for(std::chrono::milliseconds(3000)); - viewer.requestStop(); + if (viewer) { + std::this_thread::sleep_for(std::chrono::milliseconds(3000)); + viewer->requestStop(); + } }); - viewer.setRunning(true); - viewer.run(); + if (viewer) { + viewer->setRunning(true); + viewer->run(); + } scenario.join(); std::cout << "[MotorRobotArmMujocoTest] moveJ initial max error: " @@ -239,9 +272,16 @@ TEST_P(MotorRobotArmMujocoTest, MoveJ) TEST_P(MotorRobotArmMujocoTest, MoveL) { MotorRobotArm& arm = *arm_; + const bool uses_qp = std::string(GetParam().name) == "QpIk"; + Result rejected_fast_move_l{Result::failure(ArmErrorCode::UnknownError, "not run")}; + double rejected_motion_m = std::numeric_limits::quiet_NaN(); - MuJocoViewer viewer(world_); - viewer.setupCamera(2.5, -160.0, -25.0); + const bool headless = std::getenv("CMVR_MUJOCO_HEADLESS") != nullptr; + std::unique_ptr viewer; + if (!headless) { + viewer = std::make_unique(world_); + viewer->setupCamera(2.5, -160.0, -25.0); + } ScenarioOutcome outcome; std::thread scenario([&] { @@ -276,6 +316,14 @@ TEST_P(MotorRobotArmMujocoTest, MoveL) cartesian_options.acceleration = 20; cartesian_options.jerk = 100.0; + if (uses_qp) { + // At 0.8 m/s, this path requires elbow velocity below -5 rad/s. + // Hard Cartesian equality must reject it before execution. + rejected_fast_move_l = arm.moveL(move_l_target, cartesian_options, FrameType::Base); + rejected_motion_m = translationError(arm.getTcpPose(), move_l_start); + cartesian_options.velocity = 0.2; + } + std::cout << "[MotorRobotArmMujocoTest] moveL target pose" << std::endl; outcome.move_l = arm.moveL(move_l_target, cartesian_options, FrameType::Base); waitFor([&] { @@ -286,12 +334,16 @@ TEST_P(MotorRobotArmMujocoTest, MoveL) outcome.worker_error = error.what(); } - std::this_thread::sleep_for(std::chrono::milliseconds(10000)); - viewer.requestStop(); + if (viewer) { + std::this_thread::sleep_for(std::chrono::milliseconds(10000)); + viewer->requestStop(); + } }); - viewer.setRunning(true); - viewer.run(); + if (viewer) { + viewer->setRunning(true); + viewer->run(); + } scenario.join(); std::cout << "[MotorRobotArmMujocoTest] moveJ setup max error: " @@ -301,75 +353,684 @@ TEST_P(MotorRobotArmMujocoTest, MoveL) EXPECT_TRUE(outcome.worker_error.empty()) << outcome.worker_error; EXPECT_TRUE(outcome.move_j_initial.ok()) << outcome.move_j_initial.message; EXPECT_LT(outcome.move_j_initial_error, 0.10); + if (uses_qp) { + std::cout << "[MotorRobotArmMujocoTest] rejected fast moveL: " + << rejected_fast_move_l.message << ", displacement_m=" << rejected_motion_m << std::endl; + EXPECT_EQ(rejected_fast_move_l.code, ArmErrorCode::CommandFailed); + EXPECT_LT(rejected_motion_m, 1e-6); + EXPECT_LT(outcome.move_l_error, 0.0002); + } EXPECT_TRUE(outcome.move_l.ok()) << outcome.move_l.message; EXPECT_LT(outcome.move_l_error, 0.04); } -TEST_P(MotorRobotArmMujocoTest, SpeedL) +void MotorRobotArmMujocoTest::runSpeedL(const bool angular) { MotorRobotArm& arm = *arm_; + const double speed = angular ? .1 : .05; + const auto leg_duration = std::chrono::milliseconds(angular ? 3000 : 800); + const char* label = angular ? "SpeedLRotation" : "SpeedL6D"; - MuJocoViewer viewer(world_); - viewer.setupCamera(2.5, -160.0, -25.0); - ScenarioOutcome outcome; + const bool headless = std::getenv("CMVR_MUJOCO_HEADLESS") != nullptr; + std::unique_ptr viewer; + if (!headless) { + viewer = std::make_unique(world_); + viewer->setupCamera(2.5, -160.0, -25.0); + } + struct LegResult { + int axis; + bool reversal; + bool completed; + double sign; + double displacement; + double lateral_displacement; + double command_velocity; + double actual_velocity; + double reverse_ms; + }; + std::vector legs; + std::array stopped{}; + std::string worker_error; std::thread scenario([&] { try { - if (!world_ || !world_->isRunning()) { - throw std::runtime_error("MuJoCo world is not running"); - } - std::this_thread::sleep_for(std::chrono::milliseconds(300)); - - const std::vector move_j_initial{ - 0.25, 1.00, M_PI / 2, M_PI / 2, -M_PI / 2, 0.0, 0.0 + const auto require = [](const Result& result) { + if (!result.ok()) throw std::runtime_error(result.message); }; - MotionOptions joint_options; - joint_options.velocity = 2.8; - joint_options.acceleration = 20.0; + const int site = mj_name2id(world_->model(), mjOBJ_SITE, "R_FINGER_TIP_SITE"); + if (site < 0) throw std::runtime_error("TCP site not found"); + std::vector jacobian(3 * world_->model()->nv); + struct Sample { + Eigen::Vector3d position; + Eigen::Matrix3d rotation; + Eigen::Vector3d velocity{Eigen::Vector3d::Zero()}; + }; + const auto sample = [&] { + std::lock_guard lock(world_->mutex()); + const auto* model = world_->model(); + const auto* data = world_->data(); + mj_jacSite(model, data, angular ? nullptr : jacobian.data(), + angular ? jacobian.data() : nullptr, site); + Sample value; + for (int axis = 0; axis < 3; ++axis) { + value.position[axis] = data->site_xpos[3 * site + axis]; + for (int j = 0; j < 3; ++j) + value.rotation(axis, j) = data->site_xmat[9 * site + 3 * axis + j]; + for (int j = 0; j < model->nv; ++j) + value.velocity[axis] += jacobian[axis * model->nv + j] * data->qvel[j]; + } + // This model's fixed PELVIS_S has world-aligned Base axes. + return value; + }; + const std::vector initial{ + .25, 1.0, M_PI / 2, M_PI / 2, -M_PI / 2, 0.0, 0.0 + }; + MotionOptions move; + move.velocity = 2.8; + move.acceleration = 20.0; + SpeedLOptions options; + options.acceleration = .5; + if (!angular) options.linear_jerk = 10; + options.continuous_linear_reversal = true; - std::cout << "[MotorRobotArmMujocoTest] moveJ setup pose" << std::endl; - outcome.move_j_initial = arm.moveJ(JointPositionCommand{move_j_initial}, joint_options); - waitFor([&] { - return maxPositionError(arm.getJointState().position, move_j_initial) < 0.04; - }, std::chrono::seconds(2)); - outcome.move_j_initial_error = maxPositionError(arm.getJointState().position, move_j_initial); + // Allow the newly started position actuators to settle at zero. + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + for (int axis = 0; axis < 3; ++axis) { + // Reset between axes; opposite commands below have no stopL in between. + require(arm.moveJ(JointPositionCommand{initial}, move)); + waitFor([&] { return maxPositionError(arm.getJointState().position, initial) < .04; }, + std::chrono::seconds(2)); + if (maxPositionError(arm.getJointState().position, initial) >= .04) + throw std::runtime_error("speedL setup pose did not settle"); + std::this_thread::sleep_for(std::chrono::milliseconds(500)); - std::this_thread::sleep_for(std::chrono::seconds(2)); - - const CartesianPose speed_l_start = arm.getTcpPose(); - CartesianVelocity cartesian_velocity; - cartesian_velocity.vx = 0.05; - - std::cout << "[MotorRobotArmMujocoTest] speedL" << std::endl; - outcome.speed_l = arm.speedL(cartesian_velocity, 0.5, 0.0, FrameType::Base); - std::this_thread::sleep_for(std::chrono::seconds(1)); - outcome.speed_l_command_x = arm.getSpeedLCommandTwistBase().vx; - outcome.speed_l_delta_x = arm.getTcpPose().x - speed_l_start.x; - (void)arm.stopL(0.5); - waitFor([&] { return !arm.busy(); }, std::chrono::seconds(3)); + for (int leg = 0; leg < 3; ++leg) { + const double sign = leg == 1 ? -1.0 : 1.0; + const auto start = sample(); + if (leg > 0 && sign * start.velocity[axis] > -.4 * speed) + throw std::runtime_error("reversal did not start while moving in opposite direction"); + CartesianVelocity target; + const std::array components = angular + ? std::array{&CartesianVelocity::wx, &CartesianVelocity::wy, &CartesianVelocity::wz} + : std::array{&CartesianVelocity::vx, &CartesianVelocity::vy, &CartesianVelocity::vz}; + target.*components[axis] = sign * speed; + std::cout << '[' << label << "] " << GetParam().name << " target=" + << (sign > 0 ? '+' : '-') << "XYZ"[axis] + << " reverse=" << (leg > 0) << std::endl; + const auto begin = std::chrono::steady_clock::now(); + require(arm.speedL(target, options, 0.0, FrameType::Base)); + double reverse_ms = -1; + int direction_samples = 0; + bool completed = true; + auto reached = start; + auto next = begin; + while (std::chrono::steady_clock::now() - begin < leg_duration) { + reached = sample(); + if (!arm.busy()) { + completed = false; + break; + } + direction_samples = sign * reached.velocity[axis] > .1 * speed ? direction_samples + 1 : 0; + if (leg > 0 && direction_samples >= 5 && reverse_ms < 0) + reverse_ms = std::chrono::duration( + std::chrono::steady_clock::now() - begin).count(); + next += std::chrono::milliseconds(5); + std::this_thread::sleep_until(next); + } + const auto command = arm.getSpeedLCommandTwistBase(); + Eigen::Vector3d displacement = reached.position - start.position; + if (angular) { + const Eigen::AngleAxisd delta(reached.rotation * start.rotation.transpose()); + displacement = delta.axis() * delta.angle(); + } + Eigen::Vector3d lateral = displacement; + lateral[axis] = 0; + legs.push_back({axis, leg > 0, completed, sign, + sign * displacement[axis], lateral.norm(), + sign * (command.*components[axis]), sign * reached.velocity[axis], reverse_ms}); + const auto& result = legs.back(); + std::cout << '[' << label << "] " << GetParam().name << " result=" + << (sign > 0 ? '+' : '-') << "XYZ"[axis] + << (angular ? " angle_deg=" : " displacement_mm=") + << result.displacement * (angular ? 180 / M_PI : 1000) + << (angular ? " cross_axis_deg=" : " lateral_mm=") + << result.lateral_displacement * (angular ? 180 / M_PI : 1000) + << (angular ? " command_rad_s=" : " command_m_s=") << result.command_velocity + << (angular ? " actual_rad_s=" : " actual_m_s=") << result.actual_velocity + << " reverse_ms=" << result.reverse_ms + << " completed=" << completed << std::endl; + // Keep a failed leg in the results, then stop and test the next axis. + if (!completed) break; + } + require(arm.stopL(.5)); + waitFor([&] { return !arm.busy(); }, std::chrono::seconds(3)); + const double residual_speed = sample().velocity.norm(); + stopped[axis] = !arm.busy() && residual_speed < .01; + std::cout << '[' << label << "] " << GetParam().name << " stop=" << "XYZ"[axis] + << " ok=" << stopped[axis] + << (angular ? " residual_rad_s=" : " residual_m_s=") << residual_speed << std::endl; + if (!stopped[axis]) throw std::runtime_error("speedL did not stop cleanly"); + } } catch (const std::exception& error) { - outcome.worker_error = error.what(); + worker_error = error.what(); + (void)arm.stopL(.5); + } + if (viewer) { + std::this_thread::sleep_for(std::chrono::seconds(3)); + viewer->requestStop(); } - - std::this_thread::sleep_for(std::chrono::milliseconds(3000)); - viewer.requestStop(); }); - viewer.setRunning(true); - viewer.run(); + if (viewer) { + viewer->setRunning(true); + viewer->run(); + } scenario.join(); - std::cout << "[MotorRobotArmMujocoTest] moveJ setup max error: " - << outcome.move_j_initial_error - << ", speedL command x: " << outcome.speed_l_command_x - << ", speedL x delta: " << outcome.speed_l_delta_x << std::endl; + EXPECT_TRUE(worker_error.empty()) << worker_error; + EXPECT_EQ(legs.size(), 9U); // Six directions and both reversal orders on each axis. + for (std::size_t i = 0; i < legs.size(); ++i) { + const auto& leg = legs[i]; + SCOPED_TRACE(::testing::Message() << "axis=" << "XYZ"[leg.axis] << " sign=" << leg.sign); + EXPECT_TRUE(leg.completed); + EXPECT_GT(leg.displacement, .005); + EXPECT_NEAR(leg.command_velocity, speed, .1 * speed); + EXPECT_NEAR(leg.actual_velocity, speed, .3 * speed); + if (leg.reversal) { + EXPECT_GT(leg.reverse_ms, 0); + EXPECT_LT(leg.reverse_ms, 600); + } + } + for (bool axis_stopped : stopped) EXPECT_TRUE(axis_stopped); +} - EXPECT_TRUE(outcome.worker_error.empty()) << outcome.worker_error; - EXPECT_TRUE(outcome.move_j_initial.ok()) << outcome.move_j_initial.message; - EXPECT_LT(outcome.move_j_initial_error, 0.10); - EXPECT_TRUE(outcome.speed_l.ok()) << outcome.speed_l.message; - EXPECT_GT(outcome.speed_l_command_x, 0.01); - EXPECT_GT(outcome.speed_l_delta_x, 0.003); +TEST_P(MotorRobotArmMujocoTest, SpeedL) { runSpeedL(false); } +TEST_P(MotorRobotArmMujocoTest, SpeedLRotation) { runSpeedL(true); } + +TEST_P(MotorRobotArmMujocoTest, JointMovePRejectsInvalidTargetsAndCallbacksBeforeExecution) +{ + auto& arm = *arm_; + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + const std::vector initial{.25, 1.0, M_PI / 2, M_PI / 2, -M_PI / 2, 0, 0}; + MotionOptions options; + options.velocity = 1.0; + options.acceleration = 3.0; + ASSERT_TRUE(arm.moveJ({initial}, options).ok()); + const auto start = arm.getJointState().position; + int trajectories = 0; + options.trajectory_callback = [&](const JointTrajectory&) { ++trajectories; }; + + std::vector> invalid_targets{{}, std::vector(kDof - 1), + std::vector(kDof + 1)}; + for (const double invalid : {std::numeric_limits::quiet_NaN(), + std::numeric_limits::infinity(), 1000.0}) { + invalid_targets.push_back(initial); + invalid_targets.back()[0] = invalid; + } + for (const auto& target : invalid_targets) { + const auto result = arm.moveP(JointPositionCommand{target}, options); + EXPECT_EQ(result.code, ArmErrorCode::InvalidArgument) << result.message; + EXPECT_FALSE(arm.busy()); + } + EXPECT_EQ(trajectories, 0); + EXPECT_LT(maxPositionError(arm.getJointState().position, start), 1e-6); + + auto target = initial; + target[0] += 0.1; + options.cancellation_requested = [] { return true; }; + EXPECT_EQ(arm.moveP(JointPositionCommand{target}, options).code, ArmErrorCode::CommandRejected); + options.cancellation_requested = {}; + int constraint_checks = 0; + options.is_tcp_pose_valid = [&](const CartesianPose&) { ++constraint_checks; return false; }; + EXPECT_FALSE(arm.moveP(JointPositionCommand{target}, options).ok()); + EXPECT_GT(constraint_checks, 0); + EXPECT_EQ(trajectories, 0); + + options.is_tcp_pose_valid = {}; + options.trajectory_callback = [&](const JointTrajectory&) { + ++trajectories; + throw std::runtime_error("injected trajectory rejection"); + }; + const auto rejected = arm.moveP(JointPositionCommand{target}, options); + EXPECT_EQ(rejected.code, ArmErrorCode::CommandFailed); + EXPECT_NE(rejected.message.find("injected trajectory rejection"), std::string::npos); + EXPECT_EQ(trajectories, 1); + EXPECT_LT(maxPositionError(arm.getJointState().position, start), 1e-6); + EXPECT_FALSE(arm.busy()); +} + +TEST_P(MotorRobotArmMujocoTest, JointAndCartesianMovePShareValidatedTrajectoryExecution) +{ + auto& arm = *arm_; + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + // Actual TouchScreenTask initialization target; preserve all seven angles. + const std::vector target{-.2423, 1.2929, 1.61, 1.58, -2.8792, .115, -.08}; + auto initial = target; + initial[0] += 0.1; + initial[3] -= 0.1; + MotionOptions options; + options.velocity = 1.0; + options.acceleration = 3.0; + ASSERT_TRUE(arm.stopMotion().ok()); + const auto initialized = arm.moveP(JointPositionCommand{initial}, options); + ASSERT_TRUE(initialized.ok()) << initialized.message; + const auto start = arm.getJointState().position; + JointTrajectory trajectory; + options.trajectory_callback = [&](const JointTrajectory& samples) { trajectory = samples; }; + const auto joint_result = arm.moveP(JointPositionCommand{target}, options); + ASSERT_TRUE(joint_result.ok()) << joint_result.message; + ASSERT_GE(trajectory.size(), 2); + EXPECT_LT(maxPositionError(trajectory.front().position, start), 1e-6); + EXPECT_LT(maxPositionError(trajectory.back().position, target), 1e-12); + EXPECT_LT(maxPositionError(arm.getJointState().position, target), 0.002); + + Eigen::Matrix4d target_transform; + ASSERT_TRUE(arm.kinematicsSolver()->fk(target, target_transform, true)); + const auto target_pose = common::math::matrixToPose(target_transform); + ASSERT_TRUE(arm.moveJ({initial}, options).ok()); + trajectory.clear(); + const auto cartesian_result = arm.moveP(target_pose, options, FrameType::Base); + ASSERT_TRUE(cartesian_result.ok()) << cartesian_result.message; + ASSERT_GE(trajectory.size(), 2); + Eigen::Matrix4d planned_transform; + ASSERT_TRUE(arm.kinematicsSolver()->fk(trajectory.back().position, planned_transform, true)); + EXPECT_LT((planned_transform.block<3, 1>(0, 3) - target_transform.block<3, 1>(0, 3)).norm(), 0.001); + EXPECT_LT(Eigen::AngleAxisd(target_transform.block<3, 3>(0, 0).transpose() * + planned_transform.block<3, 3>(0, 0)).angle(), 0.001); + EXPECT_LT(translationError(arm.getTcpPose(), target_pose), 0.001); + EXPECT_FALSE(arm.busy()); +} + +TEST_P(MotorRobotArmMujocoTest, SpeedLPlanningFailureAllowsStoppedJointReturn) +{ + if (std::string(GetParam().name) != "QpIk") GTEST_SKIP() << "hard QP failure regression"; + configureAdaptiveSpeed(false); + ASSERT_FALSE(HasFatalFailure()); + using namespace std::chrono_literals; + auto& arm = *arm_; + std::this_thread::sleep_for(300ms); + const std::vector initial{.25, 1.0, M_PI / 2, M_PI / 2, -M_PI / 2, 0, 0}; + MotionOptions move; + move.velocity = 1.0; + move.acceleration = 3.0; + ASSERT_TRUE(arm.moveJ({initial}, move).ok()); + + // The accelerating +X command eventually needs elbow velocity outside + // its configured bounds; exercise the real QP and asynchronous executor. + CartesianVelocity target; + target.vx = 2.0; + SpeedLOptions options; + options.acceleration = 15.0; + options.linear_jerk = 100.0; + ASSERT_TRUE(arm.speedL(target, options, 0, FrameType::Base).ok()); + waitFor([&] { return arm.isFault() && !arm.busy(); }, 3s); + ASSERT_TRUE(arm.isFault()); + ASSERT_FALSE(arm.busy()); + const auto planning_failure = arm.getSpeedLResult(); + ASSERT_EQ(planning_failure.code, ArmErrorCode::CommandFailed); + ASSERT_NE(planning_failure.message.find("infeasible within joint limits"), std::string::npos) + << planning_failure.message; + + const auto stopped = arm.stopMotion(); + ASSERT_TRUE(stopped.ok()) << stopped.message; + JointTrajectory return_trajectory; + move.trajectory_callback = [&](const JointTrajectory& samples) { return_trajectory = samples; }; + const auto returned = arm.moveP(JointPositionCommand{initial}, move); + ASSERT_TRUE(returned.ok()) << returned.message; + ASSERT_GE(return_trajectory.size(), 2); + EXPECT_LT(maxPositionError(return_trajectory.back().position, initial), 1e-12); + EXPECT_LT(maxPositionError(arm.getJointState().position, initial), 0.002); + EXPECT_FALSE(arm.busy()); + EXPECT_TRUE(arm.isFault()); + EXPECT_EQ(arm.getSpeedLResult().code, planning_failure.code); + EXPECT_EQ(arm.getSpeedLResult().message, planning_failure.message); + EXPECT_FALSE(arm.speedL(target, options, 0, FrameType::Base).ok()) + << "joint return must not silently acknowledge the speedL fault"; + + ASSERT_TRUE(arm.stopMotion().ok()); + const auto recovered = arm.recoverSpeedLPlanningFault(); + ASSERT_TRUE(recovered.ok()) << recovered.message; + EXPECT_FALSE(arm.isFault()); + EXPECT_TRUE(arm.getSpeedLResult().ok()); + const auto restarted_from = arm.getTcpPose(); + target.vx = 0.02; + options.acceleration = 0.5; + options.linear_jerk = 10.0; + ASSERT_TRUE(arm.speedL(target, options, 0, FrameType::Base).ok()); + waitFor([&] { return arm.getSpeedLCommandTwistBase().vx > 0.019 || arm.isFault(); }, 2s); + ASSERT_FALSE(arm.isFault()) << arm.getSpeedLResult().message; + EXPECT_GT(arm.getSpeedLCommandTwistBase().vx, 0.019); + std::this_thread::sleep_for(100ms); + EXPECT_GT(arm.getTcpPose().x - restarted_from.x, 0.001); + ASSERT_TRUE(arm.stopL().ok()); + waitFor([&] { return !arm.busy(); }, 2s); + EXPECT_FALSE(arm.busy()); + EXPECT_FALSE(arm.isFault()); + EXPECT_TRUE(arm.getSpeedLResult().ok()); +} + +TEST_P(MotorRobotArmMujocoTest, TouchLogFailureBrakesWithoutHoldingOldVelocity) +{ + runTouchLog(false); +} + +TEST_P(MotorRobotArmMujocoTest, TouchLogAdaptiveSpeedSlowsBeforeWristLimit) +{ + runTouchLog(true); +} + +TEST_P(MotorRobotArmMujocoTest, TouchLogMinimumSpeedRatioStopsAndAllowsRecovery) +{ + runTouchLog(true, .1); +} + +void MotorRobotArmMujocoTest::runTouchLog(bool adaptive, double min_speed_ratio) +{ + if (std::string(GetParam().name) != "QpIk") GTEST_SKIP() << "QP touch-log replay"; + configureAdaptiveSpeed(adaptive, min_speed_ratio); + ASSERT_FALSE(HasFatalFailure()); + using namespace std::chrono_literals; + auto& arm = *arm_; + config::TouchScreenTaskRootConfig root; + ASSERT_TRUE(ProtoMessageIo::getProtoFromAsciiFile( + (project_root_ / "cmvr-es/config/tasks/touch_screen_task/touch_screen_task_mujoco.pb.txt").string(), + &root)); + const auto& cfg = root.touch_screen_task(); + std::vector initial; + for (const auto* name : kJointNames) { + const auto& joints = cfg.initialization().joint_positions(); + const auto joint = std::find_if(joints.begin(), joints.end(), + [&](const auto& item) { return item.joint_name() == name; }); + ASSERT_NE(joint, joints.end()); + initial.push_back(joint->rad()); + } + std::this_thread::sleep_for(300ms); + ASSERT_TRUE(arm.stopMotion().ok()); + MotionOptions initialize; + initialize.velocity = cfg.initialization().velocity(); + initialize.acceleration = cfg.initialization().acceleration(); + ASSERT_TRUE(arm.moveJ({initial}, initialize).ok()); + + // Replay the rounded 2026-09-30 09:44:56 PBVS log, without camera sampling. + // T_B_G_rot is an axis-angle vector in degrees (not Euler angles). + // The original pre-approach camera pose was not logged; reconstruct its + // locked yaw from the configured initial FK and this screen-frame estimate. + const Eigen::Vector3d rotation_vector = Eigen::Vector3d(64.205, -65.0019, -72.3706) * M_PI / 180.0; + const Eigen::Matrix3d R_B_G = Eigen::AngleAxisd( + rotation_vector.norm(), rotation_vector.normalized()).toRotationMatrix(); + const auto& hand = cfg.alignment().target().hand_orientation_g(); + const Eigen::Matrix3d R_G_H = + (Eigen::AngleAxisd(hand.rz(), Eigen::Vector3d::UnitZ()) * + Eigen::AngleAxisd(hand.ry(), Eigen::Vector3d::UnitY()) * + Eigen::AngleAxisd(hand.rx(), Eigen::Vector3d::UnitX())).toRotationMatrix(); + const auto& calibration = cfg.alignment().calibration().hand_tag_to_tcp(); + Eigen::Matrix3d R_H_P; + R_H_P << calibration.m00(), calibration.m01(), calibration.m02(), + calibration.m10(), calibration.m11(), calibration.m12(), + calibration.m20(), calibration.m21(), calibration.m22(); + const Eigen::Matrix3d R_target = R_G_H * R_H_P; + const Eigen::Matrix3d R_current = R_B_G.transpose() * + common::math::poseToMatrix(arm.getTcpPose()).block<3, 3>(0, 0); + Eigen::Vector3d projected = R_current.col(0) - R_target.col(2) * + R_target.col(2).dot(R_current.col(0)); + ASSERT_GT(projected.norm(), 1e-9); + projected.normalize(); + const double locked_yaw = std::atan2(R_target.col(1).dot(projected), + R_target.col(0).dot(projected)); + Eigen::Matrix4d target_B = Eigen::Matrix4d::Identity(); + target_B.block<3, 3>(0, 0) = R_B_G * R_target * + Eigen::AngleAxisd(locked_yaw, Eigen::Vector3d::UnitZ()).toRotationMatrix(); + target_B.block<3, 1>(0, 3) = Eigen::Vector3d(.544036, -.293155, -.31339); + const Eigen::Vector3d normal_B = R_B_G.col(2); + const Eigen::Vector3d anchor_B = target_B.block<3, 1>(0, 3) - + normal_B * cfg.alignment().target().position_offset_g().z(); + MotionOptions approach; + approach.velocity = cfg.approach().velocity(); + approach.acceleration = cfg.approach().acceleration(); + approach.jerk = cfg.approach().jerk(); + approach.is_tcp_pose_valid = [normal_B, anchor_B, clearance = cfg.approach().minimum_clearance_m()] + (const CartesianPose& pose) { + return normal_B.dot(Eigen::Vector3d(pose.x, pose.y, pose.z) - anchor_B) >= clearance; + }; + const auto approached = arm.moveP(common::math::matrixToPose(target_B), approach, FrameType::Base); + ASSERT_TRUE(approached.ok()) << approached.message; + const auto start_pose = arm.getTcpPose(); + const auto simulation_time = [&] { + std::lock_guard lock(world_->mutex()); + return world_->data()->time; + }; + const double start_simulation_time = simulation_time(); + const auto print_state = [&](double elapsed) { + const auto state = arm.getJointState(); + std::cout << std::setprecision(12) << "[TouchLogReplay] wall_s=" << elapsed + << " simulation_s=" << simulation_time() - start_simulation_time << " q="; + for (double q : state.position) std::cout << q << ' '; + std::cout << " qdot="; + for (double qd : state.velocity) std::cout << qd << ' '; + std::cout << std::endl; + }; + std::cout << "[TouchLogReplay] locked_yaw_rad=" << locked_yaw << std::endl; + print_state(0.0); + const auto& speed = cfg.touch().speed_l(); + SpeedLOptions options; + options.acceleration = speed.acceleration(); + options.linear_jerk = speed.linear_jerk(); + options.continuous_linear_reversal = true; + // Join the simulator's cycle barrier so no feedback sample is skipped, + // including the first failed QP cycle and the following joint braking. + const std::string probe = "touch_log_feedback_probe"; + struct ReleaseProbe { + std::shared_ptr world; + std::string name; + ~ReleaseProbe() { world->endControlCycle(name, true); } + } release{world_, probe}; + const double dt = world_->beginControlCycle(probe); + auto previous_velocity = arm.getJointState().velocity; + double maximum_acceleration = 0; + double minimum_wrist_position = std::numeric_limits::infinity(); + const auto started = std::chrono::steady_clock::now(); + ASSERT_TRUE(arm.speedL(common::math::vectorToVelocity( + common::math::toEigenVec6(speed.twist_tool())), options, 0, FrameType::Tool).ok()); + double last_command_speed = 0; + int samples = 0; + for (; samples < 3000; ++samples) { + world_->endControlCycle(probe, false); + world_->beginControlCycle(probe); + const auto state = arm.getJointState(); + ASSERT_EQ(state.velocity.size(), kDof); + ASSERT_EQ(state.position.size(), kDof); + for (std::size_t joint = 0; joint < kDof; ++joint) { + maximum_acceleration = std::max(maximum_acceleration, + std::abs(state.velocity[joint] - previous_velocity[joint]) / dt); + } + previous_velocity = state.velocity; + minimum_wrist_position = std::min(minimum_wrist_position, state.position[6]); + last_command_speed = common::math::velocityToVector( + arm.getSpeedLCommandTwistBase()).head<3>().norm(); + if (samples % 100 == 0) + print_state(std::chrono::duration(std::chrono::steady_clock::now() - started).count()); + if (adaptive && min_speed_ratio > 0 && arm.isFault()) { + // A threshold stop reports failure only after measured standstill. + EXPECT_FALSE(arm.busy()); + for (double velocity : state.velocity) EXPECT_NEAR(velocity, 0, 1e-6); + } + if (arm.isFault() && !arm.busy()) break; + } + world_->endControlCycle(probe, true); + print_state(std::chrono::duration(std::chrono::steady_clock::now() - started).count()); + const auto failure = arm.getSpeedLResult(); + std::cout << "[TouchLogReplay] adaptive=" << adaptive << " result=" << failure.message + << " tcp_distance_m=" << translationError(arm.getTcpPose(), start_pose) + << " max_measured_acceleration_rad_s2=" << maximum_acceleration + << " minimum_wrist_position_rad=" << minimum_wrist_position + << " final_command_speed_m_s=" << last_command_speed << std::endl; + EXPECT_LE(maximum_acceleration, 100.01); + EXPECT_GE(minimum_wrist_position, -.57001); + RecordProperty("maximum_measured_acceleration_rad_s2", std::to_string(maximum_acceleration)); + RecordProperty("minimum_wrist_position_rad", std::to_string(minimum_wrist_position)); + RecordProperty("final_command_speed_m_s", std::to_string(last_command_speed)); + if (adaptive && min_speed_ratio == 0) { + EXPECT_EQ(samples, 3000); + EXPECT_FALSE(arm.isFault()) << failure.message; + EXPECT_TRUE(failure.ok()) << failure.message; + EXPECT_LT(last_command_speed, .035); + ASSERT_TRUE(arm.stopL().ok()); + waitFor([&] { return !arm.busy(); }, 2s); + EXPECT_FALSE(arm.busy()); + EXPECT_FALSE(arm.isFault()) << arm.getSpeedLResult().message; + } else if (adaptive) { + EXPECT_LT(samples, 3000); + EXPECT_TRUE(arm.isFault()); + EXPECT_FALSE(arm.busy()); + EXPECT_EQ(failure.code, ArmErrorCode::OutOfVelocityLimit); + EXPECT_NE(failure.message.find("adaptive speed ratio below min_speed_ratio"), std::string::npos); + EXPECT_NEAR(last_command_speed, 0, 1e-9); + for (double velocity : arm.getJointState().velocity) EXPECT_NEAR(velocity, 0, 1e-6); + ASSERT_TRUE(arm.stopMotion().ok()); + ASSERT_TRUE(arm.recoverSpeedLPlanningFault().ok()); + EXPECT_FALSE(arm.isFault()); + EXPECT_TRUE(arm.getSpeedLResult().ok()); + const double wrist_at_stop = arm.getJointState().position[6]; + CartesianVelocity retreat; + retreat.vy = .04; + ASSERT_TRUE(arm.speedL(retreat, options, 0, FrameType::Tool).ok()); + waitFor([&] { return arm.getJointState().position[6] > wrist_at_stop + .01 || arm.isFault(); }, 2s); + EXPECT_FALSE(arm.isFault()) << arm.getSpeedLResult().message; + EXPECT_GT(arm.getJointState().position[6], wrist_at_stop + .01); + ASSERT_TRUE(arm.stopL().ok()); + waitFor([&] { return !arm.busy(); }, 2s); + EXPECT_FALSE(arm.busy()); + EXPECT_TRUE(arm.getSpeedLResult().ok()) << arm.getSpeedLResult().message; + } else { + EXPECT_TRUE(arm.isFault()); + EXPECT_EQ(failure.code, ArmErrorCode::CommandFailed); + EXPECT_NE(failure.message.find("infeasible within joint limits"), std::string::npos); + // Before the fix the wrist held its old speed for two more ticks and + // finished at -0.569448 rad. Same-cycle braking must stop earlier. + EXPECT_GE(minimum_wrist_position, -.5693); + EXPECT_LT(minimum_wrist_position, -.54); + for (double velocity : arm.getJointState().velocity) EXPECT_NEAR(velocity, 0, 1e-6); + } + ASSERT_TRUE(arm.stopMotion().ok()); +} + +TEST_P(MotorRobotArmMujocoTest, SpeedLScalingAndRecovery) +{ + using namespace std::chrono_literals; + struct Release { + std::shared_ptr world; + std::string id; + ~Release() { world->endControlCycle(id, true); } + }; + auto& arm = *arm_; + std::this_thread::sleep_for(300ms); + MotionOptions move; + move.velocity = 1.0; + move.acceleration = 3.0; + ASSERT_TRUE(arm.moveJ({{.25, 1.0, M_PI / 2, M_PI / 2, -M_PI / 2, 0, 0}}, move).ok()); + CartesianVelocity target; + target.vx = .05; + SpeedLOptions options; + options.acceleration = .5; + options.linear_jerk = 10; + options.capture_reference = true; + ASSERT_TRUE(arm.speedL(target, options, 0, FrameType::Base).ok()); + waitFor([&] { return std::abs(arm.getSpeedLCommandTwistBase().vx - .05) < 1e-5; }, 2s); + const auto reference = arm.getSpeedLReference(); + ASSERT_TRUE(reference.valid); + for (const double scaling : {.5, 0.0, 1.0}) { + ASSERT_TRUE(arm.setSpeedScaling(scaling).ok()); + waitFor([&] { return std::abs(arm.getSpeedLCommandTwistBase().vx - .05 * scaling) < 1e-5; }, 2s); + EXPECT_NEAR(arm.getSpeedLCommandTwistBase().vx, .05 * scaling, 1e-5); + EXPECT_TRUE(arm.busy()); // A zero multiplier pauses without completing the command. + EXPECT_EQ(arm.getSpeedLReference().command_version, reference.command_version); + EXPECT_DOUBLE_EQ(arm.getSpeedLReference().tcp_pose_base.x, reference.tcp_pose_base.x); + } + EXPECT_FALSE(arm.setSpeedScaling(std::numeric_limits::quiet_NaN()).ok()); + EXPECT_DOUBLE_EQ(arm.getSpeedScaling(), 1.0); + + ASSERT_TRUE(arm.shutdown().ok()); + EXPECT_FALSE(arm.busy()); + EXPECT_NEAR(arm.getSpeedLCommandTwistBase().vx, 0.0, 1e-12); + target.vx = -.05; + { + // Observe exactly the first restarted command before physics advances. + const std::string probe = "speedl_restart_probe"; + Release release{world_, probe}; + world_->beginControlCycle(probe); + ASSERT_TRUE(arm.speedL(target, options, 0, FrameType::Base).ok()); + waitFor([&] { return arm.getSpeedLCommandTwistBase().vx < -1e-12; }, 1s); + const auto restarted = arm.getSpeedLCommandTwistBase().vx; + EXPECT_LT(restarted, 0.0); + EXPECT_GT(restarted, -.01); // Starts from rest, not the interrupted +.05 command. + } + ASSERT_TRUE(arm.stopL().ok()); + waitFor([&] { return !arm.busy(); }, 3s); + EXPECT_FALSE(arm.busy()); + EXPECT_TRUE(arm.getSpeedLResult().ok()) << arm.getSpeedLResult().message; + EXPECT_FALSE(arm.isFault()); + ASSERT_TRUE(arm.shutdown().ok()); + + target.vx = .02; + ASSERT_TRUE(arm.speedL(target, options, 0, FrameType::Base).ok()); + waitFor([&] { return std::abs(arm.getSpeedLCommandTwistBase().vx - .02) < 1e-5; }, 2s); + ASSERT_TRUE(arm.protectiveStop().ok()); + EXPECT_TRUE(arm.isProtectiveStopped()); + EXPECT_FALSE(arm.busy()); + EXPECT_FALSE(arm.isFault()); + ASSERT_TRUE(arm.unlockProtectiveStop().ok()); + target.vx = -.02; + ASSERT_TRUE(arm.speedL(target, options, 0, FrameType::Base).ok()); + waitFor([&] { return std::abs(arm.getSpeedLCommandTwistBase().vx + .02) < 1e-5; }, 2s); + EXPECT_NEAR(arm.getSpeedLCommandTwistBase().vx, -.02, 1e-5); + ASSERT_TRUE(arm.stopL().ok()); + waitFor([&] { return !arm.busy(); }, 3s); + ASSERT_TRUE(arm.shutdown().ok()); + EXPECT_FALSE(arm.isFault()); + + // Hold the physics boundary while comparing the public feedback with + // MuJoCo's independent site Jacobian; the planner is idle throughout. + const std::string probe = "speedl_feedback_probe"; + Release release{world_, probe}; + world_->beginControlCycle(probe); + JointVelocityCommand joint; + joint.velocity.assign(kDof, 0.0); + joint.velocity[0] = .08; + ASSERT_TRUE(arm.speedJ(joint, 0, 0).ok()); + world_->endControlCycle(probe, false); + world_->beginControlCycle(probe); + const auto state = arm.getRobotState(); + Eigen::Matrix actual = Eigen::Matrix::Zero(); + { + std::lock_guard lock(world_->mutex()); + const auto* model = world_->model(); + const auto* data = world_->data(); + const int site = mj_name2id(model, mjOBJ_SITE, "R_FINGER_TIP_SITE"); + ASSERT_GE(site, 0); + std::vector jp(3 * model->nv), jr(3 * model->nv); + mj_jacSite(model, data, jp.data(), jr.data(), site); + for (int axis = 0; axis < 3; ++axis) + for (int j = 0; j < model->nv; ++j) { + actual[axis] += jp[axis * model->nv + j] * data->qvel[j]; + actual[axis + 3] += jr[axis * model->nv + j] * data->qvel[j]; + } + } + const auto& v = state.actual_tcp_velocity; + const Eigen::Matrix reported = (Eigen::Matrix() << v.vx, v.vy, v.vz, v.wx, v.wy, v.wz).finished(); + EXPECT_LT((reported - actual).norm(), 1e-7); + EXPECT_GT(reported.norm(), .01); + EXPECT_NEAR(arm.getSpeedLCommandTwistBase().vx, 0, 1e-12); + + std::vector> motors; + for (const auto* name : kJointNames) motors.push_back(motor_system_->getMotor(name)); + auto invalid = joint.velocity; + invalid[0] = -.08; + invalid.back() = std::numeric_limits::quiet_NaN(); + EXPECT_FALSE(motor_system_->commandCyclicVelocitiesAtomic(motors, invalid)); + world_->endControlCycle(probe, false); + world_->beginControlCycle(probe); + EXPECT_NEAR(arm.getJointState().velocity[0], .08, 1e-12); // No partial write before detecting NaN. + ASSERT_TRUE(arm.stopJ(0).ok()); } INSTANTIATE_TEST_SUITE_P( diff --git a/cmvr-es/devices/arm/motor_robot_arm/src/motor_robot_arm_speedl_stop_test.cpp b/cmvr-es/devices/arm/motor_robot_arm/src/motor_robot_arm_speedl_stop_test.cpp index 49b61bcf..004b12bf 100644 --- a/cmvr-es/devices/arm/motor_robot_arm/src/motor_robot_arm_speedl_stop_test.cpp +++ b/cmvr-es/devices/arm/motor_robot_arm/src/motor_robot_arm_speedl_stop_test.cpp @@ -20,6 +20,7 @@ #include "algorithms/kinematics/ik_solver/ik_solver_factory.h" #include "algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_ik_base.h" +#include "common/config/config_files.h" #include "common/io/proto_file_io.h" #include "devices/motor/manager/include/motor_manager.h" #include "simulate/mujoco/mujoco_world/include/mujoco_world.h" @@ -201,6 +202,8 @@ protected: { project_root_ = findProjectRoot(); ASSERT_FALSE(project_root_.empty()); + ConfigHelper::setConfigRootFromFile( + (project_root_ / "cmvr-es/config/cmvr_es.pb.txt").string()); config::MujocoWorldRootConfig world_root_config; ASSERT_TRUE(ProtoMessageIo::getProtoFromAsciiFile( diff --git a/cmvr-es/devices/arm/motor_robot_arm/src/rrt_connect_mujoco_test.cpp b/cmvr-es/devices/arm/motor_robot_arm/src/rrt_connect_mujoco_test.cpp new file mode 100644 index 00000000..a4c449f4 --- /dev/null +++ b/cmvr-es/devices/arm/motor_robot_arm/src/rrt_connect_mujoco_test.cpp @@ -0,0 +1,357 @@ +#include "arm/motor_robot_arm/include/motor_robot_arm.h" +#include "algorithms/kinematics/ik_solver/ik_solver_factory.h" +#include "common/config/config_files.h" +#include "common/io/proto_file_io.h" +#include "common/math/transform_math.h" +#include "devices/motor/manager/include/motor_manager.h" +#include "simulate/mujoco/mujoco_viewer/include/mujoco_viewer.h" +#include "simulate/mujoco/mujoco_world/include/mujoco_world.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace cmvr::device { +namespace { +using Clock = std::chrono::steady_clock; + +struct FeedbackSample { + double time_s, sim_time_s; + std::vector position, velocity; +}; + +void writePlannedCsv(const std::filesystem::path& path, const JointTrajectory& trajectory) +{ + if (trajectory.empty()) return; + std::ofstream csv(path); + ASSERT_TRUE(csv.is_open()) << path; + csv << std::setprecision(17) << "time_s"; + for (std::size_t j = 0; j < trajectory.front().position.size(); ++j) + csv << ",q" << j + 1 << "_rad,v" << j + 1 << "_rad_s,a" << j + 1 << "_rad_s2,j" << j + 1 << "_rad_s3"; + csv << '\n'; + for (const auto& p : trajectory) { + ASSERT_EQ(p.acceleration.size(), p.position.size()); + ASSERT_EQ(p.jerk.size(), p.position.size()); + csv << p.time_s; + for (std::size_t j = 0; j < p.position.size(); ++j) + csv << ',' << p.position[j] << ',' << p.velocity[j] << ',' << p.acceleration[j] << ',' << p.jerk[j]; + csv << '\n'; + } + ASSERT_TRUE(csv.good()); +} + +void writeFeedbackCsv(const std::filesystem::path& path, const std::vector& samples) +{ + if (samples.empty()) return; + std::ofstream csv(path); + ASSERT_TRUE(csv.is_open()) << path; + csv << std::setprecision(17) << "time_s,sim_time_s,acceleration_time_s,jerk_time_s"; + const auto dof = samples.front().position.size(); + for (std::size_t j = 0; j < dof; ++j) + csv << ",q" << j + 1 << "_rad,v" << j + 1 << "_rad_s,a" << j + 1 << "_fd_rad_s2,j" << j + 1 << "_fd_rad_s3"; + csv << '\n'; + const double nan = std::numeric_limits::quiet_NaN(); + std::vector previous_acceleration(dof, nan); + double previous_acceleration_time = nan; + for (std::size_t i = 0; i < samples.size(); ++i) { + const auto& p = samples[i]; + const double dt = i ? p.time_s - samples[i - 1].time_s : nan; + const double at = i ? 0.5 * (p.time_s + samples[i - 1].time_s) : nan; + const double jt = i > 1 ? 0.5 * (at + previous_acceleration_time) : nan; + csv << p.time_s << ',' << p.sim_time_s << ',' << at << ',' << jt; + for (std::size_t j = 0; j < dof; ++j) { + const double a = i ? (p.velocity[j] - samples[i - 1].velocity[j]) / dt : nan; + const double jerk = i > 1 ? (a - previous_acceleration[j]) / (at - previous_acceleration_time) : nan; + csv << ',' << p.position[j] << ',' << p.velocity[j] << ',' << a << ',' << jerk; + previous_acceleration[j] = a; + } + previous_acceleration_time = at; + csv << '\n'; + } + ASSERT_TRUE(csv.good()); +} + +class RrtConnectMujocoTest : public ::testing::Test { +protected: + void SetUp() override + { + const std::filesystem::path root{CMVR_ES_SOURCE_DIR}; + ConfigHelper::setConfigRootFromFile((root / "cmvr-es/config/cmvr_es.pb.txt").string()); + config::ArmRootConfig arms; + ASSERT_TRUE(ProtoMessageIo::getProtoFromAsciiFile( + (root / "cmvr-es/config/devices/arm/arm_mujoco.pb.txt").string(), &arms)); + ASSERT_GT(arms.arm().robot_arms_size(), 0); + auto arm_config = arms.arm().robot_arms(0); + arm_config.mutable_kinematics()->mutable_pinocchio_dls_ik_solver()->set_urdf_path( + (root / "model/xiaoyan_description/dual_arm.urdf").string()); + arm_config.mutable_motion()->mutable_joint_path()->mutable_collision_checker()->set_urdf_path( + (root / "model/xiaoyan_description/dual_arm_collision.urdf").string()); + const std::vector joints(arm_config.motor().joint_names().begin(), + arm_config.motor().joint_names().end()); + + config::MujocoWorldConfig world_config; + world_config.set_id("mujoco_world"); + world_config.set_model_path((root / "model/xiaoyan_description/dual_arm.xml").string()); + world_config.set_timestep_s(0.001); + world_config.set_realtime_factor(1.0); + world_config.set_require_actuator(true); + world_ = std::make_shared(world_config); + ASSERT_TRUE(world_->init()); + // 只在仿真启动前设置初始姿态;规划后的运动通过机械臂接口执行。 + const std::vector initial{0.25, 1.0, 1.5708, 1.5708, -1.5708, 0.0, 0.0}; + ASSERT_EQ(joints.size(), initial.size()); + for (std::size_t i = 0; i < joints.size(); ++i) { + ASSERT_TRUE(world_->world()->setJointPosition(joints[i], initial[i])); + } + // 仿真关节限位可能比 URDF 更窄,规划使用两者的交集。 + auto* limits = arm_config.mutable_kinematics()->mutable_pinocchio_dls_ik_solver() + ->mutable_joint_limit_policy()->mutable_limits(); + const auto* model = world_->world()->model(); + for (auto& limit : *limits->mutable_joints()) { + const int joint = mj_name2id(model, mjOBJ_JOINT, limit.joint_name().c_str()); + ASSERT_GE(joint, 0); + limit.set_q_lb(std::max(limit.q_lb(), model->jnt_range[2 * joint])); + limit.set_q_ub(std::min(limit.q_ub(), model->jnt_range[2 * joint + 1])); + } + target_fk_ = cmvr::IKSolverFactory::create(arm_config.kinematics()); + ASSERT_TRUE(target_fk_); + ASSERT_TRUE(target_fk_->init()); + ASSERT_TRUE(world_->start()); + + config::MotorRootConfig motors; + ASSERT_TRUE(ProtoMessageIo::getProtoFromAsciiFile( + (root / "cmvr-es/config/devices/motor/mujoco_motors.pb.txt").string(), &motors)); + ASSERT_EQ(motors.motor().motor_groups_size(), 1); + ASSERT_EQ(motors.motor().motor_groups(0).bus_type(), config::MOTOR_BUS_MUJOCO); + motors_ = std::make_shared( + arm_config.motor().motor_system_id(), motors.motor(), "right_arm_mujoco_motors"); + ASSERT_TRUE(motors_->init()); + arm_ = std::make_shared(arm_config); + ASSERT_TRUE(arm_->init()); + ASSERT_TRUE(arm_->torqueOn().ok()); + } + + void TearDown() override + { + if (arm_) arm_->stop(); + if (motors_) motors_->stop(); + if (world_) world_->stop(); + } + + std::shared_ptr world_; + std::shared_ptr motors_; + std::shared_ptr arm_; + std::shared_ptr target_fk_; +}; + +TEST_F(RrtConnectMujocoTest, MovePWithViewer) +{ + const bool suite = std::getenv("CMVR_MOVEP_SUITE") != nullptr; + const bool headless = std::getenv("CMVR_MOVEP_HEADLESS") != nullptr; + const bool auto_close = std::getenv("CMVR_MOVEP_AUTO_CLOSE") != nullptr; + const char* output = std::getenv("CMVR_MOVEP_CSV_DIR"); + const std::filesystem::path directory = output ? output : + (std::filesystem::path(CMVR_ES_SOURCE_DIR) / "output/movep_csv").string(); + std::filesystem::create_directories(directory); + const auto names = arm_->getRobotModel().joint_names; + const auto initial = arm_->getJointState().position; + std::ofstream joint_names(directory / "joints.csv"); + joint_names << "index,name\n"; + std::vector q_indices, v_indices; + for (std::size_t j = 0; j < names.size(); ++j) { + joint_names << j + 1 << ',' << names[j] << '\n'; + const int id = mj_name2id(world_->world()->model(), mjOBJ_JOINT, names[j].c_str()); + ASSERT_GE(id, 0); + q_indices.push_back(world_->world()->model()->jnt_qposadr[id]); + v_indices.push_back(world_->world()->model()->jnt_dofadr[id]); + } + struct Target { const char* name; std::vector joints; CartesianPose pose; }; + struct Profile { const char* name; double velocity, acceleration, jerk; }; + std::vector targets{ + {"joint_pose_1", {-0.446719, -0.013159, 2.513135, 1.522461, -0.638216, 0.254061, -0.2}, {}}, + {"joint_pose_2", {-0.557132, 1.234893, 1.293086, 1.99, -1.833259, -0.595983, 0.422149}, {}}, + {"joint_pose_3", {-0.524703, 0.407224, 1.582127, 0.663140, -0.736188, 0.154737, -0.2}, {}}, + {"joint_pose_4", {0.710814, 0.438574, 0.687546, 1.99, -1.031896, 0.72, 0.179214}, {}}, + {"joint_pose_5", {0.497175, 1.411030, 2.583072, 1.645615, -1.950738, -0.72, 0.825329}, {}}, + {"joint_pose_6", {0.694478, 1.237590, 2.214783, 1.99, -0.669084, 0.72, -0.2}, {}}, + {"joint_pose_7", {-0.549076, 1.51, 2.525787, 1.551384, -0.523898, -0.72, -0.061424}, {}}, + {"joint_pose_8", {0.197744, 1.51, 2.622572, 0.913252, -2.040164, 0.254035, 0.967050}, {}}}; + if (!suite) targets.resize(1); + std::vector profiles{{"v065_a170_j030", 0.65, 1.7, 30.0}}; + if (suite) { + if (!std::getenv("CMVR_MOVEP_PROBE")) + profiles = {{"v030_a080_j030", 0.30, 0.8, 30.0}, {"v065_a080_j030", 0.65, 0.8, 30.0}, + {"v030_a170_j030", 0.30, 1.7, 30.0}, {"v065_a170_j030", 0.65, 1.7, 30.0}, + {"v065_a170_j001", 0.65, 1.7, 1.0}, {"v065_a170_j005", 0.65, 1.7, 5.0}, + {"v065_a170_j100", 0.65, 1.7, 100.0}}; + } + Eigen::VectorXd lower, upper; + ASSERT_TRUE(target_fk_->getJointPositionLimits(lower, upper)); + for (auto& target : targets) { + ASSERT_EQ(target.joints.size(), names.size()); + for (std::size_t j = 0; j < target.joints.size(); ++j) { + ASSERT_GE(target.joints[j], lower[j]); + ASSERT_LE(target.joints[j], upper[j]); + } + // 只用候选关节角计算目标 TCP 位姿,不修改仿真或电机当前状态。 + Eigen::Matrix4d transform; + ASSERT_TRUE(target_fk_->fk(target.joints, transform, true)); + target.pose = common::math::matrixToPose(transform); + } + const auto orientation_distance = [](const CartesianPose& a, const CartesianPose& b) { + const Eigen::Matrix3d ra = common::math::poseToMatrix(a).topLeftCorner<3, 3>(); + const Eigen::Matrix3d rb = common::math::poseToMatrix(b).topLeftCorner<3, 3>(); + return Eigen::AngleAxisd(ra.transpose() * rb).angle(); + }; + std::unique_ptr viewer; + if (!headless) { + viewer = std::make_unique(world_->world()); + viewer->setupCamera(2.5, -160.0, -20.0); + viewer->setRunning(true); + } + std::atomic closed{false}; + std::thread motion([&] { + if (!headless) std::this_thread::sleep_for(std::chrono::seconds(2)); + std::ofstream summary(directory / "cases.csv"); + summary << std::setprecision(17) + << "case,target,velocity_limit,acceleration_limit,jerk_limit,dx,dy,dz," + "origin_x,origin_y,origin_z,target_x,target_y,target_z,success,error_code," + "moveP_wall_s,planned_duration_s,planned_samples,feedback_samples," + "final_tcp_error_m,message,drx,dry,drz,origin_rx,origin_ry,origin_rz," + "target_rx,target_ry,target_rz,reached_x,reached_y,reached_z," + "reached_rx,reached_ry,reached_rz,requested_orientation_change_rad," + "final_orientation_error_rad"; + for (std::size_t j = 0; j < names.size(); ++j) summary << ",fk_q" << j + 1 << "_rad"; + summary << '\n'; + bool first = true; + for (const auto& candidate : targets) for (const auto& profile : profiles) { + if (closed.load()) return; + // 每次经机械臂接口回到同一关节起点,避免不同试验的 IK 种子漂移。 + const auto current = arm_->getJointState().position; + double return_distance = 0.0; + for (std::size_t j = 0; j < initial.size(); ++j) + return_distance = std::max(return_distance, std::abs(current[j] - initial[j])); + if (!first && return_distance > 1e-6) { + MotionOptions reset; + reset.velocity = 0.65; reset.acceleration = 1.7; reset.jerk = 30.0; + reset.cancellation_requested = [&] { return closed.load(); }; + const auto returned = arm_->moveJ(JointPositionCommand{initial}, reset); + if (!returned.ok()) { + ADD_FAILURE() << "return to start failed: " << returned.message; + if (viewer) viewer->requestStop(); + return; + } + } + first = false; + const CartesianPose origin = arm_->fk(true); + const CartesianPose target = candidate.pose; + const double dx = target.x - origin.x, dy = target.y - origin.y, dz = target.z - origin.z; + const double orientation_change = orientation_distance(origin, target); + EXPECT_GT(std::hypot(std::hypot(dx, dy), dz), 0.001); + EXPECT_GT(orientation_change, 1e-3); + const std::string id = std::string(candidate.name) + "_" + profile.name; + JointTrajectory planned; + std::vector feedback; + feedback.reserve(20000); + std::atomic capturing{false}, finished{false}; + Clock::time_point epoch; + std::thread recorder([&] { + auto next = Clock::now(); + double last_sim_time = -1.0; + while (!finished.load()) { + if (capturing.load()) { + FeedbackSample sample; + sample.position.resize(names.size()); + sample.velocity.resize(names.size()); + { + // 同一仿真步的 q/v 快照;DirectState 模式下不用 qacc 当作实际加速度。 + std::lock_guard lock(world_->world()->mutex()); + const auto* data = world_->world()->data(); + sample.time_s = std::chrono::duration(Clock::now() - epoch).count(); + sample.sim_time_s = data->time; + for (std::size_t j = 0; j < names.size(); ++j) { + sample.position[j] = data->qpos[q_indices[j]]; + sample.velocity[j] = data->qvel[v_indices[j]]; + } + } + if (sample.sim_time_s > last_sim_time) { + last_sim_time = sample.sim_time_s; + feedback.push_back(std::move(sample)); + } + } + next = std::max(next + std::chrono::milliseconds(1), Clock::now()); + std::this_thread::sleep_until(next); + } + }); + MotionOptions options; + options.velocity = profile.velocity; + options.acceleration = profile.acceleration; + options.jerk = profile.jerk; + options.cancellation_requested = [&] { return closed.load(); }; + options.trajectory_callback = [&](const JointTrajectory& trajectory) { + planned = trajectory; + epoch = Clock::now(); // 执行前轨迹回调完成时刻,不额外对齐或平移反馈曲线。 + capturing.store(true); + }; + std::cout << "[MovePCase] begin " << id + << " translation_m=" << std::hypot(std::hypot(dx, dy), dz) + << " rotation_rad=" << orientation_change << std::endl; + const auto begin = Clock::now(); + const auto result = arm_->moveP(target, options, FrameType::Base); + const double elapsed = std::chrono::duration(Clock::now() - begin).count(); + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + finished.store(true); + recorder.join(); + writePlannedCsv(directory / (id + "_planned.csv"), planned); + writeFeedbackCsv(directory / (id + "_actual.csv"), feedback); + const auto reached = arm_->fk(true); + const double error = std::hypot(std::hypot(reached.x - target.x, reached.y - target.y), reached.z - target.z); + const double orientation_error = orientation_distance(reached, target); + summary << id << ',' << candidate.name << ',' << options.velocity << ',' << options.acceleration + << ',' << options.jerk << ',' << dx << ',' << dy << ',' << dz + << ',' << origin.x << ',' << origin.y << ',' << origin.z + << ',' << target.x << ',' << target.y << ',' << target.z + << ',' << result.ok() << ',' << static_cast(result.code) << ',' << elapsed + << ',' << (planned.empty() ? 0.0 : planned.back().time_s) + << ',' << planned.size() << ',' << feedback.size() << ',' << error + << ',' << std::quoted(result.message) + << ',' << target.rx - origin.rx << ',' << target.ry - origin.ry << ',' << target.rz - origin.rz + << ',' << origin.rx << ',' << origin.ry << ',' << origin.rz + << ',' << target.rx << ',' << target.ry << ',' << target.rz + << ',' << reached.x << ',' << reached.y << ',' << reached.z + << ',' << reached.rx << ',' << reached.ry << ',' << reached.rz + << ',' << orientation_change << ',' << orientation_error; + for (const double q : candidate.joints) summary << ',' << q; + summary << '\n'; + summary.flush(); + std::cout << "[MovePCase] end " << id << " success=" << result.ok() + << " position_error_m=" << error << " orientation_error_rad=" << orientation_error + << " message=" << result.message << " csv=" << directory << std::endl; + if (!closed.load()) { + EXPECT_TRUE(result.ok()) << id << ": " << result.message; + if (result.ok()) { + EXPECT_LT(error, 0.002) << id; + EXPECT_LT(orientation_error, 0.005) << id; + } + } + } + if (auto_close || headless) if (viewer) viewer->requestStop(); + }); + if (!headless) { + viewer->run(); + closed.store(true); + } + motion.join(); +} + +} // namespace +} // namespace cmvr::device diff --git a/cmvr-es/devices/arm/motor_robot_arm/src/speed_l_executor.cpp b/cmvr-es/devices/arm/motor_robot_arm/src/speed_l_executor.cpp new file mode 100644 index 00000000..514faf43 --- /dev/null +++ b/cmvr-es/devices/arm/motor_robot_arm/src/speed_l_executor.cpp @@ -0,0 +1,636 @@ +#include "devices/arm/motor_robot_arm/include/speed_l_executor.h" + +#include +#include +#include +#include +#include +#include + +#include "common/base/logging/logger.h" +#include "common/config/config_files.h" +#include "common/math/transform_math.h" + +namespace cmvr::device { +namespace { + +SpeedLExecutor::Config normalizeConfig(SpeedLExecutor::Config config) +{ + const SpeedLExecutor::Config defaults; + using cmvr::common::config::positiveOr; + config.control_period_s = positiveOr(config.control_period_s, defaults.control_period_s); + config.stop_twist_norm = positiveOr(config.stop_twist_norm, defaults.stop_twist_norm); + config.stop_command_velocity_norm = positiveOr(config.stop_command_velocity_norm, defaults.stop_command_velocity_norm); + config.stop_measured_velocity_norm = positiveOr(config.stop_measured_velocity_norm, defaults.stop_measured_velocity_norm); + config.stop_acceleration = positiveOr(config.stop_acceleration, defaults.stop_acceleration); + config.stop_timeout_s = positiveOr(config.stop_timeout_s, defaults.stop_timeout_s); + return config; +} + +Result callbackException(const char* operation) +{ + try { + throw; + } catch (const std::exception& error) { + return Result::failure(ArmErrorCode::CommandFailed, std::string(operation) + ": " + error.what()); + } catch (...) { + return Result::failure(ArmErrorCode::CommandFailed, std::string(operation) + ": unknown exception"); + } +} + +// Release a failed simulation cycle before recovery attempts another one. +struct CycleGuard { + const SpeedLExecutor::EndCycleCallback& end; + Result& status; + bool& computation_result; + bool active{false}; + ~CycleGuard() + { + if (!active) return; + try { + end(false); + } catch (...) { + computation_result = false; + const auto error = callbackException("end speedL cycle"); + if (status.ok()) status = error; + else status.message += "; " + error.message; + } + } +}; + +} // namespace + +SpeedLExecutor::SpeedLExecutor( + Config config, std::shared_ptr planner, + const std::size_t dof, ReadStateCallback read_state, + SendVelocityCallback send_velocity, ReadScalingCallback read_scaling, + BeginCycleCallback begin_cycle, EndCycleCallback end_cycle) + : config_(normalizeConfig(config)), planner_(std::move(planner)), dof_(dof), + read_state_(std::move(read_state)), send_velocity_(std::move(send_velocity)), + read_scaling_(std::move(read_scaling)), begin_cycle_(std::move(begin_cycle)), + end_cycle_(std::move(end_cycle)) +{ +} + +SpeedLExecutor::~SpeedLExecutor() +{ + (void)shutdown(); +} + +Result SpeedLExecutor::speedL(const CartesianVelocity& velocity, + const SpeedLOptions& options, + const double duration, const FrameType frame) +{ + if (!planner_ || !read_state_ || !send_velocity_ || dof_ == 0 || + static_cast(begin_cycle_) != static_cast(end_cycle_) || + !std::isfinite(options.acceleration) || options.acceleration <= 0.0 || + !std::isfinite(duration) || duration < 0.0 || !std::isfinite(twistNorm_(velocity)) || + (frame != FrameType::Base && frame != FrameType::Tool) || + (options.linear_jerk && (!std::isfinite(*options.linear_jerk) || *options.linear_jerk <= 0.0))) { + return Result::failure(ArmErrorCode::InvalidArgument, "speedL invalid input"); + } + std::uint64_t version; + { + std::lock_guard lifecycle(lifecycle_mutex_); + std::lock_guard lock(mutex_); + if (faulted_.load()) { + return Result::failure(ArmErrorCode::RobotInFault, + "speedL fault must be cleared: " + last_result_.message); + } + if (!pending_stop_reason_.ok()) { + return Result::failure(ArmErrorCode::RobotNotReady, + "speedL is stopping: " + pending_stop_reason_.message); + } + if (finishing_) { + return Result::failure(ArmErrorCode::RobotNotReady, "speedL is confirming stop"); + } + if (!command_active_) { + reset_required_ = true; + last_result_ = Result::success(); + } + target_twist_ = velocity; + target_frame_ = frame; + target_options_ = options; + reference_ = {}; + command_active_ = true; + busy_.store(true); + version = ++command_version_; + if (!worker_.joinable()) { + stop_requested_.store(false); + shutdown_result_ = Result::success(); + try { + worker_ = std::thread(&SpeedLExecutor::workerLoop_, this); + } catch (...) { + command_active_ = false; + busy_.store(false); + return callbackException("start speedL worker"); + } + } + } + cv_.notify_all(); + + if (duration > 0.0) { + std::this_thread::sleep_for(std::chrono::duration(duration)); + { + std::lock_guard lock(mutex_); + // Scaling updates do not replace the command or restart its timer. + if (command_active_ && command_version_ == version && !faulted_.load() && + pending_stop_reason_.ok()) { + setStopTargetLocked_(target_options_.acceleration); + } + } + cv_.notify_all(); + return lastResult(); + } + return Result::success(); +} + +Result SpeedLExecutor::stop(const std::optional acceleration) +{ + const double value = acceleration.value_or(config_.stop_acceleration); + if (!std::isfinite(value) || value <= 0.0) { + return Result::failure(ArmErrorCode::InvalidArgument, "stop acceleration must be positive and finite"); + } + std::lock_guard lifecycle(lifecycle_mutex_); + std::lock_guard lock(mutex_); + // A faulted active command is already braking. Accept an idempotent stop + // without replacing that phase or hiding its separately queryable error. + if (faulted_.load()) return command_active_ ? Result::success() : last_result_; + if (!pending_stop_reason_.ok()) return Result::success(); + if (!command_active_) return Result::success(); + setStopTargetLocked_(value); + cv_.notify_all(); + return Result::success(); +} + +Result SpeedLExecutor::shutdown() +{ + std::lock_guard lifecycle(lifecycle_mutex_); + if (worker_.joinable()) { + stop_requested_.store(true); + cv_.notify_all(); + worker_.join(); + stop_requested_.store(false); + std::lock_guard lock(mutex_); + return shutdown_result_; + } + if (busy_.load()) { + { + std::lock_guard lock(mutex_); + finishing_ = true; + } + finishCommand_(); + } + std::lock_guard lock(mutex_); + return shutdown_result_; +} + +Result SpeedLExecutor::clearFault() +{ + return clearFault_(false); +} + +Result SpeedLExecutor::clearPlanningFault() +{ + return clearFault_(true); +} + +void SpeedLExecutor::recordStopFailure(const Result& result) +{ + if (result.ok()) return; + std::lock_guard lifecycle(lifecycle_mutex_); + std::lock_guard lock(mutex_); + recordFailureLocked_(result); +} + +Result SpeedLExecutor::clearFault_(const bool planning_only) +{ + std::lock_guard lifecycle(lifecycle_mutex_); + const auto explicit_recovery = [&] { + return Result::failure(ArmErrorCode::RobotInFault, + "speedL fault requires explicit recovery: " + last_result_.message); + }; + { + std::lock_guard lock(mutex_); + if (command_active_ || finishing_) { + return Result::failure(ArmErrorCode::RobotNotReady, "speedL is still stopping"); + } + if (!faulted_.load()) return Result::success(); + if (planning_only && !planning_fault_) return explicit_recovery(); + finishing_ = true; + } + // A callback failure may have terminated the worker itself. Reap either + // an idle or exited worker before acknowledging the fault and restarting. + if (worker_.joinable()) { + stop_requested_.store(true); + cv_.notify_all(); + worker_.join(); + stop_requested_.store(false); + } + { + std::lock_guard lock(mutex_); + // Joining can expose a late callback or stop-confirmation failure. + if (planning_only && !planning_fault_) { + finishing_ = false; + return explicit_recovery(); + } + finishing_ = true; + } + const auto stopped = finish_(); + std::lock_guard lock(mutex_); + finishing_ = false; + reset_required_ = true; + busy_.store(!stopped.ok()); + shutdown_result_ = stopped; + if (!stopped.ok()) { + recordFailureLocked_(stopped); + return stopped; + } + if (planning_only) { + CMVR_LOG(INFO) << "[SpeedLExecutor] clearing stopped planning fault: " << last_result_.message; + } + faulted_.store(false); + planning_fault_ = false; + last_result_ = Result::success(); + command_twist_snapshot_ = {}; + return Result::success(); +} + +Result SpeedLExecutor::lastResult() const +{ + std::lock_guard lock(mutex_); + return last_result_; +} + +CartesianVelocity SpeedLExecutor::getCommandTwistBase() const +{ + std::lock_guard lock(mutex_); + return command_twist_snapshot_; +} + +SpeedLReference SpeedLExecutor::getReference() const +{ + std::lock_guard lock(mutex_); + return reference_; +} + +void SpeedLExecutor::workerLoop_() +{ + using Clock = std::chrono::steady_clock; + const auto period = std::chrono::duration_cast( + std::chrono::duration(config_.control_period_s)); + std::vector q_now, qd_now; + std::uint64_t submitted_version = 0, recovery_version = 0; + std::optional accepted_options; + std::optional stop_started; + auto previous_tick = Clock::now(); + bool first_tick = true; + bool braking = false; + + try { + while (true) { + CartesianVelocity target; + FrameType frame; + SpeedLOptions options; + std::uint64_t version; + bool reset; + bool controlled_stopping; + { + std::unique_lock lock(mutex_); + cv_.wait(lock, [&] { return stop_requested_.load() || command_active_; }); + if (stop_requested_.load()) break; + target = target_twist_; + frame = target_frame_; + options = target_options_; + version = command_version_; + reset = reset_required_; + controlled_stopping = !pending_stop_reason_.ok(); + } + if (reset) { + accepted_options.reset(); + submitted_version = 0; + recovery_version = 0; + stop_started.reset(); + first_tick = true; + braking = false; + } + const bool stopping = braking || controlled_stopping || + twistNorm_(target) < config_.stop_twist_norm; + const auto tick = Clock::now(); + if (!stopping) stop_started.reset(); + else if (!stop_started) stop_started = tick; + double dt = first_tick ? config_.control_period_s + : std::chrono::duration(tick - previous_tick).count(); + previous_tick = tick; + first_tick = false; + CartesianVelocityStep planned; + Result status = Result::success(); + bool computation_result = false; + bool planning_result = false; + { + CycleGuard cycle{end_cycle_, status, computation_result}; + const auto emergency_zero = [&] { + computation_result = false; + CMVR_LOG(ERROR) << "[SpeedLExecutor] constrained braking failed; issuing emergency zero" + << " (acceleration/jerk not guaranteed): " << status.message; + const auto zero_result = sendVelocity_(JointVelocityCommand{std::vector(dof_, 0.0)}); + if (!zero_result.ok()) status.message += "; " + zero_result.message; + }; + try { + if (begin_cycle_) { + dt = begin_cycle_(); + cycle.active = true; + } + if (!std::isfinite(dt) || dt <= 0.0) { + status = Result::failure(ArmErrorCode::InvalidArgument, "invalid speedL cycle period"); + } else { + status = readState_(q_now, qd_now); + } + if (status.ok() && reset) { + computation_result = true; + status = planner_->reset(q_now, qd_now); + if (status.ok()) { + std::lock_guard lock(mutex_); + reset_required_ = false; + } + } + if (status.ok() && !braking && !controlled_stopping && submitted_version != version) { + computation_result = true; + status = planner_->submit(target, options, frame); + if (status.ok()) { + submitted_version = version; + accepted_options = options; + } + } + if (status.ok() && !braking) { + computation_result = false; + const double scaling = read_scaling_ ? read_scaling_() : 1.0; + if (!std::isfinite(scaling) || scaling < 0.0 || scaling > 1.0) { + status = Result::failure(ArmErrorCode::InvalidArgument, "invalid speed scaling"); + } else { + computation_result = true; + planned = planner_->step(dt, q_now, qd_now, scaling); + status = planned.status; + if (status.ok() && !planned.stop_reason.ok()) { + std::lock_guard lock(mutex_); + if (pending_stop_reason_.ok()) { + pending_stop_reason_ = planned.stop_reason; + CMVR_LOG(WARNING) << "[SpeedLExecutor] " << pending_stop_reason_.message + << "; waiting for controlled stop"; + } + controlled_stopping = true; + if (!stop_started) stop_started = tick; + } + planning_result = status.code == ArmErrorCode::CommandFailed || + status.code == ArmErrorCode::OutOfJointLimit || + status.code == ArmErrorCode::OutOfVelocityLimit || + status.code == ArmErrorCode::OutOfAccelerationLimit || + status.code == ArmErrorCode::OutOfWorkspace; + if (planning_result && !stop_requested_.load()) { + std::lock_guard lock(mutex_); + if (controlled_stopping || command_version_ == version) { + CMVR_LOG(ERROR) << "[SpeedLExecutor] " << status.message + << "; starting joint braking in the failed cycle"; + recordFailureLocked_(status, true); + braking = true; + if (!stop_started) stop_started = tick; + } + } + } + } + if (braking && (status.ok() || (computation_result && planning_result)) && + !stop_requested_.load()) { + // Use the feedback from this acquired cycle: never release + // the failed cycle while the previous speed is still held. + computation_result = false; + planning_result = false; + planned = planner_->brakeStep(dt, q_now, qd_now); + status = planned.status; + } + if (status.ok() && !stop_requested_.load()) { + computation_result = false; + status = sendVelocity_(planned.joint_velocity); + if (status.ok()) planner_->commitStep(); + } + if ((braking || controlled_stopping) && !status.ok() && + !stop_requested_.load()) emergency_zero(); + } catch (...) { + computation_result = false; + status = callbackException("speedL cycle"); + if ((braking || controlled_stopping) && !stop_requested_.load()) emergency_zero(); + } + } + // A requested hard stop owns subsequent output; its safety rejection + // must not become an unrelated asynchronous motion error. + if (stop_requested_.load()) { + if (!status.ok()) { + std::lock_guard lock(mutex_); + if (status.code == ArmErrorCode::RobotInEmergencyStop || + status.code == ArmErrorCode::RobotInProtectiveStop) { + planning_fault_ = false; + if (!pending_stop_reason_.ok()) recordFailureLocked_(status); + } else { + recordFailureLocked_(status, computation_result && planning_result); + } + } + break; + } + bool finish = false; + const bool stop_timed_out = stop_started && + std::chrono::duration(Clock::now() - *stop_started).count() >= config_.stop_timeout_s; + { + std::lock_guard lock(mutex_); + // A replacement makes an old computation irrelevant, but does + // not repair failed feedback, output, scaling or clock I/O. + const bool external_stop = status.code == ArmErrorCode::RobotInEmergencyStop || + status.code == ArmErrorCode::RobotInProtectiveStop; + const bool applies = braking || controlled_stopping || command_version_ == version || + (!status.ok() && !computation_result); + if (external_stop) { + // Safety flags can be raised before shutdown reaches this + // executor. Their rejection is an intentional hard stop. + planning_fault_ = false; + if (controlled_stopping) recordFailureLocked_(status); + command_active_ = false; + finishing_ = true; + finish = true; + } else if (applies && stop_timed_out) { + recordFailureLocked_(status, computation_result && planning_result); + recordFailureLocked_(Result::failure(ArmErrorCode::Timeout, + "speedL smooth stop timed out")); + command_active_ = false; + finishing_ = true; + finish = true; + } else if (applies && !status.ok()) { + CMVR_LOG(ERROR) << "[SpeedLExecutor] " << status.message; + recordFailureLocked_(status, computation_result && planning_result); + if (!braking && !controlled_stopping && accepted_options && + command_version_ != recovery_version) { + target_options_ = *accepted_options; + setStopTargetLocked_(accepted_options->acceleration); + recovery_version = command_version_; + } else { + command_active_ = false; + finishing_ = true; + finish = true; + } + } else if (applies) { + command_twist_snapshot_ = planned.twist_base; + if (planned.reference.valid) { + planned.reference.command_version = version; + reference_ = planned.reference; + } + if ((stopping || braking || controlled_stopping) && planned.settled && + velocityNorm_(planned.joint_velocity.velocity) < config_.stop_command_velocity_norm && + velocityNorm_(qd_now) < config_.stop_measured_velocity_norm) { + command_active_ = false; + finishing_ = true; + finish = true; + } + } + } + if (finish) { + finishCommand_(); + first_tick = true; + } + if (!begin_cycle_) { + // Never replay late deadlines in a burst. Integrate the measured + // interval on the next cycle instead of using a fictitious clock. + auto deadline = tick + period; + if (Clock::now() >= deadline) deadline = Clock::now() + period; + std::unique_lock lock(mutex_); + cv_.wait_until(lock, deadline, [&] { return stop_requested_.load(); }); + } + } + } catch (...) { + const auto error = callbackException("speedL worker"); + std::lock_guard lock(mutex_); + recordFailureLocked_(error); + } + bool needs_stop; + { + std::lock_guard lock(mutex_); + needs_stop = command_active_ || busy_.load(); + command_active_ = false; + finishing_ = needs_stop; + reset_required_ = true; + } + if (needs_stop) finishCommand_(); +} + +void SpeedLExecutor::setStopTargetLocked_(const double acceleration) +{ + target_twist_ = {}; + target_frame_ = FrameType::Base; + target_options_.acceleration = acceleration; + target_options_.capture_reference = false; + command_active_ = true; + ++command_version_; +} + +void SpeedLExecutor::recordFailureLocked_(const Result& result, const bool planning_failure) +{ + if (result.ok()) return; + if (!pending_stop_reason_.ok()) { + const auto reason = std::exchange(pending_stop_reason_, Result::success()); + recordFailureLocked_(reason, true); + } + planning_fault_ = faulted_.load() ? planning_fault_ && planning_failure : planning_failure; + faulted_.store(true); + if (last_result_.ok()) last_result_ = result; + else if (last_result_.message.find(result.message) == std::string::npos) + last_result_.message += "; " + result.message; +} + +void SpeedLExecutor::finishCommand_() +{ + const auto stopped = finish_(); + std::lock_guard lock(mutex_); + shutdown_result_ = stopped; + if (!pending_stop_reason_.ok()) { + const auto reason = std::exchange(pending_stop_reason_, Result::success()); + recordFailureLocked_(reason, true); + } + recordFailureLocked_(stopped); + reset_required_ = true; + finishing_ = false; + if (stopped.ok()) command_twist_snapshot_ = {}; + busy_.store(!stopped.ok()); +} + +Result SpeedLExecutor::finish_() +{ + JointVelocityCommand zero; + zero.velocity.assign(dof_, 0.0); + auto result = sendVelocity_(zero); + // Simulation must be released before waiting for measured stop, including + // when zero submission failed and needs an explicit later recovery. + if (end_cycle_) { + try { + end_cycle_(true); + } catch (...) { + const auto error = callbackException("finish speedL cycle"); + if (result.ok()) result = error; + else result.message += "; " + error.message; + } + } + if (!result.ok()) return result; + const auto deadline = std::chrono::steady_clock::now() + + std::chrono::duration(config_.stop_timeout_s); + std::vector q, qd; + while (true) { + result = readState_(q, qd); + if (!result.ok()) return result; + if (velocityNorm_(qd) < config_.stop_measured_velocity_norm) return Result::success(); + if (std::chrono::steady_clock::now() >= deadline) { + return Result::failure(ArmErrorCode::Timeout, "speedL zero sent but measured stop was not confirmed"); + } + std::this_thread::sleep_for(std::chrono::duration(config_.control_period_s)); + } +} + +Result SpeedLExecutor::readState_(std::vector& q, std::vector& qd) const +{ + try { + if (!read_state_ || !read_state_(q, qd)) { + return Result::failure(ArmErrorCode::CommandFailed, "speedL read_state failed"); + } + if (q.size() != dof_ || qd.size() != dof_ || + !std::all_of(q.begin(), q.end(), [](double value) { return std::isfinite(value); }) || + !std::all_of(qd.begin(), qd.end(), [](double value) { return std::isfinite(value); })) { + return Result::failure(ArmErrorCode::InvalidArgument, "speedL invalid state feedback"); + } + return Result::success(); + } catch (...) { + return callbackException("speedL read_state"); + } +} + +Result SpeedLExecutor::sendVelocity_(const JointVelocityCommand& velocity) const +{ + try { + if (!send_velocity_) return Result::failure(ArmErrorCode::RobotNotReady, "speedL has no velocity output"); + if (velocity.velocity.size() != dof_ || + !std::all_of(velocity.velocity.begin(), velocity.velocity.end(), + [](double value) { return std::isfinite(value); })) { + return Result::failure(ArmErrorCode::InvalidArgument, "speedL invalid joint velocity command"); + } + return send_velocity_(velocity); + } catch (...) { + return callbackException("speedL send_velocity"); + } +} + +double SpeedLExecutor::velocityNorm_(const std::vector& velocity) +{ + double value = 0.0; + for (const double item : velocity) value = std::hypot(value, item); + return value; +} + +double SpeedLExecutor::twistNorm_(const CartesianVelocity& velocity) +{ + return common::math::velocityToVector(velocity).norm(); +} + +} // namespace cmvr::device diff --git a/cmvr-es/devices/arm/motor_robot_arm/src/speed_l_executor_test.cpp b/cmvr-es/devices/arm/motor_robot_arm/src/speed_l_executor_test.cpp new file mode 100644 index 00000000..c7817af4 --- /dev/null +++ b/cmvr-es/devices/arm/motor_robot_arm/src/speed_l_executor_test.cpp @@ -0,0 +1,1031 @@ +#include +#include "devices/arm/motor_robot_arm/include/speed_l_executor.h" +#include +#include +#include +#include +#include +#include +#include + +namespace cmvr::device { +namespace { +using namespace std::chrono_literals; +class Planner final : public CartesianVelocityPlanner { +public: + bool configureSpeedL(const config::SpeedLPlannerConfig&, std::size_t) override { return true; } + Result reset(const std::vector&, const std::vector& qd) override { + if (!check("reset")) return Result::failure(ArmErrorCode::CommandFailed, "reset failed"); + current = {}; + capture_reference = false; + reset_velocity.store(qd.empty() ? 0.0 : qd.front()); + ++resets; + return Result::success(); + } + Result submit(const CartesianVelocity& target, const SpeedLOptions& options, FrameType) override { + ++submissions; + if (!check("submit")) return Result::failure(ArmErrorCode::CommandFailed, "submit failed"); + if (!accept(target, options)) return Result::failure(ArmErrorCode::InvalidArgument, "limits rejected"); + current = target; + capture_reference = options.capture_reference; + applied_reversal.store(options.continuous_linear_reversal.value_or(false)); + applied_jerk.store(options.linear_jerk.value_or(10.0)); + return Result::success(); + } + CartesianVelocityStep step(double dt, const std::vector&, const std::vector&, + double scaling = 1.0) override { + CartesianVelocityStep result; + last_period.store(dt); + last_scaling.store(scaling); + if (!check("step")) { + result.status = Result::failure(ArmErrorCode::CommandFailed, "step failed"); + return result; + } + if (step_result) return step_result(); + result.status = Result::success(); + result.joint_velocity.velocity = {current.vy * scaling}; + result.twist_base = current; + result.twist_base.vy *= scaling; + result.settled = current.vx == 0 && current.vy == 0 && current.vz == 0 && + current.wx == 0 && current.wy == 0 && current.wz == 0 && + stop_settled.load(); + if (capture_reference) { + result.reference.valid = true; + result.reference.tcp_pose_base.y = .5; + result.reference.target_base.vx = current.vy; + capture_reference = false; + } + return result; + } + CartesianVelocityStep brakeStep(double dt, const std::vector& q, + const std::vector& qd) override { + ++brakes; + if (brake) return brake(dt, q, qd); + CartesianVelocityStep result; + result.status = Result::success(); + result.joint_velocity.velocity = {0}; + result.settled = true; + return result; + } + void commitStep() override { + check("commit"); + ++commits; + } + CartesianVelocity current; + bool capture_reference{false}; + std::atomic applied_jerk{0.0}; + std::atomic applied_reversal{false}; + std::atomic submissions{0}; + std::atomic resets{0}; + std::atomic brakes{0}, commits{0}; + std::atomic reset_velocity{0.0}; + std::atomic last_scaling{1.0}; + std::atomic last_period{0.0}; + std::atomic stop_settled{true}; + std::function check = [](auto) { return true; }; + std::function&, + const std::vector&)> brake; + std::function step_result; + std::function accept = + [](const auto&, const auto&) { return true; }; +}; + +bool waitUntil(const std::function& condition) { + const auto deadline = std::chrono::steady_clock::now() + 1s; + while (!condition() && std::chrono::steady_clock::now() < deadline) + std::this_thread::sleep_for(1ms); + return condition(); +} +TEST(SpeedLExecutor, ZeroVelocityDoesNotFinishAnUnsettledStop) { + std::mutex mutex; + std::condition_variable cv; + bool forward_sent = false, second_stop_step = false, release = false; + int stop_steps = 0; + auto planner = std::make_shared(); + planner->stop_settled = false; + planner->check = [&](std::string_view operation) { + if (operation == "step" && planner->current.vy == 0) { + std::unique_lock lock(mutex); + if (++stop_steps == 2) { + second_stop_step = true; + cv.notify_all(); + cv.wait_for(lock, 2s, [&] { return release; }); + } + } + return true; + }; + SpeedLExecutor executor({}, planner, 1, + [](auto& q, auto& qd) { q = {0}; qd = {0}; return true; }, + [&](const JointVelocityCommand& command) { + std::lock_guard lock(mutex); + forward_sent |= command.velocity[0] > 0; + cv.notify_all(); + return Result::success(); + }); + CartesianVelocity target; + target.vy = .08; + ASSERT_TRUE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + { + std::unique_lock lock(mutex); + ASSERT_TRUE(cv.wait_for(lock, 1s, [&] { return forward_sent; })); + } + ASSERT_TRUE(executor.stop().ok()); + { + std::unique_lock lock(mutex); + // Both commanded and measured velocities were zero on the first stop step. + ASSERT_TRUE(cv.wait_for(lock, 1s, [&] { return second_stop_step; })); + EXPECT_TRUE(executor.busy()); + EXPECT_EQ(executor.clearPlanningFault().code, ArmErrorCode::RobotNotReady); + planner->stop_settled = true; + release = true; + cv.notify_all(); + } + const auto deadline = std::chrono::steady_clock::now() + 1s; + while (executor.busy() && std::chrono::steady_clock::now() < deadline) + std::this_thread::sleep_for(1ms); + EXPECT_FALSE(executor.busy()); + executor.shutdown(); +} +TEST(SpeedLExecutor, CompletedStopCannotClearNewReversal) { + std::mutex mutex; + std::condition_variable cv; + bool forward_sent = false, block_zero = false, zero_entered = false; + bool release_zero = false, reverse_sent = false; + auto planner = std::make_shared(); + SpeedLExecutor executor({}, planner, 1, + [](auto& q, auto& qd) { q = {0}; qd = {0}; return true; }, + [&](const JointVelocityCommand& command) { + std::unique_lock lock(mutex); + forward_sent |= command.velocity[0] > 0; + reverse_sent |= command.velocity[0] < 0; + if (command.velocity[0] == 0 && block_zero && !zero_entered) { + zero_entered = true; cv.notify_all(); + cv.wait_for(lock, 2s, [&] { return release_zero; }); + } + cv.notify_all(); return Result::success(); + }); + CartesianVelocity v; v.vy = .08; + SpeedLOptions options; + options.acceleration = 3; + ASSERT_TRUE(executor.speedL(v, options, 0, FrameType::Base).ok()); + { + std::unique_lock lock(mutex); + ASSERT_TRUE(cv.wait_for(lock, 1s, [&] { return forward_sent; })); + block_zero = true; + } + ASSERT_TRUE(executor.stop(3).ok()); + { + std::unique_lock lock(mutex); + ASSERT_TRUE(cv.wait_for(lock, 1s, [&] { return zero_entered; })); + } + v.vy = -.08; + ASSERT_TRUE(executor.speedL(v, options, 0, FrameType::Base).ok()); + { + std::unique_lock lock(mutex); + release_zero = true; cv.notify_all(); + EXPECT_TRUE(cv.wait_for(lock, 1s, [&] { return reverse_sent; })); + } + EXPECT_TRUE(executor.busy()); + executor.shutdown(); +} +TEST(SpeedLExecutor, PublishesReferenceAfterSendAndKeepsCommandLimits) { + std::mutex mutex; + std::condition_variable cv; + bool entered = false, release = false; + auto planner = std::make_shared(); + SpeedLExecutor executor({}, planner, 1, + [](auto& q, auto& qd) { q = {0}; qd = {0}; return true; }, + [&](const JointVelocityCommand&) { + std::unique_lock lock(mutex); + if (!entered) { + entered = true; cv.notify_all(); + cv.wait_for(lock, 2s, [&] { return release; }); + } + return Result::success(); + }); + CartesianVelocity v; v.vy = -.08; + SpeedLOptions options; + options.acceleration = 3; + options.linear_jerk = 60; + options.continuous_linear_reversal = true; + options.capture_reference = true; + ASSERT_TRUE(executor.speedL(v, options, 0, FrameType::Tool).ok()); + { + std::unique_lock lock(mutex); + ASSERT_TRUE(cv.wait_for(lock, 1s, [&] { return entered; })); + EXPECT_FALSE(executor.getReference().valid); + release = true; cv.notify_all(); + } + const auto deadline = std::chrono::steady_clock::now() + 1s; + while (!executor.getReference().valid && std::chrono::steady_clock::now() < deadline) + std::this_thread::sleep_for(1ms); + const auto ref = executor.getReference(); + EXPECT_TRUE(ref.valid); + EXPECT_GT(ref.command_version, 0U); + EXPECT_DOUBLE_EQ(ref.tcp_pose_base.y, .5); + EXPECT_DOUBLE_EQ(ref.target_base.vx, -.08); + EXPECT_DOUBLE_EQ(planner->applied_jerk.load(), 60); + EXPECT_TRUE(planner->applied_reversal.load()); + executor.shutdown(); +} +TEST(SpeedLExecutor, RejectsInvalidMotionLimitsBeforeStarting) { + auto planner = std::make_shared(); + SpeedLExecutor executor({}, planner, 1, + [](auto&, auto&) { return false; }, + [](const auto&) { return Result::success(); }); + SpeedLOptions options; + options.linear_jerk = std::numeric_limits::quiet_NaN(); + EXPECT_FALSE(executor.speedL({}, options, 0, FrameType::Base).ok()); + options.linear_jerk = -1; + EXPECT_FALSE(executor.speedL({}, options, 0, FrameType::Base).ok()); + EXPECT_FALSE(executor.busy()); +} + +TEST(SpeedLExecutor, FailedOldCommandCannotClearNewCommand) { + // A superseded computation may be discarded. Actual I/O failures must + // remain visible even if a newer command arrived while I/O was pending. + for (const auto stage : {"submit", "step"}) { + SCOPED_TRACE(stage); + std::mutex mutex; + std::condition_variable cv; + bool entered = false, release = false, reverse_sent = false; + auto gate = [&](std::string_view operation) { + std::unique_lock lock(mutex); + if (operation != stage || entered) return true; + entered = true; + cv.notify_all(); + cv.wait_for(lock, 2s, [&] { return release; }); + return false; + }; + auto planner = std::make_shared(); + planner->check = gate; + SpeedLExecutor executor({}, planner, 1, + [&](auto& q, auto& qd) { q = {0}; qd = {0}; return gate("read"); }, + [&](const JointVelocityCommand& command) { + if (!gate("send")) return Result::failure(ArmErrorCode::CommandFailed, "injected failure"); + std::lock_guard lock(mutex); + reverse_sent |= command.velocity[0] < 0; + cv.notify_all(); + return Result::success(); + }); + CartesianVelocity target; + target.vy = .08; + SpeedLOptions options; + options.capture_reference = true; + ASSERT_TRUE(executor.speedL(target, options, 0, FrameType::Base).ok()); + { + std::unique_lock lock(mutex); + ASSERT_TRUE(cv.wait_for(lock, 1s, [&] { return entered; })); + } + target.vy = -.08; + SpeedLOptions reverse_options; + reverse_options.acceleration = 3; + ASSERT_TRUE(executor.speedL(target, reverse_options, 0, FrameType::Base).ok()); + { + std::unique_lock lock(mutex); + release = true; + cv.notify_all(); + EXPECT_TRUE(cv.wait_for(lock, 1s, [&] { return reverse_sent; })); + } + EXPECT_TRUE(executor.busy()); + executor.shutdown(); + } +} + +TEST(SpeedLExecutor, TimedCommandStopsAndIdleStopDoesNotRestartWorker) { + auto planner = std::make_shared(); + SpeedLExecutor executor({}, planner, 1, + [](auto& q, auto& qd) { q = {0}; qd = {0}; return true; }, + [](const auto&) { return Result::success(); }); + CartesianVelocity target; + target.vy = .08; + SpeedLOptions options; + options.acceleration = 3; + ASSERT_TRUE(executor.speedL(target, options, .05, FrameType::Base).ok()); + const auto deadline = std::chrono::steady_clock::now() + 1s; + while (executor.busy() && std::chrono::steady_clock::now() < deadline) + std::this_thread::sleep_for(1ms); + ASSERT_FALSE(executor.busy()); + EXPECT_DOUBLE_EQ(executor.getCommandTwistBase().vy, 0); + EXPECT_EQ(planner->submissions.load(), 2); // start and timed stop, not every cycle + ASSERT_TRUE(executor.stop().ok()); + EXPECT_FALSE(executor.busy()); + EXPECT_EQ(planner->submissions.load(), 2); + // A completed command leaves a reusable worker; shutdown may start a new one. + executor.shutdown(); + ASSERT_TRUE(executor.speedL(target, options, .05, FrameType::Base).ok()); + executor.shutdown(); + EXPECT_FALSE(executor.busy()); +} + +TEST(SpeedLExecutor, RejectedLimitsStopWithLastAcceptedOptionsAndRetryOnlyOnce) { + for (bool rejected_stop : {false, true}) { + for (bool recovery_fails : {false, true}) { + SCOPED_TRACE(::testing::Message() << "rejected_stop=" << rejected_stop + << " recovery_fails=" << recovery_fails); + std::mutex mutex; + std::condition_variable cv; + bool forward_sent = false; + std::vector targets; + std::vector requests; + auto planner = std::make_shared(); + planner->accept = [&](const CartesianVelocity& target, const SpeedLOptions& options) { + std::lock_guard lock(mutex); + targets.push_back(target); + requests.push_back(options); + return options.linear_jerk != .01 && !(recovery_fails && target.vy == 0); + }; + SpeedLExecutor executor({}, planner, 1, + [](auto& q, auto& qd) { q = {0}; qd = {0}; return true; }, + [&](const JointVelocityCommand& command) { + std::lock_guard lock(mutex); + forward_sent |= command.velocity[0] > 0; + cv.notify_all(); + return Result::success(); + }); + CartesianVelocity target; + target.vy = .08; + SpeedLOptions accepted; + accepted.acceleration = 3; + accepted.linear_jerk = 10; + accepted.continuous_linear_reversal = true; + ASSERT_TRUE(executor.speedL(target, accepted, 0, FrameType::Base).ok()); + { + std::unique_lock lock(mutex); + ASSERT_TRUE(cv.wait_for(lock, 1s, [&] { return forward_sent; })); + } + SpeedLOptions rejected = accepted; + rejected.acceleration = .1; + rejected.linear_jerk = .01; + rejected.continuous_linear_reversal = false; + rejected.capture_reference = true; + target.vy = rejected_stop ? 0 : -.08; + ASSERT_TRUE(executor.speedL(target, rejected, 0, FrameType::Base).ok()); + const auto deadline = std::chrono::steady_clock::now() + 1s; + while (executor.busy() && std::chrono::steady_clock::now() < deadline) + std::this_thread::sleep_for(1ms); + ASSERT_FALSE(executor.busy()); + EXPECT_TRUE(executor.faulted()); + EXPECT_FALSE(executor.lastResult().ok()); + { + std::lock_guard lock(mutex); + ASSERT_EQ(requests.size(), 3U); // accepted, rejected, one recovery stop + EXPECT_DOUBLE_EQ(targets.back().vy, 0); + EXPECT_DOUBLE_EQ(requests.back().acceleration, accepted.acceleration); + EXPECT_EQ(requests.back().linear_jerk, accepted.linear_jerk); + EXPECT_EQ(requests.back().continuous_linear_reversal, accepted.continuous_linear_reversal); + EXPECT_FALSE(requests.back().capture_reference); + } + executor.shutdown(); + } + } +} + +TEST(SpeedLExecutor, FailedIoLatchesFaultEvenWhenNewerCommandIsQueued) { + for (const auto stage : {"read", "send"}) { + SCOPED_TRACE(stage); + std::mutex mutex; + std::condition_variable cv; + bool entered = false, release = false, reverse_sent = false; + const auto gate = [&](std::string_view operation) { + std::unique_lock lock(mutex); + if (operation != stage || entered) return true; + entered = true; + cv.notify_all(); + cv.wait_for(lock, 2s, [&] { return release; }); + return false; + }; + auto planner = std::make_shared(); + SpeedLExecutor executor({}, planner, 1, + [&](auto& q, auto& qd) { q = {0}; qd = {0}; return gate("read"); }, + [&](const JointVelocityCommand& command) { + if (!gate("send")) + return Result::failure(ArmErrorCode::CommandFailed, "injected bus failure"); + std::lock_guard lock(mutex); + reverse_sent |= command.velocity[0] < 0; + return Result::success(); + }); + CartesianVelocity target; + target.vy = .08; + ASSERT_TRUE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + { + std::unique_lock lock(mutex); + ASSERT_TRUE(cv.wait_for(lock, 1s, [&] { return entered; })); + } + target.vy = -.08; + ASSERT_TRUE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + { + std::lock_guard lock(mutex); + release = true; + cv.notify_all(); + } + ASSERT_TRUE(waitUntil([&] { return executor.faulted() && !executor.busy(); })); + EXPECT_FALSE(executor.lastResult().ok()); + EXPECT_FALSE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + { + std::lock_guard lock(mutex); + EXPECT_FALSE(reverse_sent); + } + executor.shutdown(); + EXPECT_TRUE(executor.faulted()); // Joining the worker does not acknowledge a fault. + EXPECT_EQ(executor.clearPlanningFault().code, ArmErrorCode::RobotInFault); + EXPECT_TRUE(executor.clearFault().ok()); + EXPECT_FALSE(executor.faulted()); + } +} + +TEST(SpeedLExecutor, FailedFinalZeroStaysBusyUntilFeedbackConfirmsStop) { + auto planner = std::make_shared(); + std::atomic forward_sent{false}, allow_zero{false}; + std::atomic zero_attempts{0}; + std::atomic measured_speed{0}; + SpeedLExecutor::Config config; + config.stop_timeout_s = .03; + SpeedLExecutor executor(config, planner, 1, + [&](auto& q, auto& qd) { q = {0}; qd = {measured_speed.load()}; return true; }, + [&](const JointVelocityCommand& command) { + if (command.velocity[0] != 0) forward_sent.store(true); + // The planned stop succeeds; only the final confirmation write fails. + if (command.velocity[0] == 0 && ++zero_attempts > 1 && !allow_zero.load()) + return Result::failure(ArmErrorCode::CommandFailed, "final zero rejected"); + return Result::success(); + }); + CartesianVelocity target; + target.vy = .08; + ASSERT_TRUE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + ASSERT_TRUE(waitUntil([&] { return forward_sent.load(); })); + ASSERT_TRUE(executor.stop().ok()); + ASSERT_TRUE(waitUntil([&] { return executor.faulted(); })); + EXPECT_TRUE(executor.busy()); + EXPECT_FALSE(executor.lastResult().ok()); + EXPECT_FALSE(executor.shutdown().ok()); + EXPECT_TRUE(executor.busy()); + EXPECT_FALSE(executor.clearFault().ok()); + allow_zero.store(true); + measured_speed.store(.03); + EXPECT_FALSE(executor.clearFault().ok()); + EXPECT_TRUE(executor.faulted()); + EXPECT_TRUE(executor.busy()); + measured_speed.store(0); + EXPECT_TRUE(executor.clearFault().ok()); + EXPECT_FALSE(executor.faulted()); + EXPECT_FALSE(executor.busy()); + EXPECT_TRUE(executor.lastResult().ok()); +} + +TEST(SpeedLExecutor, RestartResetsFromFeedbackAndScalingDoesNotResubmit) { + auto planner = std::make_shared(); + std::atomic scaling{1}, measured_speed{.02}; + SpeedLExecutor executor({}, planner, 1, + [&](auto& q, auto& qd) { q = {0}; qd = {measured_speed.load()}; return true; }, + [&](const auto& command) { + if (command.velocity[0] == 0) measured_speed.store(0); + return Result::success(); + }, [&] { return scaling.load(); }); + CartesianVelocity target; + target.vy = .08; + SpeedLOptions options; + options.capture_reference = true; + ASSERT_TRUE(executor.speedL(target, options, 0, FrameType::Tool).ok()); + ASSERT_TRUE(waitUntil([&] { return executor.getReference().valid; })); + EXPECT_EQ(planner->resets.load(), 1); + EXPECT_DOUBLE_EQ(planner->reset_velocity.load(), .02); + const auto reference = executor.getReference(); + for (double factor : {.5, 0.0, 1.0}) { + scaling.store(factor); + ASSERT_TRUE(waitUntil([&] { return planner->last_scaling.load() == factor; })); + EXPECT_TRUE(executor.busy()); + EXPECT_EQ(planner->submissions.load(), 1); + EXPECT_EQ(planner->resets.load(), 1); + EXPECT_EQ(executor.getReference().command_version, reference.command_version); + EXPECT_DOUBLE_EQ(executor.getReference().target_base.vx, reference.target_base.vx); + } + ASSERT_TRUE(executor.shutdown().ok()); + measured_speed.store(.004); + ASSERT_TRUE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + ASSERT_TRUE(waitUntil([&] { return planner->resets.load() == 2; })); + EXPECT_DOUBLE_EQ(planner->reset_velocity.load(), .004); + EXPECT_TRUE(executor.shutdown().ok()); +} + +TEST(SpeedLExecutor, DelayedCycleDoesNotBurstCatchUpCommands) { + auto planner = std::make_shared(); + int steps = 0; + planner->check = [&](std::string_view operation) { + if (operation == "step" && ++steps == 2) std::this_thread::sleep_for(40ms); + return true; + }; + std::mutex mutex; + std::condition_variable cv; + std::vector sends; + SpeedLExecutor::Config config; + config.control_period_s = .01; + SpeedLExecutor executor(config, planner, 1, + [](auto& q, auto& qd) { q = {0}; qd = {0}; return true; }, + [&](const JointVelocityCommand& command) { + if (command.velocity[0] > 0) { + std::lock_guard lock(mutex); + sends.push_back(std::chrono::steady_clock::now()); + cv.notify_all(); + } + return Result::success(); + }); + CartesianVelocity target; + target.vy = .08; + ASSERT_TRUE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + { + std::unique_lock lock(mutex); + ASSERT_TRUE(cv.wait_for(lock, 1s, [&] { return sends.size() >= 5; })); + for (std::size_t i = 2; i < 5; ++i) + EXPECT_GE(std::chrono::duration(sends[i] - sends[i - 1]).count(), .005); + } + EXPECT_TRUE(executor.shutdown().ok()); +} + +TEST(SpeedLExecutor, ExternalClockIsReleasedOnStopShutdownAndPlanningFailure) { + for (const auto ending : {"stop", "shutdown", "failure"}) { + SCOPED_TRACE(ending); + auto planner = std::make_shared(); + std::atomic fail{false}; + planner->check = [&](std::string_view operation) { return operation != "step" || !fail.load(); }; + std::atomic continued_cycles{0}, finished_cycles{0}; + SpeedLExecutor executor({}, planner, 1, + [](auto& q, auto& qd) { q = {0}; qd = {0}; return true; }, + [](const auto&) { return Result::success(); }, {}, + [] { std::this_thread::sleep_for(2ms); return .002; }, + [&](bool finished) { if (finished) ++finished_cycles; else ++continued_cycles; }); + CartesianVelocity target; + target.vy = .08; + ASSERT_TRUE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + ASSERT_TRUE(waitUntil([&] { return continued_cycles.load() >= 2; })); + EXPECT_DOUBLE_EQ(planner->last_period.load(), .002); + if (std::string_view(ending) == "failure") fail.store(true); + else if (std::string_view(ending) == "stop") EXPECT_TRUE(executor.stop().ok()); + else EXPECT_TRUE(executor.shutdown().ok()); + ASSERT_TRUE(waitUntil([&] { return finished_cycles.load() > 0; })); + EXPECT_TRUE(waitUntil([&] { return !executor.busy(); })); + if (std::string_view(ending) == "failure") EXPECT_TRUE(executor.faulted()); + executor.shutdown(); + } +} + +TEST(SpeedLExecutor, FailedCycleBrakesBeforeReleaseAndKeepsOriginalFaultUntilStopped) { + auto planner = std::make_shared(); + std::mutex mutex; + std::condition_variable cv; + std::vector failure_cycle; + bool release = false, second_brake_entered = false; + std::atomic cycle{0}, first_brake_cycle{0}; + double measured = .03, sent = .03; + planner->check = [&](std::string_view operation) { + std::lock_guard lock(mutex); + if (operation == "step") { + first_brake_cycle.store(cycle.load()); + failure_cycle.emplace_back("failed step"); + return false; + } + if (operation == "commit" && cycle == first_brake_cycle) + failure_cycle.emplace_back("commit"); + return true; + }; + planner->brake = [&](double, const auto&, const auto& qd) { + std::unique_lock lock(mutex); + if (planner->brakes == 1) failure_cycle.emplace_back("brake"); + if (planner->brakes == 2) { + second_brake_entered = true; + cv.notify_all(); + cv.wait_for(lock, 2s, [&] { return release; }); + } + CartesianVelocityStep result; + result.status = Result::success(); + const double next = std::max(0.0, qd.front() - .01); + result.joint_velocity.velocity = {next}; + result.settled = next == 0; + return result; + }; + SpeedLExecutor executor({}, planner, 1, + [&](auto& q, auto& qd) { + std::lock_guard lock(mutex); + q = {0}; qd = {measured}; return true; + }, + [&](const JointVelocityCommand& command) { + std::lock_guard lock(mutex); + sent = command.velocity.front(); + if (cycle == first_brake_cycle) failure_cycle.emplace_back("send brake"); + return Result::success(); + }, {}, + [&] { ++cycle; return .001; }, + [&](bool finished) { + std::lock_guard lock(mutex); + if (!finished && cycle == first_brake_cycle) failure_cycle.emplace_back("release"); + measured = sent; + }); + CartesianVelocity target; + target.vy = .08; + ASSERT_TRUE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + { + std::unique_lock lock(mutex); + ASSERT_TRUE(cv.wait_for(lock, 1s, [&] { return second_brake_entered; })); + EXPECT_EQ(failure_cycle, (std::vector{ + "failed step", "brake", "send brake", "commit", "release"})); + EXPECT_TRUE(executor.busy()); + EXPECT_TRUE(executor.faulted()); + EXPECT_EQ(executor.lastResult().message, "step failed"); + EXPECT_EQ(executor.speedL(target, {}, 0, FrameType::Base).code, ArmErrorCode::RobotInFault); + EXPECT_TRUE(executor.stop().ok()); // Keep braking; do not replace the failed command. + release = true; + cv.notify_all(); + } + ASSERT_TRUE(waitUntil([&] { return !executor.busy(); })); + EXPECT_EQ(planner->submissions, 1); // Braking never resubmits a Cartesian zero target. + EXPECT_GE(planner->brakes, 3); + EXPECT_EQ(planner->commits, planner->brakes); + EXPECT_EQ(executor.lastResult().message, "step failed"); + EXPECT_TRUE(executor.clearPlanningFault().ok()); + EXPECT_TRUE(executor.shutdown().ok()); +} + +TEST(SpeedLExecutor, FailedBrakeOrBrakeOutputSendsEmergencyZeroWithoutCommitting) { + for (const bool fail_output : {false, true}) { + SCOPED_TRACE(fail_output); + auto planner = std::make_shared(); + planner->check = [](std::string_view operation) { return operation != "step"; }; + planner->brake = [&](double, const auto&, const auto&) { + CartesianVelocityStep result; + result.status = fail_output ? Result::success() + : Result::failure(ArmErrorCode::OutOfJointLimit, "braking distance exhausted"); + result.joint_velocity.velocity = {.02}; + return result; + }; + std::atomic zero_sends{0}, releases{0}; + std::atomic zero_before_release{false}; + SpeedLExecutor executor({}, planner, 1, + [](auto& q, auto& qd) { q = {0}; qd = {0}; return true; }, + [&](const JointVelocityCommand& command) { + if (command.velocity.front() != 0) + return Result::failure(ArmErrorCode::CommandFailed, "brake send rejected"); + ++zero_sends; + if (releases == 0) zero_before_release = true; + return Result::success(); + }, {}, [] { return .001; }, [&](bool) { ++releases; }); + CartesianVelocity target; + target.vy = .08; + ASSERT_TRUE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + ASSERT_TRUE(waitUntil([&] { return executor.faulted() && !executor.busy(); })); + EXPECT_TRUE(zero_before_release); + EXPECT_GE(zero_sends, 2); // Emergency output, then final stop confirmation. + EXPECT_EQ(planner->commits, 0); + EXPECT_EQ(planner->brakes, 1); + EXPECT_NE(executor.lastResult().message.find("step failed"), std::string::npos); + EXPECT_NE(executor.lastResult().message.find( + fail_output ? "brake send rejected" : "braking distance exhausted"), std::string::npos); + EXPECT_EQ(executor.clearPlanningFault().code, ArmErrorCode::RobotInFault); + EXPECT_TRUE(executor.shutdown().ok()); + } +} + +TEST(SpeedLExecutor, UnsettledSmoothStopTimesOutAndConfirmsFinalZero) { + auto planner = std::make_shared(); + planner->stop_settled = false; + std::atomic forward_sent{false}; + std::atomic zero_sends{0}; + SpeedLExecutor::Config config; + config.stop_timeout_s = .03; + SpeedLExecutor executor(config, planner, 1, + [](auto& q, auto& qd) { q = {0}; qd = {0}; return true; }, + [&](const JointVelocityCommand& command) { + if (command.velocity[0] > 0) forward_sent.store(true); + else if (command.velocity[0] == 0) ++zero_sends; + return Result::success(); + }); + CartesianVelocity target; + target.vy = .08; + ASSERT_TRUE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + ASSERT_TRUE(waitUntil([&] { return forward_sent.load(); })); + ASSERT_TRUE(executor.stop().ok()); + ASSERT_TRUE(waitUntil([&] { return executor.faulted() && !executor.busy(); })); + EXPECT_EQ(executor.lastResult().code, ArmErrorCode::Timeout); + EXPECT_FALSE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + EXPECT_GT(zero_sends.load(), 1); // Smooth-stop samples plus the final zero. + EXPECT_DOUBLE_EQ(executor.getCommandTwistBase().vy, 0); + EXPECT_TRUE(executor.shutdown().ok()); + EXPECT_TRUE(executor.faulted()); + EXPECT_EQ(executor.clearPlanningFault().code, ArmErrorCode::RobotInFault); +} + +TEST(SpeedLExecutor, ControlledStopReportsReasonOnlyAfterMeasuredStop) { + auto planner = std::make_shared(); + std::atomic steps{0}; + std::atomic measured_velocity{.03}; + planner->step_result = [&] { + CartesianVelocityStep result; + result.status = Result::success(); + result.stop_reason = Result::failure(ArmErrorCode::OutOfVelocityLimit, + "adaptive speed below minimum ratio"); + result.settled = ++steps > 1; + result.joint_velocity.velocity = {result.settled ? 0.0 : .02}; + return result; + }; + SpeedLExecutor executor({}, planner, 1, + [&](auto& q, auto& qd) { q = {0}; qd = {measured_velocity.load()}; return true; }, + [](const auto&) { return Result::success(); }); + CartesianVelocity target; + target.vy = .04; + ASSERT_TRUE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + ASSERT_TRUE(waitUntil([&] { return planner->commits >= 3; })); + EXPECT_TRUE(executor.busy()); + EXPECT_FALSE(executor.faulted()); + EXPECT_TRUE(executor.lastResult().ok()); + EXPECT_TRUE(executor.stop().ok()); + EXPECT_TRUE(executor.stop().ok()); + EXPECT_EQ(executor.speedL(target, {}, 0, FrameType::Base).code, ArmErrorCode::RobotNotReady); + EXPECT_EQ(executor.speedL({}, {}, 0, FrameType::Base).code, ArmErrorCode::RobotNotReady); + EXPECT_EQ(planner->submissions, 1); + EXPECT_EQ(planner->brakes, 0); + measured_velocity = 0; + ASSERT_TRUE(waitUntil([&] { return executor.faulted() && !executor.busy(); })); + EXPECT_EQ(executor.lastResult().code, ArmErrorCode::OutOfVelocityLimit); + EXPECT_EQ(executor.lastResult().message, "adaptive speed below minimum ratio"); + EXPECT_TRUE(executor.clearPlanningFault().ok()); + EXPECT_TRUE(executor.shutdown().ok()); +} + +TEST(SpeedLExecutor, ControlledStopCannotBeCancelledByConcurrentReplacement) { + auto planner = std::make_shared(); + std::mutex mutex; + std::condition_variable cv; + bool entered = false, release = false; + std::atomic measured_velocity{.03}; + planner->step_result = [&] { + std::unique_lock lock(mutex); + if (!entered) { + entered = true; + cv.notify_all(); + cv.wait_for(lock, 2s, [&] { return release; }); + } + CartesianVelocityStep result; + result.status = Result::success(); + result.stop_reason = Result::failure(ArmErrorCode::OutOfVelocityLimit, "low speed stop"); + result.joint_velocity.velocity = {0}; + result.settled = true; + return result; + }; + SpeedLExecutor executor({}, planner, 1, + [&](auto& q, auto& qd) { q = {0}; qd = {measured_velocity.load()}; return true; }, + [](const auto&) { return Result::success(); }); + CartesianVelocity target; + target.vy = .04; + ASSERT_TRUE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + { + std::unique_lock lock(mutex); + ASSERT_TRUE(cv.wait_for(lock, 1s, [&] { return entered; })); + } + target.vy = -.04; + ASSERT_TRUE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + { + std::lock_guard lock(mutex); + release = true; + cv.notify_all(); + } + ASSERT_TRUE(waitUntil([&] { return planner->commits >= 3; })); + EXPECT_EQ(planner->submissions, 1); + EXPECT_TRUE(executor.busy()); + EXPECT_TRUE(executor.lastResult().ok()); + EXPECT_EQ(executor.speedL(target, {}, 0, FrameType::Base).code, ArmErrorCode::RobotNotReady); + measured_velocity = 0; + ASSERT_TRUE(waitUntil([&] { return executor.faulted() && !executor.busy(); })); + EXPECT_EQ(executor.lastResult().message, "low speed stop"); + EXPECT_TRUE(executor.shutdown().ok()); +} + +TEST(SpeedLExecutor, ControlledStopPreservesReasonWhenLaterPlanningOrOutputFails) { + for (const bool fail_output : {false, true}) { + SCOPED_TRACE(fail_output); + auto planner = std::make_shared(); + int steps = 0; + std::atomic releases{0}, sends{0}; + std::atomic zero_before_failed_release{false}; + planner->step_result = [&] { + CartesianVelocityStep result; + if (++steps == 2 && !fail_output) { + result.status = Result::failure(ArmErrorCode::CommandFailed, "stop planning failed"); + return result; + } + result.status = Result::success(); + result.stop_reason = Result::failure(ArmErrorCode::OutOfVelocityLimit, "low speed stop"); + result.joint_velocity.velocity = {.02}; + return result; + }; + SpeedLExecutor executor({}, planner, 1, + [](auto& q, auto& qd) { q = {0}; qd = {0}; return true; }, + [&](const JointVelocityCommand& command) { + if (++sends == 2 && fail_output) + return Result::failure(ArmErrorCode::CommandFailed, "stop output failed"); + if (command.velocity[0] == 0 && releases == 1) zero_before_failed_release = true; + return Result::success(); + }, {}, [] { return .001; }, [&](bool finished) { if (!finished) ++releases; }); + CartesianVelocity target; + target.vy = .04; + ASSERT_TRUE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + ASSERT_TRUE(waitUntil([&] { return executor.faulted() && !executor.busy(); })); + EXPECT_EQ(executor.lastResult().code, ArmErrorCode::OutOfVelocityLimit); + EXPECT_NE(executor.lastResult().message.find("low speed stop"), std::string::npos); + EXPECT_NE(executor.lastResult().message.find( + fail_output ? "stop output failed" : "stop planning failed"), std::string::npos); + EXPECT_TRUE(zero_before_failed_release); + EXPECT_EQ(planner->brakes, fail_output ? 0 : 1); + EXPECT_EQ(planner->commits, fail_output ? 1 : 2); + const auto recovery = executor.clearPlanningFault(); + if (fail_output) EXPECT_EQ(recovery.code, ArmErrorCode::RobotInFault); + else EXPECT_TRUE(recovery.ok()); + EXPECT_TRUE(executor.shutdown().ok()); + } +} + +TEST(SpeedLExecutor, ControlledStopTimeoutPreservesReasonAndRequiresExplicitRecovery) { + auto planner = std::make_shared(); + planner->step_result = [] { + CartesianVelocityStep result; + result.status = Result::success(); + result.stop_reason = Result::failure(ArmErrorCode::OutOfVelocityLimit, "low speed stop"); + result.joint_velocity.velocity = {0}; + result.settled = false; + return result; + }; + SpeedLExecutor::Config config; + config.stop_timeout_s = .015; + SpeedLExecutor executor(config, planner, 1, + [](auto& q, auto& qd) { q = {0}; qd = {0}; return true; }, + [](const auto&) { return Result::success(); }); + CartesianVelocity target; + target.vy = .04; + ASSERT_TRUE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + ASSERT_TRUE(waitUntil([&] { return executor.faulted() && !executor.busy(); })); + EXPECT_NE(executor.lastResult().message.find("low speed stop"), std::string::npos); + EXPECT_NE(executor.lastResult().message.find("timed out"), std::string::npos); + EXPECT_EQ(executor.clearPlanningFault().code, ArmErrorCode::RobotInFault); + EXPECT_TRUE(executor.shutdown().ok()); +} + +TEST(SpeedLExecutor, PlanningFaultRecoveryConfirmsStopAndResetsNextCommand) { + auto planner = std::make_shared(); + std::atomic reject_step{true}, forward_sent{false}; + std::atomic measured_velocity{0}; + std::atomic zero_sends{0}; + planner->check = [&](std::string_view operation) { + return operation != "step" || !reject_step.load(); + }; + SpeedLExecutor executor({}, planner, 1, + [&](auto& q, auto& qd) { q = {0}; qd = {measured_velocity.load()}; return true; }, + [&](const JointVelocityCommand& command) { + if (command.velocity[0] == 0) ++zero_sends; + else forward_sent.store(true); + return Result::success(); + }); + CartesianVelocity target; + target.vy = .08; + ASSERT_TRUE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + ASSERT_TRUE(waitUntil([&] { return executor.faulted() && !executor.busy(); })); + EXPECT_EQ(executor.lastResult().message, "step failed"); + EXPECT_FALSE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + const int zeros_before_clear = zero_sends.load(); + executor.recordStopFailure(Result::success()); + ASSERT_TRUE(executor.clearPlanningFault().ok()); + EXPECT_GT(zero_sends.load(), zeros_before_clear); + EXPECT_FALSE(executor.faulted()); + EXPECT_TRUE(executor.lastResult().ok()); + EXPECT_EQ(planner->resets.load(), 1); + + reject_step.store(false); + measured_velocity.store(.004); + ASSERT_TRUE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + ASSERT_TRUE(waitUntil([&] { return forward_sent.load(); })); + EXPECT_EQ(planner->resets.load(), 2); + EXPECT_DOUBLE_EQ(planner->reset_velocity.load(), .004); + EXPECT_EQ(executor.clearPlanningFault().code, ArmErrorCode::RobotNotReady); + EXPECT_TRUE(executor.busy()); + EXPECT_TRUE(executor.shutdown().ok()); +} + +TEST(SpeedLExecutor, MixedPlanningAndIoFailuresRemainIneligibleAfterSuccessfulStop) { + for (const auto stage : {"read", "send", "end", "measured_stop", "external_stop"}) { + SCOPED_TRACE(stage); + auto planner = std::make_shared(); + std::atomic failed_step{false}, inject{true}; + planner->check = [&](std::string_view operation) { + if (operation == "step" && inject.load()) { + failed_step.store(true); + return false; + } + return true; + }; + const auto failing = [&](std::string_view operation) { + return operation == stage && failed_step.load() && inject.load(); + }; + SpeedLExecutor::Config config; + config.stop_timeout_s = .015; + SpeedLExecutor executor(config, planner, 1, + [&](auto& q, auto& qd) { + q = {0}; qd = {failing("measured_stop") ? .1 : 0}; + return !failing("read"); + }, + [&](const JointVelocityCommand&) { + return failing("send") ? Result::failure(ArmErrorCode::CommandFailed, "bus failed") + : Result::success(); + }, {}, [] { return .001; }, + [&](bool finished) { + if (!finished && failing("end")) throw std::runtime_error("cycle failed"); + }); + CartesianVelocity target; + target.vy = .08; + ASSERT_TRUE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + ASSERT_TRUE(waitUntil([&] { return executor.faulted(); })); + // Reap the worker while injections remain active, so stop I/O and + // feedback failures have been recorded before testing recovery. + executor.shutdown(); + if (std::string_view(stage) == "external_stop") { + executor.recordStopFailure(Result::failure(ArmErrorCode::CommandRejected, "stopJ failed")); + EXPECT_NE(executor.lastResult().message.find("stopJ failed"), std::string::npos); + } + EXPECT_EQ(executor.lastResult().code, ArmErrorCode::CommandFailed); + EXPECT_NE(executor.lastResult().message.find("step failed"), std::string::npos); + inject.store(false); + EXPECT_TRUE(executor.shutdown().ok()); + EXPECT_FALSE(executor.busy()); + EXPECT_EQ(executor.clearPlanningFault().code, ArmErrorCode::RobotInFault); + EXPECT_TRUE(executor.faulted()); + EXPECT_NE(executor.lastResult().message.find("step failed"), std::string::npos); + EXPECT_TRUE(executor.clearFault().ok()); + } +} + +TEST(SpeedLExecutor, ExceptionsAndInvalidPlannerStateRequireExplicitRecovery) { + for (const auto stage : {"reset", "submit", "step_exception", "scaling", "period"}) { + SCOPED_TRACE(stage); + auto planner = std::make_shared(); + std::atomic inject{true}; + planner->check = [&](std::string_view operation) { + if (!inject.load()) return true; + if (operation == "step" && std::string_view(stage) == "step_exception") + throw std::runtime_error("planner exception"); + return operation != stage; + }; + SpeedLExecutor executor({}, planner, 1, + [](auto& q, auto& qd) { q = {0}; qd = {0}; return true; }, + [](const auto&) { return Result::success(); }, + [&] { + if (inject.load() && std::string_view(stage) == "scaling") + throw std::runtime_error("scaling exception"); + return 1.0; + }, + [&] { return inject.load() && std::string_view(stage) == "period" ? 0.0 : .001; }, + [](bool) {}); + CartesianVelocity target; + target.vy = .08; + ASSERT_TRUE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + ASSERT_TRUE(waitUntil([&] { return executor.faulted() && !executor.busy(); })); + inject.store(false); + EXPECT_TRUE(executor.shutdown().ok()); + EXPECT_EQ(executor.clearPlanningFault().code, ArmErrorCode::RobotInFault); + EXPECT_TRUE(executor.faulted()); + EXPECT_TRUE(executor.clearFault().ok()); + } +} + +TEST(SpeedLExecutor, FailedRecoveryConfirmationPermanentlyRevokesAutomaticEligibility) { + for (const auto stage : {"read", "send", "end", "measured_stop"}) { + SCOPED_TRACE(stage); + auto planner = std::make_shared(); + planner->check = [](std::string_view operation) { return operation != "step"; }; + std::atomic inject{false}; + const auto failing = [&](std::string_view operation) { return inject.load() && operation == stage; }; + SpeedLExecutor::Config config; + config.stop_timeout_s = .015; + SpeedLExecutor executor(config, planner, 1, + [&](auto& q, auto& qd) { + q = {0}; qd = {failing("measured_stop") ? .1 : 0}; + return !failing("read"); + }, + [&](const auto&) { + return failing("send") ? Result::failure(ArmErrorCode::CommandFailed, "zero failed") + : Result::success(); + }, {}, [] { return .001; }, + [&](bool finished) { + if (finished && failing("end")) throw std::runtime_error("finish failed"); + }); + CartesianVelocity target; + target.vy = .08; + ASSERT_TRUE(executor.speedL(target, {}, 0, FrameType::Base).ok()); + ASSERT_TRUE(waitUntil([&] { return executor.faulted() && !executor.busy(); })); + inject.store(true); + EXPECT_FALSE(executor.clearPlanningFault().ok()); + EXPECT_TRUE(executor.faulted()); + EXPECT_TRUE(executor.busy()); + inject.store(false); + EXPECT_TRUE(executor.shutdown().ok()); + EXPECT_EQ(executor.clearPlanningFault().code, ArmErrorCode::RobotInFault); + EXPECT_TRUE(executor.clearFault().ok()); + } +} +} +} diff --git a/cmvr-es/devices/arm/motor_robot_arm/src/speedl_reversal_mujoco_test.cpp b/cmvr-es/devices/arm/motor_robot_arm/src/speedl_reversal_mujoco_test.cpp index abc459b5..c8259510 100644 --- a/cmvr-es/devices/arm/motor_robot_arm/src/speedl_reversal_mujoco_test.cpp +++ b/cmvr-es/devices/arm/motor_robot_arm/src/speedl_reversal_mujoco_test.cpp @@ -1,4 +1,5 @@ #include "arm/motor_robot_arm/include/motor_robot_arm.h" +#include "common/config/config_files.h" #include "common/io/proto_file_io.h" #include "devices/motor/manager/include/motor_manager.h" #include "simulate/mujoco/mujoco_world/include/mujoco_world.h" @@ -91,6 +92,7 @@ int main(int argc, char** argv) { const auto world = world_device.world(); const int site = mj_name2id(world->model(), mjOBJ_SITE, "R_FINGER_TIP_SITE"); if (site < 0) throw std::runtime_error("TCP site not found"); + ConfigHelper::setConfigRootFromFile((root / "cmvr-es/config/cmvr_es.pb.txt").string()); auto arms = readConfig(root / "cmvr-es/config/devices/arm/arm_mujoco.pb.txt"); auto ac = arms.arm().robot_arms(0); ac.mutable_kinematics()->mutable_pinocchio_dls_ik_solver()->set_urdf_path( @@ -172,6 +174,8 @@ int main(int argc, char** argv) { require(arm.stopL(3.0)); const auto stop_deadline = Clock::now() + std::chrono::seconds(3); while (arm.busy() && Clock::now() < stop_deadline) std::this_thread::sleep_for(std::chrono::milliseconds(5)); + const bool stopped = !arm.busy(); + const double stopped_tcp_speed = sample(world, site).velocity.norm(); std::cout << std::fixed << std::setprecision(3) << "REVERSAL legacy=" << legacy << " approach_ms=" << approach_ms << " frame=" << (tool_frame ? "Tool" : "Base") @@ -184,7 +188,55 @@ int main(int argc, char** argv) { << " actual_vy_at_reverse=" << origin.velocity.dot(axis) << " max_forward_mm=" << peak * 1000 << " peak_at_ms=" << peak_ms << " actual_reverse_ms=" << reverse_ms << " return_to_origin_ms=" << return_ms - << " remained_active=" << active << " reference_valid=" << reference_valid << " csv=" << csv_path << '\n'; + << " remained_active=" << active << " reference_valid=" << reference_valid + << " stopped=" << stopped << " stopped_tcp_speed_m_s=" << stopped_tcp_speed + << " csv=" << csv_path << '\n'; + if (!stopped || stopped_tcp_speed >= .01) throw std::runtime_error("speedL did not stop cleanly"); + + CartesianPose move_l_target = arm.getTcpPose(); + move_l_target.x += .02; + MotionOptions cartesian_move; + cartesian_move.velocity = .05; + cartesian_move.acceleration = .5; + cartesian_move.jerk = 10.0; + require(arm.moveL(move_l_target, cartesian_move, FrameType::Base)); + double move_l_error = 0.0; + const auto settle_deadline = Clock::now() + std::chrono::seconds(2); + do { + const auto reached = arm.getTcpPose(); + move_l_error = Eigen::Vector3d(reached.x - move_l_target.x, + reached.y - move_l_target.y, reached.z - move_l_target.z).norm(); + if (move_l_error < .003) break; + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } while (Clock::now() < settle_deadline); + if (!std::isfinite(move_l_error) || move_l_error >= .003) { + throw std::runtime_error("moveL after speedL missed its target"); + } + + const double restart_y = sample(world, site).position.y(); + CartesianVelocity restart_velocity; + restart_velocity.vy = .02; + require(arm.speedL(restart_velocity, .5, 0.0, FrameType::Base)); + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + const double restart_command = arm.getSpeedLCommandTwistBase().vy; + const double restart_displacement = sample(world, site).position.y() - restart_y; + require(arm.stopL(.5)); + const auto restart_stop_deadline = Clock::now() + std::chrono::seconds(3); + while (arm.busy() && Clock::now() < restart_stop_deadline) { + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + const double restart_stop_speed = sample(world, site).velocity.norm(); + std::cout << "MODE_SWITCH moveL_error_mm=" << move_l_error * 1000 + << " resumed_command_vy_m_s=" << restart_command + << " resumed_displacement_y_mm=" << restart_displacement * 1000 + << " stopped=" << !arm.busy() + << " stopped_tcp_speed_m_s=" << restart_stop_speed << '\n'; + if (restart_command <= .01 || restart_displacement <= .001 || + arm.busy() || restart_stop_speed >= .01) { + throw std::runtime_error("speedL did not resume and stop after moveL"); + } + // The idle velocity worker must not overwrite the next position command. + require(arm.moveJ(JointPositionCommand{{.25, 1.0, M_PI/2, M_PI/2, -M_PI/2, 0, 0}}, move)); arm.stop(); manager->stop(); world_device.stop(); diff --git a/cmvr-es/devices/arm/robot_arm.h b/cmvr-es/devices/arm/robot_arm.h index bc5c3efa..b51e7d5a 100644 --- a/cmvr-es/devices/arm/robot_arm.h +++ b/cmvr-es/devices/arm/robot_arm.h @@ -106,15 +106,32 @@ public: return speedL(velocity, options.acceleration, duration, frame); } virtual SpeedLReference getSpeedLReference() const { return {}; } + // Submission success and the asynchronous execution result are distinct. + virtual Result getSpeedLResult() const { + return Result::failure(ArmErrorCode::UnsupportedCommand, "speedL result is unavailable"); + } virtual Result stopMotion() = 0; virtual Result moveP(const CartesianPose& target, const MotionOptions& options, FrameType frame = FrameType::Base) { + if (options.is_tcp_pose_valid) { + return Result::failure( + ArmErrorCode::UnsupportedCommand, + "MoveP TCP pose constraints are not supported by this robot arm"); + } return moveL(target, options, frame); } + // Plan to the exact joint configuration without converting through FK/IK. + virtual Result moveP(const JointPositionCommand& target, + const MotionOptions& options) + { + return Result::failure(ArmErrorCode::UnsupportedCommand, + "joint-target MoveP is not supported by this robot arm"); + } + virtual Result startServoMode(const ServoOptions& options) = 0; virtual Result servoJ(const JointPositionCommand& target) = 0; virtual Result servoL(const CartesianPose& target, @@ -132,6 +149,12 @@ public: virtual Result brakeRelease() = 0; virtual Result shutdown() = 0; virtual Result clearFault() = 0; + // Only backends that can distinguish planning faults may recover them automatically. + virtual Result recoverSpeedLPlanningFault() { + return isFault() + ? Result::failure(ArmErrorCode::RobotInFault, "arm fault requires explicit recovery") + : Result::success(); + } virtual Result unlockProtectiveStop() = 0; virtual Result loadProgram(const std::string& program_name) = 0; virtual Result playProgram() = 0; diff --git a/cmvr-es/devices/camera/mujoco_camera/include/mujoco_camera.h b/cmvr-es/devices/camera/mujoco_camera/include/mujoco_camera.h index 26911c5c..95a522dc 100644 --- a/cmvr-es/devices/camera/mujoco_camera/include/mujoco_camera.h +++ b/cmvr-es/devices/camera/mujoco_camera/include/mujoco_camera.h @@ -4,6 +4,7 @@ #pragma once +#include #include #include #include @@ -53,9 +54,16 @@ public: void getRGBDImages(cv::Mat& color, cv::Mat& depth, Rs2Intrinsics& intrinsics) override; bool startStreaming() override; void stopStreaming() override; + void getEncodedFrame(StreamFrameData& frame_data, size_t& index) override; + bool waitEncodedFrame(StreamFrameData& frame_data, + size_t& index, + std::chrono::milliseconds timeout) override; bool getLatestEncodedFrame(StreamFrameData& frame_data, size_t& next_index) override; + bool requestKeyFrame() override; private: + bool startImpl_(); + bool stopImpl_(); bool fetch(cv::Mat& color, cv::Mat& depth, Rs2Intrinsics& intrinsics); void fillIntrinsics(int width, int height, Rs2Intrinsics& intrinsics) const; bool initOffscreen_(); @@ -79,11 +87,19 @@ private: cv::Mat depth; Rs2Intrinsics intrinsics{}; uint64_t frame_id{0}; + uint64_t capture_sequence{0}; + int64_t capture_monotonic_ns{0}; + int64_t capture_utc_ns{0}; bool valid{false}; }; + bool encodeCachedFrame_(const CachedFrame& captured, + StreamFrameData& frame_data, + size_t& next_index); + private: FetchRgbdFn fetch_rgbd_fn_; + std::mutex lifecycle_mtx_; mutable std::mutex mtx_; config::MujocoCameraConfig config_; std::weak_ptr world_; @@ -108,12 +124,19 @@ private: uint64_t last_frame_id_{0}; bool has_last_frame_id_{false}; size_t stream_frame_index_{0}; - bool streaming_{false}; + std::atomic streaming_{false}; + std::mutex stream_mtx_; + size_t streaming_refs_{0}; + uint64_t stream_epoch_{0}; + bool force_key_frame_{false}; + std::atomic encoded_capture_sequence_{0}; + StreamFrameData latest_encoded_frame_; std::shared_ptr rgb_encoder_; mutable std::mutex cache_mtx_; std::condition_variable cache_cv_; CachedFrame latest_frame_; + uint64_t capture_sequence_{0}; std::thread render_thread_; bool render_thread_running_{false}; bool render_stop_requested_{false}; diff --git a/cmvr-es/devices/camera/mujoco_camera/src/mujoco_camera.cpp b/cmvr-es/devices/camera/mujoco_camera/src/mujoco_camera.cpp index a540531f..bd81124b 100644 --- a/cmvr-es/devices/camera/mujoco_camera/src/mujoco_camera.cpp +++ b/cmvr-es/devices/camera/mujoco_camera/src/mujoco_camera.cpp @@ -133,6 +133,12 @@ bool MujocoCamera::init() } bool MujocoCamera::start() +{ + std::lock_guard lock(lifecycle_mtx_); + return startImpl_(); +} + +bool MujocoCamera::startImpl_() { bool initialized = false; { @@ -207,7 +213,7 @@ bool MujocoCamera::start() const bool has_frame = latest_frame_.valid; cache_lock.unlock(); if (!ready || !has_frame) { - stop(); + stopImpl_(); if (ready) { setError_("[MujocoCamera] render thread stopped before producing a frame"); } else { @@ -219,6 +225,12 @@ bool MujocoCamera::start() } bool MujocoCamera::stop() +{ + std::lock_guard lock(lifecycle_mtx_); + return stopImpl_(); +} + +bool MujocoCamera::stopImpl_() { { std::lock_guard lock(cache_mtx_); @@ -237,6 +249,15 @@ bool MujocoCamera::stop() thread_to_join.join(); } + { + std::lock_guard lock(stream_mtx_); + streaming_.store(false); + streaming_refs_ = 0; + force_key_frame_ = false; + encoded_capture_sequence_.store(0); + latest_encoded_frame_ = StreamFrameData{}; + rgb_encoder_.reset(); + } { std::lock_guard lock(cache_mtx_); render_thread_running_ = false; @@ -248,13 +269,14 @@ bool MujocoCamera::stop() void MujocoCamera::setFetchRgbdFn(FetchRgbdFn fetch_rgbd_fn) { + std::lock_guard lifecycle_lock(lifecycle_mtx_); bool render_thread_active = false; { std::lock_guard lock(cache_mtx_); render_thread_active = render_thread_running_; } if (render_thread_active) { - stop(); + stopImpl_(); } std::lock_guard lock(mtx_); @@ -307,37 +329,144 @@ void MujocoCamera::getRGBDImages(cv::Mat& color, cv::Mat& depth, Rs2Intrinsics& bool MujocoCamera::startStreaming() { - if (!start()) { + std::lock_guard lifecycle_lock(lifecycle_mtx_); + if (!startImpl_()) { return false; } - std::lock_guard lock(mtx_); - streaming_ = true; - state_.is_streaming = true; + { + std::lock_guard lock(stream_mtx_); + if (streaming_refs_++ == 0) { + ++stream_epoch_; + force_key_frame_ = false; + encoded_capture_sequence_.store(0); + latest_encoded_frame_ = StreamFrameData{}; + rgb_encoder_.reset(); + } + streaming_.store(true); + std::lock_guard state_lock(mtx_); + state_.is_streaming = true; + } + cache_cv_.notify_all(); return true; } void MujocoCamera::stopStreaming() { - std::lock_guard lock(mtx_); - streaming_ = false; - state_.is_streaming = false; - stream_frame_index_ = 0; - rgb_encoder_.reset(); + { + std::lock_guard lock(stream_mtx_); + if (streaming_refs_ == 0 || --streaming_refs_ != 0) { + return; + } + streaming_.store(false); + force_key_frame_ = false; + encoded_capture_sequence_.store(0); + latest_encoded_frame_ = StreamFrameData{}; + rgb_encoder_.reset(); + std::lock_guard state_lock(mtx_); + state_.is_streaming = false; + } + cache_cv_.notify_all(); +} + +void MujocoCamera::getEncodedFrame(StreamFrameData& frame_data, size_t& index) +{ + (void)waitEncodedFrame(frame_data, index, std::chrono::milliseconds::zero()); +} + +bool MujocoCamera::waitEncodedFrame(StreamFrameData& frame_data, + size_t& index, + const std::chrono::milliseconds timeout) +{ + const auto deadline = std::chrono::steady_clock::now() + + std::max(timeout, std::chrono::milliseconds::zero()); + uint64_t last_attempted_capture = 0; + + while (true) { + uint64_t encoded_capture = 0; + { + std::lock_guard lock(stream_mtx_); + if (!streaming_.load()) { + return false; + } + if (latest_encoded_frame_.sequence > index) { + frame_data = latest_encoded_frame_; + index = static_cast(frame_data.sequence); + return true; + } + encoded_capture = encoded_capture_sequence_.load(); + } + + CachedFrame captured; + { + std::unique_lock lock(cache_mtx_); + const uint64_t min_capture = std::max(encoded_capture, last_attempted_capture); + const bool ready = cache_cv_.wait_until(lock, deadline, [&] { + return !streaming_.load() || render_stop_requested_ || !render_thread_running_ || + (latest_frame_.valid && latest_frame_.capture_sequence > min_capture); + }); + if (!ready || !streaming_.load() || render_stop_requested_ || + !render_thread_running_ || !latest_frame_.valid) { + return false; + } + captured = latest_frame_; + } + + StreamFrameData encoded; + size_t next_index = index; + if (encodeCachedFrame_(captured, encoded, next_index) && next_index > index) { + frame_data = std::move(encoded); + index = next_index; + return true; + } + last_attempted_capture = std::max(last_attempted_capture, captured.capture_sequence); + if (std::chrono::steady_clock::now() >= deadline) { + return false; + } + } } bool MujocoCamera::getLatestEncodedFrame(StreamFrameData& frame_data, size_t& next_index) { - if (!streaming_) { + CachedFrame captured; + { + std::lock_guard lock(cache_mtx_); + if (!latest_frame_.valid || latest_frame_.color.empty()) { + return false; + } + captured = latest_frame_; + } + return encodeCachedFrame_(captured, frame_data, next_index); +} + +bool MujocoCamera::requestKeyFrame() +{ + std::lock_guard lock(stream_mtx_); + if (!streaming_.load()) { return false; } + force_key_frame_ = true; + return true; +} + +bool MujocoCamera::encodeCachedFrame_(const CachedFrame& captured, + StreamFrameData& frame_data, + size_t& next_index) +{ + std::lock_guard lock(stream_mtx_); + if (!streaming_.load() || !captured.valid || captured.color.empty()) { + return false; + } + if (latest_encoded_frame_.sequence != 0 && + captured.capture_sequence <= encoded_capture_sequence_.load()) { + frame_data = latest_encoded_frame_; + next_index = static_cast(frame_data.sequence); + return true; + } - cv::Mat color; - cv::Mat depth; - Rs2Intrinsics intrinsics{}; - if (!fetch(color, depth, intrinsics) || color.empty()) { - return false; - } + const cv::Mat& color = captured.color; + const cv::Mat& depth = captured.depth; + const Rs2Intrinsics& intrinsics = captured.intrinsics; cv::Mat color_to_encode = color; if (encode_width_ > 0 && encode_height_ > 0 && @@ -350,33 +479,59 @@ bool MujocoCamera::getLatestEncodedFrame(StreamFrameData& frame_data, size_t& ne return false; } - frame_data.rgbImage = color.clone(); - frame_data.intrinsics = intrinsics; + StreamFrameData encoded; + // Published capture buffers are immutable. Keep a reference instead of + // copying full-resolution images for every encoded RGB frame. + encoded.rgbImage = color; + encoded.intrinsics = intrinsics; CameraStreamEncodeOptions encode_options; encode_options.draw_timestamp = enable_stream_timestamp_; encode_options.overlay = streamOverlay(); const Rs2Intrinsics encode_intrinsics = scaleIntrinsics( intrinsics, color.cols, color.rows, color_to_encode.cols, color_to_encode.rows); - if (!CameraStreamEncoder::encode(rgb_encoder_, - color_to_encode, - frame_data.rgbFrame, - frame_data.bKey, - encode_intrinsics, - encode_options)) { + rgb_encoder_->frame->pict_type = force_key_frame_ + ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_NONE; + const bool encoded_ok = CameraStreamEncoder::encode(rgb_encoder_, + color_to_encode, + encoded.rgbFrame, + encoded.bKey, + encode_intrinsics, + encode_options); + rgb_encoder_->frame->pict_type = AV_PICTURE_TYPE_NONE; + if (!encoded_ok) { return false; } + if (encoded.bKey) { + force_key_frame_ = false; + } if (!depth.empty()) { - frame_data.depthImage = depth.clone(); + encoded.depthImage = depth; const auto* depth_begin = reinterpret_cast(depth.data); const auto* depth_end = depth_begin + depth.total() * depth.elemSize(); - frame_data.depthFrame.assign(depth_begin, depth_end); + encoded.depthFrame.assign(depth_begin, depth_end); + encoded.depth_width = depth.cols; + encoded.depth_height = depth.rows; } - frame_data.width = color_to_encode.cols; - frame_data.height = color_to_encode.rows; - frame_data.fps = fps; - frame_data.codec = codec_; - frame_data.depthKey = true; - next_index = ++stream_frame_index_; + encoded.width = color_to_encode.cols; + encoded.height = color_to_encode.rows; + encoded.fps = fps; + encoded.codec = codec_; + encoded.depthKey = !depth.empty(); + encoded.stream_epoch = stream_epoch_; + encoded.sequence = ++stream_frame_index_; + encoded.source_frame_number = captured.frame_id; + encoded.capture_monotonic_ns = captured.capture_monotonic_ns; + encoded.capture_utc_ns = captured.capture_utc_ns; + encoded.pts = rgb_encoder_->frame_pts - 1; + encoded.dts = encoded.pts; + encoded.time_base_num = 1; + encoded.time_base_den = fps; + encoded.duration = 1; + + encoded_capture_sequence_.store(captured.capture_sequence); + latest_encoded_frame_ = std::move(encoded); + frame_data = latest_encoded_frame_; + next_index = static_cast(frame_data.sequence); return true; } @@ -598,21 +753,37 @@ void MujocoCamera::renderLoop_() } if (got_frame) { + const auto captured_at = std::chrono::steady_clock::now(); + const auto captured_utc = std::chrono::system_clock::now(); + bool published_frame = false; { std::lock_guard lock(cache_mtx_); - latest_frame_.color = std::move(color); - latest_frame_.depth = std::move(depth); - latest_frame_.intrinsics = intrinsics; - latest_frame_.frame_id = use_external_frames && external_frame_id != 0 - ? external_frame_id - : latest_frame_.frame_id + 1; - latest_frame_.valid = true; + if (!use_external_frames || external_frame_id == 0 || + !latest_frame_.valid || latest_frame_.frame_id != external_frame_id) { + latest_frame_.color = std::move(color); + latest_frame_.depth = std::move(depth); + latest_frame_.intrinsics = intrinsics; + latest_frame_.frame_id = use_external_frames && external_frame_id != 0 + ? external_frame_id + : latest_frame_.frame_id + 1; + latest_frame_.capture_sequence = ++capture_sequence_; + latest_frame_.capture_monotonic_ns = + std::chrono::duration_cast( + captured_at.time_since_epoch()).count(); + latest_frame_.capture_utc_ns = + std::chrono::duration_cast( + captured_utc.time_since_epoch()).count(); + latest_frame_.valid = true; + published_frame = true; + } } { std::lock_guard lock(mtx_); clear_error_(); } - cache_cv_.notify_all(); + if (published_frame) { + cache_cv_.notify_all(); + } } next_tick += period_ticks; @@ -623,7 +794,9 @@ void MujocoCamera::renderLoop_() const auto now = std::chrono::steady_clock::now(); if (next_tick < now) { - next_tick = now + period_ticks; + // The previous capture already ran past its deadline. Retry on + // the next loop rather than adding a second frame period of idle. + next_tick = now; } } diff --git a/cmvr-es/devices/camera/mujoco_camera/src/mujoco_camera_test.cpp b/cmvr-es/devices/camera/mujoco_camera/src/mujoco_camera_test.cpp index 67a6c083..1aa6feac 100644 --- a/cmvr-es/devices/camera/mujoco_camera/src/mujoco_camera_test.cpp +++ b/cmvr-es/devices/camera/mujoco_camera/src/mujoco_camera_test.cpp @@ -1,10 +1,156 @@ #include +#include +#include +#include +#include + #include "devices/camera/mujoco_camera/include/mujoco_camera.h" #include "simulate/mujoco/mujoco_world/include/mujoco_world.h" namespace { +bool beginsWithAnnexBStartCode(const std::vector& bytes) +{ + return bytes.size() >= 4 && bytes[0] == 0 && bytes[1] == 0 && + (bytes[2] == 1 || (bytes[2] == 0 && bytes[3] == 1)); +} + +bool containsH264IdrNal(const std::vector& bytes) +{ + for (size_t i = 0; i + 4 < bytes.size(); ++i) { + if (bytes[i] != 0 || bytes[i + 1] != 0) { + continue; + } + const size_t start_code_size = bytes[i + 2] == 1 ? 3 : + (bytes[i + 2] == 0 && bytes[i + 3] == 1 ? 4 : 0); + if (start_code_size != 0 && i + start_code_size < bytes.size() && + (bytes[i + start_code_size] & 0x1f) == 5) { + return true; + } + } + return false; +} + +TEST(MujocoCameraTest, WaitEncodedFramePublishesEachExternalFrameOncePerSubscriber) +{ + constexpr int kWidth = 64; + constexpr int kHeight = 48; + std::atomic available_frame_id{1}; + + cmvr::config::MujocoCameraConfig config; + config.set_id("mujoco_external_stream_test_cam"); + auto* render = config.mutable_render(); + render->set_width(kWidth); + render->set_height(kHeight); + render->set_fps(30); + render->set_stream_mode(cmvr::config::STREAM_MODE_RGBD); + auto* encoder = config.mutable_encoder(); + encoder->set_width(kWidth); + encoder->set_height(kHeight); + encoder->set_fps(30); + encoder->set_codec("H264"); + // The deployed external camera permits repeated reads of its last raw + // image. Encoded subscribers must still advance only on a new frame ID. + config.set_consume_new_frame_only(false); + + cmvr::device::MujocoCamera camera(config); + camera.setFetchRgbdFn([&](std::vector& rgb, + std::vector& depth, + int& width, + int& height, + uint64_t& frame_id) { + frame_id = available_frame_id.load(); + if (frame_id == 0) { + return false; + } + width = kWidth; + height = kHeight; + rgb.assign(kWidth * kHeight * 3, static_cast(frame_id * 40)); + depth.assign(kWidth * kHeight, static_cast(frame_id)); + return true; + }); + + cmvr::device::AbstractCamera* base = &camera; + ASSERT_TRUE(camera.init()); + ASSERT_TRUE(base->startStreaming()); + + size_t first_cursor = 0; + cmvr::device::StreamFrameData first; + ASSERT_TRUE(base->waitEncodedFrame(first, first_cursor, std::chrono::seconds(2))); + EXPECT_EQ(first_cursor, 1U); + EXPECT_EQ(first.sequence, 1U); + EXPECT_EQ(first.codec, "H264"); + EXPECT_EQ(first.width, kWidth); + EXPECT_EQ(first.height, kHeight); + EXPECT_TRUE(first.bKey); + EXPECT_TRUE(beginsWithAnnexBStartCode(first.rgbFrame)); + EXPECT_TRUE(containsH264IdrNal(first.rgbFrame)); + + // Each subscriber owns a cursor; reading once must not consume the frame + // for another subscriber, or run the encoder again for the same image. + size_t second_cursor = 0; + cmvr::device::StreamFrameData same_first; + ASSERT_TRUE(base->waitEncodedFrame(same_first, second_cursor, std::chrono::milliseconds(100))); + EXPECT_EQ(second_cursor, first_cursor); + EXPECT_EQ(same_first.sequence, first.sequence); + EXPECT_EQ(same_first.rgbFrame, first.rgbFrame); + + size_t latest_cursor = 0; + cmvr::device::StreamFrameData latest; + ASSERT_TRUE(base->getLatestEncodedFrame(latest, latest_cursor)); + EXPECT_EQ(latest_cursor, first_cursor); + EXPECT_EQ(latest.sequence, first.sequence); + EXPECT_EQ(latest.rgbFrame, first.rgbFrame); + + // Releasing one of two stream leases must not stop the other subscriber. + ASSERT_TRUE(base->startStreaming()); + base->stopStreaming(); + + cmvr::device::StreamFrameData repeated; + EXPECT_FALSE(base->waitEncodedFrame(repeated, first_cursor, std::chrono::milliseconds(150))); + EXPECT_EQ(first_cursor, 1U); + + available_frame_id.store(2); + cmvr::device::StreamFrameData second; + ASSERT_TRUE(base->waitEncodedFrame(second, first_cursor, std::chrono::seconds(2))); + EXPECT_EQ(first_cursor, 2U); + EXPECT_EQ(second.sequence, first.sequence + 1); + EXPECT_FALSE(second.rgbFrame.empty()); + EXPECT_EQ(second.rgbImage.at(0, 0), cv::Vec3b(80, 80, 80)); + + cmvr::device::StreamFrameData same_second; + ASSERT_TRUE(base->waitEncodedFrame(same_second, second_cursor, std::chrono::milliseconds(100))); + EXPECT_EQ(second_cursor, first_cursor); + EXPECT_EQ(same_second.sequence, second.sequence); + EXPECT_EQ(same_second.rgbFrame, second.rgbFrame); + + // The gRPC stream requests an IDR after dropping its pending frames. + // The next captured image must recover decoder continuity immediately. + ASSERT_TRUE(base->requestKeyFrame()); + available_frame_id.store(3); + cmvr::device::StreamFrameData recovered; + ASSERT_TRUE(base->waitEncodedFrame(recovered, first_cursor, std::chrono::seconds(2))); + EXPECT_TRUE(recovered.bKey); + EXPECT_TRUE(containsH264IdrNal(recovered.rgbFrame)); + EXPECT_EQ(recovered.sequence, second.sequence + 1); + + // Keep the caller's cursor across a streaming restart. The new epoch must + // begin with a decodable key frame and a strictly newer sequence. + base->stopStreaming(); + ASSERT_TRUE(base->startStreaming()); + cmvr::device::StreamFrameData restarted; + ASSERT_TRUE(base->waitEncodedFrame(restarted, first_cursor, std::chrono::seconds(2))); + EXPECT_GT(first_cursor, second_cursor); + EXPECT_GT(restarted.sequence, second.sequence); + EXPECT_GT(restarted.stream_epoch, second.stream_epoch); + EXPECT_TRUE(restarted.bKey); + EXPECT_TRUE(beginsWithAnnexBStartCode(restarted.rgbFrame)); + + base->stopStreaming(); + EXPECT_TRUE(camera.stop()); +} + TEST(MujocoCameraTest, CapturesOffscreenRgbdFrame) { cmvr::config::MujocoWorldConfig world_config; diff --git a/cmvr-es/devices/motor/drivers/ethercat_motor/include/cia402/cia402_protocol.h b/cmvr-es/devices/motor/drivers/ethercat_motor/include/cia402/cia402_protocol.h index f0903a91..c62e3f7c 100644 --- a/cmvr-es/devices/motor/drivers/ethercat_motor/include/cia402/cia402_protocol.h +++ b/cmvr-es/devices/motor/drivers/ethercat_motor/include/cia402/cia402_protocol.h @@ -30,6 +30,11 @@ public: double qd{0.0}; }; + struct CyclicVelocityCommand { + std::uint8_t node_id{0}; + double target_qd{0.0}; + }; + explicit Cia402Protocol(std::shared_ptr bus_runtime, const config::Cia402ProtocolConfig& config); ~Cia402Protocol() override; @@ -55,6 +60,8 @@ public: double target_qd) override; bool commandCyclicPositionsAtomic(const CyclicPositionCommand* commands, std::size_t count); + bool commandCyclicVelocitiesAtomic(const CyclicVelocityCommand* commands, + std::size_t count); bool readFeedbacksAtomic(MotorFeedback* feedbacks, std::size_t count) const; bool commandCyclicVelocity(std::uint8_t node_id, double target_qd) override; @@ -140,8 +147,8 @@ private: std::unique_ptr status_monitor_; config::Cia402ProtocolConfig config_; std::unordered_map nodes_; - std::mutex cyclic_position_mutex_; - std::vector cyclic_position_writes_; + std::mutex cyclic_command_mutex_; + std::vector cyclic_command_writes_; }; } // namespace cmvr::device diff --git a/cmvr-es/devices/motor/drivers/ethercat_motor/include/vendor/eyou/eyou_motor.h b/cmvr-es/devices/motor/drivers/ethercat_motor/include/vendor/eyou/eyou_motor.h index 4bdc2154..04f0b03a 100644 --- a/cmvr-es/devices/motor/drivers/ethercat_motor/include/vendor/eyou/eyou_motor.h +++ b/cmvr-es/devices/motor/drivers/ethercat_motor/include/vendor/eyou/eyou_motor.h @@ -33,6 +33,9 @@ public: const std::vector>& motors, std::vector& positions, std::vector& velocities); + static bool commandCyclicVelocitiesAtomic( + const std::vector>& motors, + const std::vector& velocities); private: bool hasDependencies_() const; diff --git a/cmvr-es/devices/motor/drivers/ethercat_motor/src/cia402/cia402_protocol.cpp b/cmvr-es/devices/motor/drivers/ethercat_motor/src/cia402/cia402_protocol.cpp index a621ddda..f47a0351 100644 --- a/cmvr-es/devices/motor/drivers/ethercat_motor/src/cia402/cia402_protocol.cpp +++ b/cmvr-es/devices/motor/drivers/ethercat_motor/src/cia402/cia402_protocol.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include @@ -20,7 +21,7 @@ Cia402Protocol::Cia402Protocol(std::shared_ptr bus_runt config_(config) { comm_proto = CommProto::ETHERCAT; - cyclic_position_writes_.reserve(512); + cyclic_command_writes_.reserve(512); status_monitor_ = std::make_unique( bus_runtime_, std::chrono::milliseconds(config_.status_poll_period_ms())); } @@ -104,9 +105,9 @@ bool Cia402Protocol::commandCyclicPositionsAtomic( return false; } - std::lock_guard lock(cyclic_position_mutex_); - cyclic_position_writes_.clear(); - cyclic_position_writes_.reserve(count * 2); + std::lock_guard lock(cyclic_command_mutex_); + cyclic_command_writes_.clear(); + cyclic_command_writes_.reserve(count * 2); for (std::size_t i = 0; i < count; ++i) { const auto& command = commands[i]; @@ -122,13 +123,13 @@ bool Cia402Protocol::commandCyclicPositionsAtomic( } } - cyclic_position_writes_.push_back( + cyclic_command_writes_.push_back( EthercatMotorBusRuntime::makePdoWrite( command.node_id, msgs::CIA402_TARGET_POSITION_607A, 0x00, radToCounts_(command.target_q, *state))); - cyclic_position_writes_.push_back( + cyclic_command_writes_.push_back( EthercatMotorBusRuntime::makePdoWrite( command.node_id, msgs::CIA402_TARGET_VELOCITY_60FF, @@ -136,8 +137,8 @@ bool Cia402Protocol::commandCyclicPositionsAtomic( radPerSecToCounts_(command.target_qd, *state))); } - if (!bus_runtime_->writePdosAtomic(cyclic_position_writes_.data(), - cyclic_position_writes_.size())) { + if (!bus_runtime_->writePdosAtomic(cyclic_command_writes_.data(), + cyclic_command_writes_.size())) { return false; } @@ -191,16 +192,58 @@ bool Cia402Protocol::readFeedbacksAtomic(MotorFeedback* feedbacks, return true; } +bool Cia402Protocol::commandCyclicVelocitiesAtomic( + const CyclicVelocityCommand* commands, + const std::size_t count) +{ + if (!bus_runtime_ || !commands || count == 0 || count > 256) { + return false; + } + std::lock_guard lock(cyclic_command_mutex_); + cyclic_command_writes_.clear(); + cyclic_command_writes_.reserve(count); + for (std::size_t i = 0; i < count; ++i) { + const auto& command = commands[i]; + const auto* state = findNodeState_(command.node_id); + if (!std::isfinite(command.target_qd) || !state || + !hasValidConversion_(command.node_id, *state) || + state->mode != msgs::RUN_MODE_CYCLIC_SYNC_VELOCITY || + !status_monitor_->isNodeOperational(command.node_id)) { + return false; + } + for (std::size_t previous = 0; previous < i; ++previous) { + if (commands[previous].node_id == command.node_id) { + return false; + } + } + const double counts = command.target_qd / (2.0 * M_PI) * + state->gear_ratio * state->encoder_counts_per_rev; + if (!std::isfinite(counts) || + counts < std::numeric_limits::min() || + counts > std::numeric_limits::max()) { + return false; + } + cyclic_command_writes_.push_back( + EthercatMotorBusRuntime::makePdoWrite( + command.node_id, msgs::CIA402_TARGET_VELOCITY_60FF, 0x00, + radPerSecToCounts_(command.target_qd, *state))); + } + // The bus validates every PDO before changing the shared output frame. + if (!bus_runtime_->writePdosAtomic(cyclic_command_writes_.data(), count)) { + return false; + } + for (std::size_t i = 0; i < count; ++i) { + auto& state = nodeState_(commands[i].node_id); + state.target_velocity = radPerSecToCounts_(commands[i].target_qd, state); + } + return true; +} + bool Cia402Protocol::commandCyclicVelocity(const std::uint8_t node_id, const double target_qd) { - auto& state = nodeState_(node_id); - if (!hasValidConversion_(node_id, state) || - !status_monitor_->isNodeOperational(node_id)) { - return false; - } - state.target_velocity = radPerSecToCounts_(target_qd, state); - return writeTargetsForMode_(node_id, state.mode, state); + const CyclicVelocityCommand command{node_id, target_qd}; + return commandCyclicVelocitiesAtomic(&command, 1); } bool Cia402Protocol::commandCyclicTorque(const std::uint8_t node_id, diff --git a/cmvr-es/devices/motor/drivers/ethercat_motor/src/vendor/eyou/eyou_motor.cpp b/cmvr-es/devices/motor/drivers/ethercat_motor/src/vendor/eyou/eyou_motor.cpp index 20fcbfa2..0eb39ca7 100644 --- a/cmvr-es/devices/motor/drivers/ethercat_motor/src/vendor/eyou/eyou_motor.cpp +++ b/cmvr-es/devices/motor/drivers/ethercat_motor/src/vendor/eyou/eyou_motor.cpp @@ -151,6 +151,42 @@ bool EyouMotor::commandCyclicPositionsAtomic( return protocol && protocol->commandCyclicPositionsAtomic(commands.data(), motors.size()); } +bool EyouMotor::commandCyclicVelocitiesAtomic( + const std::vector>& motors, + const std::vector& velocities) +{ + if (motors.empty() || motors.size() != velocities.size() || motors.size() > 256) { + return false; + } + std::array lock_order{}; + std::array commands{}; + std::shared_ptr protocol; + for (std::size_t i = 0; i < motors.size(); ++i) { + const auto motor = std::dynamic_pointer_cast(motors[i]); + if (!motor || !std::isfinite(velocities[i]) || !motor->hasDependencies_() || + !motor->hasValidConversion_()) { + return false; + } + if (protocol && protocol != motor->cia402_protocol_) { + return false; + } + protocol = motor->cia402_protocol_; + for (std::size_t previous = 0; previous < i; ++previous) { + if (lock_order[previous] == motor.get()) { + return false; + } + } + lock_order[i] = motor.get(); + commands[i] = {motor->node_id_, velocities[i]}; + } + std::sort(lock_order.begin(), lock_order.begin() + motors.size(), std::less{}); + std::array, 256> locks{}; + for (std::size_t i = 0; i < motors.size(); ++i) { + locks[i] = std::unique_lock(lock_order[i]->mtx_); + } + return protocol->commandCyclicVelocitiesAtomic(commands.data(), motors.size()); +} + bool EyouMotor::readFeedbacksAtomic( const std::vector>& motors, std::vector& positions, diff --git a/cmvr-es/devices/motor/drivers/mujoco/include/mujoco_motor.h b/cmvr-es/devices/motor/drivers/mujoco/include/mujoco_motor.h index 57c97387..c4f75b48 100644 --- a/cmvr-es/devices/motor/drivers/mujoco/include/mujoco_motor.h +++ b/cmvr-es/devices/motor/drivers/mujoco/include/mujoco_motor.h @@ -49,6 +49,13 @@ public: const std::vector>& motors, const std::vector& positions, const std::vector& velocities); + static bool commandCyclicVelocitiesAtomic( + const std::vector>& motors, + const std::vector& velocities); + static bool readFeedbacksAtomic( + const std::vector>& motors, + std::vector& positions, + std::vector& velocities); private: bool holdPosition_(); diff --git a/cmvr-es/devices/motor/drivers/mujoco/src/mujoco_motor.cpp b/cmvr-es/devices/motor/drivers/mujoco/src/mujoco_motor.cpp index 447e8d18..588fd20c 100644 --- a/cmvr-es/devices/motor/drivers/mujoco/src/mujoco_motor.cpp +++ b/cmvr-es/devices/motor/drivers/mujoco/src/mujoco_motor.cpp @@ -2,6 +2,7 @@ #include #include +#include #include #include @@ -276,6 +277,83 @@ bool MujocoMotor::commandCyclicPositionsAtomic( return true; } +bool MujocoMotor::commandCyclicVelocitiesAtomic( + const std::vector>& motors, + const std::vector& velocities) +{ + if (motors.empty() || motors.size() != velocities.size()) { + return false; + } + std::vector selected; + selected.reserve(motors.size()); + std::shared_ptr world; + for (std::size_t i = 0; i < motors.size(); ++i) { + const auto motor = std::dynamic_pointer_cast(motors[i]); + if (!motor || !std::isfinite(velocities[i])) { + return false; + } + const auto motor_world = motor->worldLocked_(); + if (!motor_world || (world && world != motor_world) || + std::find(selected.begin(), selected.end(), motor.get()) != selected.end()) { + return false; + } + world = motor_world; + selected.push_back(motor.get()); + } + + auto lock_order = selected; + std::sort(lock_order.begin(), lock_order.end(), std::less{}); + std::vector> locks; + locks.reserve(lock_order.size()); + for (auto* motor : lock_order) { + locks.emplace_back(motor->mtx_); + } + std::vector names; + std::vector clamped_velocities; + names.reserve(selected.size()); + clamped_velocities.reserve(selected.size()); + for (std::size_t i = 0; i < selected.size(); ++i) { + if (!selected[i]->initialized_) { + return false; + } + names.push_back(selected[i]->info_.joint_name); + clamped_velocities.push_back(selected[i]->clampQd_(velocities[i])); + } + if (!world->setJointTargetVelocities(names, clamped_velocities)) { + return false; + } + for (auto* motor : selected) { + motor->mode_ = msgs::RUN_MODE_CYCLIC_SYNC_VELOCITY; + } + return true; +} + +bool MujocoMotor::readFeedbacksAtomic( + const std::vector>& motors, + std::vector& positions, + std::vector& velocities) +{ + if (motors.empty()) { + return false; + } + std::shared_ptr world; + std::vector names; + names.reserve(motors.size()); + for (const auto& item : motors) { + const auto motor = std::dynamic_pointer_cast(item); + if (!motor) { + return false; + } + const auto motor_world = motor->worldLocked_(); + if (!motor_world || (world && world != motor_world)) { + return false; + } + world = motor_world; + names.push_back(motor->info_.joint_name); + } + return world->getJointStates(names, positions, velocities); +} + double MujocoMotor::clampQ_(const double q) const { if (std::isfinite(info_.limit_q_lb) && std::isfinite(info_.limit_q_ub) && diff --git a/cmvr-es/devices/motor/manager/CMakeLists.txt b/cmvr-es/devices/motor/manager/CMakeLists.txt index 8ea5f495..6b9b0613 100644 --- a/cmvr-es/devices/motor/manager/CMakeLists.txt +++ b/cmvr-es/devices/motor/manager/CMakeLists.txt @@ -13,7 +13,7 @@ target_link_libraries(motor_manager cmvr_es::device::ti5_canopen_motor_driver cmvr_es::device::mujoco_motor_driver cmvr_es::device::ethercat_motor_driver - cmvr_es::ik_solver + cmvr_es::environment glog ) diff --git a/cmvr-es/devices/motor/manager/include/motor_manager.h b/cmvr-es/devices/motor/manager/include/motor_manager.h index 45e8ab3e..6a59030a 100644 --- a/cmvr-es/devices/motor/manager/include/motor_manager.h +++ b/cmvr-es/devices/motor/manager/include/motor_manager.h @@ -50,6 +50,9 @@ public: const std::vector>& motors, const std::vector& positions, const std::vector& velocities) const; + bool commandCyclicVelocitiesAtomic( + const std::vector>& motors, + const std::vector& velocities) const; bool readFeedbacksAtomic( const std::vector>& motors, std::vector& positions, diff --git a/cmvr-es/devices/motor/manager/src/motor_manager.cpp b/cmvr-es/devices/motor/manager/src/motor_manager.cpp index 1d1b262e..86e93e69 100644 --- a/cmvr-es/devices/motor/manager/src/motor_manager.cpp +++ b/cmvr-es/devices/motor/manager/src/motor_manager.cpp @@ -8,7 +8,6 @@ #include #include -#include "algorithms/kinematics/ik_solver/common/include/urdf_parser.h" #include "common/base/logging/logger.h" #include "common/config/config_files.h" #include "devices/motor/bus_runtime/abstract_motor_bus_runtime.h" @@ -22,6 +21,7 @@ #include "devices/motor/drivers/mujoco/include/mujoco_motor.h" #include "devices/motor/drivers/ti5_canopen/include/ti5_motor.h" #include "devices/motor/drivers/ti5_canopen/include/ti5_motor_canopen_protocol.h" +#include "environment/include/robot_model.h" namespace cmvr::device { @@ -311,18 +311,107 @@ bool MotorManager::commandCyclicPositionsAtomic( return false; } +bool MotorManager::commandCyclicVelocitiesAtomic( + const std::vector>& motors, + const std::vector& velocities) const +{ + if (motors.empty() || motors.size() != velocities.size()) { + return false; + } + for (std::size_t i = 0; i < motors.size(); ++i) { + if (!motors[i] || !std::isfinite(velocities[i])) { + return false; + } + for (std::size_t previous = 0; previous < i; ++previous) { + if (motors[previous] == motors[i]) { + return false; + } + } + } + if (std::dynamic_pointer_cast(motors.front())) { + return EyouMotor::commandCyclicVelocitiesAtomic(motors, velocities); + } + if (std::dynamic_pointer_cast(motors.front())) { + return MujocoMotor::commandCyclicVelocitiesAtomic(motors, velocities); + } + if (std::dynamic_pointer_cast(motors.front())) { + for (const auto& motor : motors) { + if (!std::dynamic_pointer_cast(motor)) { + return false; + } + } + static std::once_flag warning; + std::call_once(warning, []() { + CMVR_LOG(WARNING) + << "[MotorManager] TI5 uses non-atomic cyclic velocity commands"; + }); + for (std::size_t i = 0; i < motors.size(); ++i) { + if (!motors[i]->commandCyclicVelocity(velocities[i])) { + // CAN commands cannot be rolled back; attempt to stop every motor. + for (const auto& motor : motors) { + if (!motor->commandCyclicVelocity(0.0)) { + CMVR_LOG(ERROR) << "[MotorManager] failed to zero TI5 motor: " + << motor->id(); + } + } + return false; + } + } + return true; + } + CMVR_LOG(ERROR) << "[MotorManager] atomic cyclic velocity is unsupported for motor type: " + << motors.front()->typeName(); + return false; +} + bool MotorManager::readFeedbacksAtomic( const std::vector>& motors, std::vector& positions, std::vector& velocities) const { - if (motors.empty()) { + if (motors.empty() || &positions == &velocities) { return false; } + for (std::size_t i = 0; i < motors.size(); ++i) { + if (!motors[i]) { + return false; + } + for (std::size_t previous = 0; previous < i; ++previous) { + if (motors[previous] == motors[i]) { + return false; + } + } + } if (std::dynamic_pointer_cast(motors.front())) { return EyouMotor::readFeedbacksAtomic(motors, positions, velocities); } + if (std::dynamic_pointer_cast(motors.front())) { + return MujocoMotor::readFeedbacksAtomic(motors, positions, velocities); + } + if (std::dynamic_pointer_cast(motors.front())) { + for (const auto& motor : motors) { + if (!std::dynamic_pointer_cast(motor)) { + return false; + } + } + static std::once_flag warning; + std::call_once(warning, []() { + CMVR_LOG(WARNING) << "[MotorManager] TI5 feedback is read per motor, not atomically"; + }); + std::vector q(motors.size()); + std::vector qd(motors.size()); + for (std::size_t i = 0; i < motors.size(); ++i) { + q[i] = motors[i]->getQ(); + qd[i] = motors[i]->getQd(); + if (!std::isfinite(q[i]) || !std::isfinite(qd[i])) { + return false; + } + } + positions = std::move(q); + velocities = std::move(qd); + return true; + } CMVR_LOG(ERROR) << "[MotorManager] atomic feedback is unsupported for motor type: " << motors.front()->typeName(); @@ -387,22 +476,18 @@ bool MotorManager::applyConfiguredJointLimits_(const config::MotorGroupConfig& g return false; } - UrdfParser parser; - std::string error; - if (!parser.loadModel(urdf_path, &error)) { - CMVR_LOG(ERROR) << "[MotorManager] Failed to load joint limit URDF: " << error; + RobotModel model; + if (!model.loadUrdf(urdf_path)) { + CMVR_LOG(ERROR) << "[MotorManager] Failed to load joint limit URDF: " << urdf_path; return false; } - const auto& model = parser.model(); - for (pinocchio::JointIndex joint_id = 1; joint_id < model.njoints; ++joint_id) { - if (model.nqs[joint_id] != 1 || model.nvs[joint_id] != 1) { - continue; - } + for (std::size_t index = 0; index < model.joint_names.size(); ++index) { + const auto& joint_limit = model.joint_limits[index]; config::JointLimitConfig limit; - limit.set_joint_name(model.names[joint_id]); - limit.set_q_lb(model.lowerPositionLimit[model.idx_qs[joint_id]]); - limit.set_q_ub(model.upperPositionLimit[model.idx_qs[joint_id]]); - limit.set_qd(model.velocityLimit[model.idx_vs[joint_id]]); + limit.set_joint_name(model.joint_names[index]); + limit.set_q_lb(joint_limit.lower); + limit.set_q_ub(joint_limit.upper); + limit.set_qd(joint_limit.max_velocity); limits_by_joint[limit.joint_name()] = limit; } } else { diff --git a/cmvr-es/environment/CMakeLists.txt b/cmvr-es/environment/CMakeLists.txt new file mode 100644 index 00000000..b96a4097 --- /dev/null +++ b/cmvr-es/environment/CMakeLists.txt @@ -0,0 +1,13 @@ +add_library(environment SHARED src/robot_model.cpp) + +target_include_directories(environment PUBLIC "${PROJECT_SOURCE_DIR}/cmvr-es") +target_compile_definitions(environment PRIVATE + PINOCCHIO_ENABLE_TEMPLATE_INSTANTIATION + PINOCCHIO_WITH_HPP_FCL + COAL_BACKWARD_COMPATIBILITY_WITH_HPP_FCL + COAL_DISABLE_HPP_FCL_WARNINGS +) +target_link_libraries(environment PRIVATE cmvr_es::logging pinocchio_default pinocchio_parsers coal) + +add_library(cmvr_es::environment ALIAS environment) +install(TARGETS environment LIBRARY DESTINATION lib) diff --git a/cmvr-es/environment/include/robot_model.h b/cmvr-es/environment/include/robot_model.h new file mode 100644 index 00000000..4d488303 --- /dev/null +++ b/cmvr-es/environment/include/robot_model.h @@ -0,0 +1,104 @@ +#ifndef CMVR_ES_ENVIRONMENT_ROBOT_MODEL_H +#define CMVR_ES_ENVIRONMENT_ROBOT_MODEL_H + +#include +#include +#include +#include + +#include +#include +#include + +namespace cmvr { + +using CollisionShape = coal::CollisionGeometry; + +struct CollisionBody { + EIGEN_MAKE_ALIGNED_OPERATOR_NEW + + std::size_t geometry_index{0}; + std::string name; + std::string link_name; + // Empty joint names represent the model root. + std::string joint_name; + std::string parent_joint_name; + std::shared_ptr geometry; + Eigen::Vector3d position{Eigen::Vector3d::Zero()}; + Eigen::Quaterniond orientation{Eigen::Quaterniond::Identity()}; + double bounding_radius_m{0.0}; +}; + +struct JointLimit { + double lower{0.0}; + double upper{0.0}; + double max_velocity{0.0}; + double max_acceleration{0.0}; + double max_torque{0.0}; +}; + +// Device metadata remains usable without a URDF. Loaded model resources are +// immutable and shared when this object is copied; live robot state is external. +struct RobotModel { + std::string name; + std::string manufacturer; + std::string serial_number; + std::size_t dof{0}; + std::vector joint_names; + std::vector joint_limits; + double max_tcp_speed{0.0}; + double max_tcp_acceleration{0.0}; + double max_payload{0.0}; + + bool valid() const + { + return dof > 0 && joint_names.size() == dof && + (joint_limits.empty() || joint_limits.size() == dof); + } + + // Boolean operations log errors and return false on failure. + // Loads kinematics only. Empty joint_names selects all one-DoF joints; + // otherwise the configured joint order is preserved. Limits come from URDF. + // Reloading clears previous kinematics and collision resources, even on failure. + bool loadUrdf(const std::string& path); + + // Optional collision URDF must match the loaded kinematics. A URDF without + // collision elements is accepted; an empty path explicitly clears geometry. + // Failure clears collision resources while retaining the kinematic model. + bool loadCollisionGeometry(const std::string& path); + + bool hasKinematics() const; + // Read-only backend model for IK. Missing kinematics throw; the reference + // remains valid while these loaded resources are retained by a model copy. + const pinocchio::Model& kinematics() const; + bool hasCollisionGeometry() const; + std::size_t collisionGeometryCount() const; + const std::string& urdfPath() const; + const std::string& collisionUrdfPath() const; + + // Computes root-fixed bodies and bodies attached to the active joints. + // Positions follow active_joint_names (joint_names if empty); inactive joints + // stay neutral. Missing collision geometry succeeds with an empty result. + // Invalid joint selections/positions or missing kinematics log and throw. + std::vector collisionBodies( + const std::vector& joint_positions, + const std::vector& active_joint_names = {}) const; + + // Resolve a frame rigidly attached to the model root, without live joint state. + bool fixedFramePose(const std::string& frame_name, Eigen::Isometry3d& pose) const; + bool containsName(const std::string& name) const; + +private: + static void requireMatchingKinematics(const pinocchio::Model& reference, + const pinocchio::Model& collision); + + std::string urdf_path_; + std::string collision_urdf_path_; + std::shared_ptr kinematics_; + std::shared_ptr collision_kinematics_; + std::shared_ptr collision_geometry_; +}; + +} // namespace cmvr + +#endif // CMVR_ES_ENVIRONMENT_ROBOT_MODEL_H diff --git a/cmvr-es/environment/src/robot_model.cpp b/cmvr-es/environment/src/robot_model.cpp new file mode 100644 index 00000000..a428f085 --- /dev/null +++ b/cmvr-es/environment/src/robot_model.cpp @@ -0,0 +1,310 @@ +#include "environment/include/robot_model.h" + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "common/base/logging/logger.h" + +namespace cmvr { + +void RobotModel::requireMatchingKinematics(const pinocchio::Model& reference, + const pinocchio::Model& collision) +{ + if (reference.njoints != collision.njoints || reference.nq != collision.nq || + reference.nv != collision.nv) { + throw std::runtime_error("Collision URDF joint structure differs from kinematic URDF"); + } + for (pinocchio::JointIndex id = 1; id < collision.joints.size(); ++id) { + const auto& name = collision.names[id]; + if (!reference.existJointName(name)) { + throw std::runtime_error("Collision URDF contains an unknown joint: " + name); + } + const auto reference_id = reference.getJointId(name); + const auto& reference_joint = reference.joints[reference_id]; + auto collision_joint = collision.joints[id]; + // Compare the joint type and axis independently of parser ordering. + collision_joint.setIndexes(reference_joint.id(), reference_joint.idx_q(), + reference_joint.idx_v(), reference_joint.idx_vExtended()); + if (collision_joint != reference_joint || + collision.names[collision.parents[id]] != + reference.names[reference.parents[reference_id]] || + !collision.jointPlacements[id].isApprox(reference.jointPlacements[reference_id], 1e-9)) { + throw std::runtime_error("Collision URDF joint kinematics differ: " + name); + } + } + for (const auto& frame : collision.frames) { + if (!reference.existFrame(frame.name, frame.type)) { + // Collision-only fixed links may describe simplified geometry. + // Movable joints were already matched above. + continue; + } + const auto& reference_frame = reference.frames[reference.getFrameId(frame.name, frame.type)]; + if (collision.names[frame.parentJoint] != reference.names[reference_frame.parentJoint] || + !frame.placement.isApprox(reference_frame.placement, 1e-9)) { + throw std::runtime_error("Collision URDF frame placement differs: " + frame.name); + } + } +} + +bool RobotModel::loadUrdf(const std::string& path) +{ + auto urdf_path = path; + kinematics_.reset(); + collision_geometry_.reset(); + collision_kinematics_.reset(); + urdf_path_.clear(); + collision_urdf_path_.clear(); + try { + auto kinematics = std::make_shared(); + pinocchio::urdf::buildModel(urdf_path, *kinematics); + const auto& model = *kinematics; + + auto names = joint_names; + if (names.empty()) { + for (pinocchio::JointIndex id = 1; id < model.joints.size(); ++id) { + if (model.joints[id].nq() == 1 && model.joints[id].nv() == 1) { + names.push_back(model.names[id]); + } + } + } + std::vector limits; + limits.reserve(names.size()); + std::unordered_set unique_names; + for (const auto& joint_name : names) { + if (joint_name.empty() || !unique_names.insert(joint_name).second) { + throw std::runtime_error("Joint names must be non-empty and unique"); + } + if (!model.existJointName(joint_name)) { + throw std::runtime_error("Joint not found in URDF: " + joint_name); + } + const auto& joint = model.joints[model.getJointId(joint_name)]; + if (joint.nq() != 1 || joint.nv() != 1) { + throw std::runtime_error("Only one-DoF selected joints are supported: " + joint_name); + } + limits.push_back({model.lowerPositionLimit[joint.idx_q()], + model.upperPositionLimit[joint.idx_q()], + model.velocityLimit[joint.idx_v()], 0.0, + model.effortLimit[joint.idx_v()]}); + } + if (name.empty()) { + name = model.name; + } + dof = names.size(); + joint_names = std::move(names); + joint_limits = std::move(limits); + urdf_path_ = std::move(urdf_path); + kinematics_ = std::move(kinematics); + return true; + } catch (const std::exception& exception) { + CMVR_LOG(ERROR) << "[RobotModel][loadUrdf] path=" << urdf_path << ": " << exception.what(); + return false; + } +} + +bool RobotModel::loadCollisionGeometry(const std::string& path) +{ + auto collision_path = path; + collision_geometry_.reset(); + collision_kinematics_.reset(); + collision_urdf_path_.clear(); + if (collision_path.empty()) { + return true; + } + if (!kinematics_) { + CMVR_LOG(ERROR) << "[RobotModel][loadCollisionGeometry] load robot kinematics first"; + return false; + } + try { + std::shared_ptr collision_kinematics = kinematics_; + if (collision_path != urdf_path_) { + auto model = std::make_shared(); + pinocchio::urdf::buildModel(collision_path, *model); + requireMatchingKinematics(*kinematics_, *model); + collision_kinematics = std::move(model); + } + auto geometry = std::make_shared(); + pinocchio::urdf::buildGeom(*collision_kinematics, collision_path, + pinocchio::COLLISION, *geometry); + for (const auto& object : geometry->geometryObjects) { + if (!object.geometry) { + throw std::runtime_error("Null collision geometry: " + object.name); + } + object.geometry->computeLocalAABB(); + } + collision_urdf_path_ = std::move(collision_path); + collision_kinematics_ = std::move(collision_kinematics); + collision_geometry_ = std::move(geometry); + return true; + } catch (const std::exception& exception) { + CMVR_LOG(ERROR) << "[RobotModel][loadCollisionGeometry] path=" << collision_path << ": " << exception.what(); + return false; + } +} + +bool RobotModel::hasKinematics() const +{ + return static_cast(kinematics_); +} + +const pinocchio::Model& RobotModel::kinematics() const +{ + if (!kinematics_) { + throw std::logic_error("Robot kinematics are not loaded"); + } + return *kinematics_; +} + +bool RobotModel::hasCollisionGeometry() const +{ + return collisionGeometryCount() > 0; +} + +std::size_t RobotModel::collisionGeometryCount() const +{ + return collision_geometry_ ? collision_geometry_->ngeoms : 0; +} + +const std::string& RobotModel::urdfPath() const +{ + return urdf_path_; +} + +const std::string& RobotModel::collisionUrdfPath() const +{ + return collision_urdf_path_; +} + +std::vector RobotModel::collisionBodies( + const std::vector& joint_positions, + const std::vector& active_joint_names) const +{ + try { + if (!kinematics_) { + throw std::logic_error("Robot kinematics are not loaded"); + } + const auto& model = collision_kinematics_ ? *collision_kinematics_ : *kinematics_; + const auto& names = active_joint_names.empty() ? joint_names : active_joint_names; + if (joint_positions.size() != names.size()) { + throw std::invalid_argument("Joint position size mismatch: expected " + + std::to_string(names.size()) + ", got " + + std::to_string(joint_positions.size())); + } + std::unordered_set active_joint_ids; + Eigen::VectorXd q = pinocchio::neutral(model); + for (std::size_t index = 0; index < names.size(); ++index) { + const auto& joint_name = names[index]; + if (joint_name.empty() || !model.existJointName(joint_name)) { + throw std::invalid_argument("Joint not found in URDF: " + joint_name); + } + const auto joint_id = model.getJointId(joint_name); + if (!active_joint_ids.insert(joint_id).second) { + throw std::invalid_argument("Active joint names must be unique: " + joint_name); + } + const auto& joint = model.joints[joint_id]; + if (joint.nq() != 1 || joint.nv() != 1) { + throw std::invalid_argument("Only one-DoF active joints are supported: " + joint_name); + } + if (!std::isfinite(joint_positions[index])) { + throw std::invalid_argument("Non-finite joint position: " + joint_name); + } + q[joint.idx_q()] = joint_positions[index]; + } + if (!hasCollisionGeometry()) { + return {}; + } + + const auto& geometry = *collision_geometry_; + // Reuse one workspace per thread; switching models rebuilds it. Retain + // the immutable resources so reloads cannot reuse a stale model address. + thread_local std::shared_ptr cached_model; + thread_local std::shared_ptr cached_geometry; + thread_local std::unique_ptr data; + thread_local std::unique_ptr geometry_data; + if (cached_model != collision_kinematics_) { + data = std::make_unique(model); + cached_model = collision_kinematics_; + } + if (cached_geometry != collision_geometry_) { + geometry_data = std::make_unique(geometry); + cached_geometry = collision_geometry_; + } + pinocchio::updateGeometryPlacements( + model, *data, geometry, *geometry_data, q); + std::vector bodies; + bodies.reserve(geometry.ngeoms); + for (pinocchio::GeomIndex id = 0; id < geometry.ngeoms; ++id) { + const auto& object = geometry.geometryObjects[id]; + if (object.parentJoint != 0 && !active_joint_ids.count(object.parentJoint)) { + continue; + } + const auto& placement = geometry_data->oMg[id]; + if (!placement.translation().allFinite() || !placement.rotation().allFinite()) { + throw std::runtime_error("Non-finite collision body pose: " + object.name); + } + CollisionBody body; + body.geometry_index = id; + body.name = object.name; + body.link_name = object.parentFrame < model.frames.size() + ? model.frames[object.parentFrame].name : object.name; + if (object.parentJoint != 0) { + body.joint_name = model.names[object.parentJoint]; + const auto parent = model.parents[object.parentJoint]; + if (parent != 0) { + body.parent_joint_name = model.names[parent]; + } + } + body.geometry = object.geometry; + body.position = placement.translation(); + body.orientation = Eigen::Quaterniond(placement.rotation()).normalized(); + body.bounding_radius_m = std::max(0.0, body.geometry->aabb_radius); + bodies.push_back(std::move(body)); + } + return bodies; + } catch (const std::exception& exception) { + CMVR_LOG(ERROR) << "[RobotModel][collisionBodies] " << exception.what(); + throw; + } +} + +bool RobotModel::fixedFramePose(const std::string& frame_name, Eigen::Isometry3d& pose) const +{ + if (!kinematics_) { + CMVR_LOG(ERROR) << "[RobotModel][fixedFramePose] robot kinematics are not loaded"; + return false; + } + const auto& model = collision_kinematics_ ? *collision_kinematics_ : *kinematics_; + if (frame_name.empty() || !model.existFrame(frame_name)) { + CMVR_LOG(ERROR) << "[RobotModel][fixedFramePose] frame not found in URDF: " << frame_name; + return false; + } + const auto& frame = model.frames[model.getFrameId(frame_name)]; + if (frame.parentJoint != 0) { + CMVR_LOG(ERROR) << "[RobotModel][fixedFramePose] frame must be fixed to the model root: " << frame_name; + return false; + } + pose.matrix() = frame.placement.toHomogeneousMatrix(); + return true; +} + +bool RobotModel::containsName(const std::string& name) const +{ + const auto has_name = [&name](const pinocchio::Model& model) { + return model.existJointName(name) || model.existFrame(name); + }; + return (kinematics_ && has_name(*kinematics_)) || + (collision_geometry_ && + (has_name(*collision_kinematics_) || + collision_geometry_->existGeometryName(name))); +} + +} // namespace cmvr diff --git a/cmvr-es/safety/CMakeLists.txt b/cmvr-es/safety/CMakeLists.txt new file mode 100644 index 00000000..8940faf0 --- /dev/null +++ b/cmvr-es/safety/CMakeLists.txt @@ -0,0 +1,18 @@ +add_library(self_collision_monitor SHARED + self_collision/src/self_collision_monitor.cpp +) + +target_include_directories(self_collision_monitor PUBLIC + ${PROJECT_SOURCE_DIR}/cmvr-es +) + +target_link_libraries(self_collision_monitor + PUBLIC + cmvr_es::collision_checker + cmvr_es::proto + PRIVATE + cmvr_es::logging +) + +add_library(cmvr_es::self_collision_monitor ALIAS self_collision_monitor) +install(TARGETS self_collision_monitor LIBRARY DESTINATION lib) diff --git a/cmvr-es/safety/self_collision/include/self_collision_monitor.h b/cmvr-es/safety/self_collision/include/self_collision_monitor.h new file mode 100644 index 00000000..815d315c --- /dev/null +++ b/cmvr-es/safety/self_collision/include/self_collision_monitor.h @@ -0,0 +1,92 @@ +#ifndef CMVR_ES_SELF_COLLISION_MONITOR_H +#define CMVR_ES_SELF_COLLISION_MONITOR_H + +#include +#include +#include +#include +#include +#include + +#include "algorithms/collision_detection/include/distance_sampling_policy.h" +#include "algorithms/collision_detection/include/collision_checker.h" +#include "cmvr/config/collision_config.pb.h" +#include "devices/arm/robot_arm.h" + +namespace cmvr::safety { + +enum class CollisionSafetyLevel { + UNKNOWN = 0, + SAFE, + WARNING, + STOP, +}; + +enum class ProtectiveRecoveryState { + IDLE = 0, + AVAILABLE, + RECOVERING, + SUCCEEDED, + FAILED, +}; + +struct SelfCollisionStatus { + CollisionSafetyLevel level{CollisionSafetyLevel::UNKNOWN}; + CollisionResult result; + bool stop_latched{false}; + std::uint64_t event_id{0}; + ProtectiveRecoveryState recovery_state{ProtectiveRecoveryState::IDLE}; + std::size_t recovery_sample_count{0}; + std::string recovery_error; +}; + +// The arm must outlive the monitor. The caller initializes it before use and +// serializes step() calls. No worker thread is created here; step() must continue +// during protective stops and while requestRecovery() runs on another thread. +class SelfCollisionMonitor { +public: + enum class State { UNINITIALIZED = 0, IDLE, RUNNING, STOPPED, FAILED }; + + SelfCollisionMonitor(const config::SelfCollisionMonitorConfig& config, + device::RobotArm& arm); + + bool init(); + bool start(); + bool step(); + void stop(); + + State state() const; + std::string detailStatusString() const; + SelfCollisionStatus latestStatus() const; + device::Result requestRecovery(std::uint64_t event_id); + +private: + static bool validateConfig(const config::SelfCollisionMonitorConfig& config, + std::string* error); + static const char* safetyLevelToString(CollisionSafetyLevel level); + static const char* recoveryStateToString(ProtectiveRecoveryState state); + void recordJointSample_(const device::JointGroupState& joint_state, + DistanceSamplingPolicy::Clock::time_point now); + + config::SelfCollisionMonitorConfig config_; + device::RobotArm& arm_; + CollisionChecker checker_; + DistanceSamplingPolicy sampling_; + + mutable std::mutex mutex_; + std::condition_variable recovery_cv_; + State state_{State::UNINITIALIZED}; + SelfCollisionStatus latest_status_{}; + std::deque joint_history_; + device::JointTrajectory recovery_path_; + DistanceSamplingPolicy::Clock::time_point history_epoch_{}; + std::optional recovery_clear_since_; + double recovery_best_distance_m_{0.0}; + bool recovery_clear_confirmed_{false}; + std::uint64_t next_event_id_{1}; + std::string last_error_; +}; + +} // namespace cmvr::safety + +#endif // CMVR_ES_SELF_COLLISION_MONITOR_H diff --git a/cmvr-es/safety/self_collision/src/self_collision_monitor.cpp b/cmvr-es/safety/self_collision/src/self_collision_monitor.cpp new file mode 100644 index 00000000..8dddecf4 --- /dev/null +++ b/cmvr-es/safety/self_collision/src/self_collision_monitor.cpp @@ -0,0 +1,557 @@ +#include "safety/self_collision/include/self_collision_monitor.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "common/base/logging/logger.h" + +namespace cmvr::safety { +namespace { + +const char* monitorStateToString(const SelfCollisionMonitor::State state) +{ + using State = SelfCollisionMonitor::State; + switch (state) { + case State::UNINITIALIZED: return "UNINITIALIZED"; + case State::IDLE: return "IDLE"; + case State::RUNNING: return "RUNNING"; + case State::STOPPED: return "STOPPED"; + case State::FAILED: return "FAILED"; + } + return "UNKNOWN"; +} + +} // namespace + +SelfCollisionMonitor::SelfCollisionMonitor( + const config::SelfCollisionMonitorConfig& config, device::RobotArm& arm) + : config_(config), arm_(arm) +{ +} + +bool SelfCollisionMonitor::validateConfig(const config::SelfCollisionMonitorConfig& config, + std::string* error) +{ + auto fail = [error](const std::string& message) { + if (error) { + *error = message; + } + return false; + }; + + const auto& sampling = config.sampling(); + if (!std::isfinite(sampling.max_geometry_displacement_m()) || + sampling.max_geometry_displacement_m() <= 0.0) { + return fail("max_geometry_displacement_m must be finite and positive"); + } + if (!std::isfinite(sampling.max_check_period_s()) || + sampling.max_check_period_s() <= 0.0) { + return fail("max_check_period_s must be finite and positive"); + } + + const auto& safety = config.safety(); + if (!std::isfinite(safety.stop_distance_m()) || safety.stop_distance_m() < 0.0) { + return fail("stop_distance_m must be finite and non-negative"); + } + if (!std::isfinite(safety.warning_distance_m()) || + safety.warning_distance_m() < safety.stop_distance_m()) { + return fail("warning_distance_m must be finite and not less than stop_distance_m"); + } + const auto& recovery = config.recovery(); + if (!std::isfinite(recovery.clear_distance_m()) || + recovery.clear_distance_m() <= safety.warning_distance_m()) { + return fail("recovery clear_distance_m must be finite and greater than warning_distance_m"); + } + if (!std::isfinite(recovery.stable_period_s()) || + recovery.stable_period_s() <= 0.0) { + return fail("recovery stable_period_s must be finite and positive"); + } + if (!std::isfinite(recovery.max_joint_velocity_rad_s()) || + recovery.max_joint_velocity_rad_s() <= 0.0) { + return fail("recovery max_joint_velocity_rad_s must be finite and positive"); + } + if (!std::isfinite(recovery.max_joint_acceleration_rad_s2()) || + recovery.max_joint_acceleration_rad_s2() <= 0.0) { + return fail("recovery max_joint_acceleration_rad_s2 must be finite and positive"); + } + if (!std::isfinite(recovery.history_duration_s()) || + recovery.history_duration_s() <= 0.0) { + return fail("recovery history_duration_s must be finite and positive"); + } + if (!std::isfinite(recovery.max_distance_regression_m()) || + recovery.max_distance_regression_m() < 0.0) { + return fail("recovery max_distance_regression_m must be finite and non-negative"); + } + if (error) { + error->clear(); + } + return true; +} + +bool SelfCollisionMonitor::init() +{ + std::string error; + if (!validateConfig(config_, &error)) { + std::lock_guard lock(mutex_); + last_error_ = std::move(error); + state_ = State::FAILED; + return false; + } + + auto* arm = &arm_; + const auto model = arm->getRobotModel(); + if (!model.valid()) { + std::lock_guard lock(mutex_); + last_error_ = "Robot arm model is invalid"; + state_ = State::FAILED; + return false; + } + + if (!checker_.init(config_.checker(), model, &error)) { + std::lock_guard lock(mutex_); + last_error_ = std::move(error); + state_ = State::FAILED; + return false; + } + + const DistanceSamplingOptions sampling_options{ + config_.sampling().max_geometry_displacement_m(), + config_.sampling().max_check_period_s(), + }; + if (!sampling_.configure(sampling_options, &error)) { + std::lock_guard lock(mutex_); + last_error_ = std::move(error); + state_ = State::FAILED; + return false; + } + + { + std::lock_guard lock(mutex_); + latest_status_ = {}; + joint_history_.clear(); + recovery_path_.clear(); + history_epoch_ = DistanceSamplingPolicy::Clock::now(); + recovery_clear_since_.reset(); + recovery_best_distance_m_ = 0.0; + recovery_clear_confirmed_ = false; + next_event_id_ = 1; + last_error_.clear(); + state_ = State::IDLE; + } + CMVR_LOG(INFO) << "[SelfCollisionMonitor] Initialized dof=" << checker_.dof() + << ", active_pairs=" << checker_.activePairCount(); + return true; +} + +bool SelfCollisionMonitor::start() +{ + std::lock_guard lock(mutex_); + if (state_ == State::RUNNING) { + return true; + } + if (state_ != State::IDLE && state_ != State::STOPPED) { + last_error_ = "Self-collision monitor is not initialized"; + state_ = State::FAILED; + return false; + } + sampling_.reset(); + latest_status_ = {}; + joint_history_.clear(); + recovery_path_.clear(); + history_epoch_ = DistanceSamplingPolicy::Clock::now(); + recovery_clear_since_.reset(); + recovery_best_distance_m_ = 0.0; + recovery_clear_confirmed_ = false; + last_error_.clear(); + state_ = State::RUNNING; + return true; +} + +bool SelfCollisionMonitor::step() +{ + auto* arm = &arm_; + { + std::lock_guard lock(mutex_); + if (state_ != State::RUNNING) { + return false; + } + } + + const auto fail_monitoring = [&](std::string error) { + bool cancel_recovery = false; + { + std::lock_guard lock(mutex_); + cancel_recovery = + latest_status_.recovery_state == ProtectiveRecoveryState::RECOVERING; + if (cancel_recovery) { + latest_status_.recovery_state = ProtectiveRecoveryState::FAILED; + latest_status_.recovery_error = error; + } + last_error_ = std::move(error); + state_ = State::FAILED; + recovery_cv_.notify_all(); + } + if (cancel_recovery) { + (void)arm->protectiveStop(); + } + return false; + }; + + const auto joint_state = arm->getJointState(); + const auto model = arm->getRobotModel(); + if (!joint_state.validForModel(model)) { + return fail_monitoring("Robot arm returned an invalid joint state"); + } + + const auto now = DistanceSamplingPolicy::Clock::now(); + recordJointSample_(joint_state, now); + + std::vector bodies; + try { + bodies = checker_.collisionBodies(joint_state.position); + } catch (const std::exception& error) { + return fail_monitoring(error.what()); + } + + if (!sampling_.shouldCheck(bodies, now)) { + return true; + } + + CollisionResult result = checker_.check(bodies); + if (!result.valid) { + return fail_monitoring( + result.error.empty() ? "Self-collision distance check failed" : result.error); + } + sampling_.markChecked(bodies, now); + + CollisionSafetyLevel level = CollisionSafetyLevel::SAFE; + if (result.minimum_distance_m <= config_.safety().stop_distance_m()) { + level = CollisionSafetyLevel::STOP; + } else if (result.minimum_distance_m <= config_.safety().warning_distance_m()) { + level = CollisionSafetyLevel::WARNING; + } + + bool trigger_stop = false; + bool abort_recovery = false; + CollisionSafetyLevel previous_level = CollisionSafetyLevel::UNKNOWN; + { + std::lock_guard lock(mutex_); + if (state_ != State::RUNNING) { + return true; + } + previous_level = latest_status_.level; + latest_status_.level = level; + latest_status_.result = result; + + if (latest_status_.recovery_state == ProtectiveRecoveryState::RECOVERING) { + if (arm->isEmergencyStopped()) { + latest_status_.recovery_state = ProtectiveRecoveryState::FAILED; + latest_status_.recovery_error = + "Protective recovery interrupted by emergency stop"; + recovery_clear_since_.reset(); + abort_recovery = true; + recovery_cv_.notify_all(); + } else if (result.minimum_distance_m + + config_.recovery().max_distance_regression_m() < + recovery_best_distance_m_) { + std::ostringstream stream; + stream << "Protective recovery distance regressed from " + << recovery_best_distance_m_ << " m to " + << result.minimum_distance_m << " m"; + latest_status_.recovery_state = ProtectiveRecoveryState::FAILED; + latest_status_.recovery_error = stream.str(); + recovery_clear_since_.reset(); + abort_recovery = true; + recovery_cv_.notify_all(); + } else { + recovery_best_distance_m_ = std::max( + recovery_best_distance_m_, result.minimum_distance_m); + if (result.minimum_distance_m >= + config_.recovery().clear_distance_m()) { + if (!recovery_clear_since_) { + recovery_clear_since_ = now; + } else if (std::chrono::duration( + now - *recovery_clear_since_).count() >= + config_.recovery().stable_period_s()) { + recovery_clear_confirmed_ = true; + recovery_cv_.notify_all(); + } + } else { + recovery_clear_since_.reset(); + recovery_clear_confirmed_ = false; + } + } + } else if (level == CollisionSafetyLevel::STOP && + !latest_status_.stop_latched) { + latest_status_.stop_latched = true; + latest_status_.event_id = next_event_id_++; + latest_status_.recovery_state = ProtectiveRecoveryState::AVAILABLE; + latest_status_.recovery_error.clear(); + recovery_path_.assign(joint_history_.begin(), joint_history_.end()); + latest_status_.recovery_sample_count = recovery_path_.size(); + trigger_stop = true; + } else if (!latest_status_.stop_latched && + result.minimum_distance_m >= + config_.recovery().clear_distance_m()) { + joint_history_.clear(); + device::JointTrajectoryPoint sample; + sample.time_s = std::chrono::duration(now - history_epoch_).count(); + sample.position = joint_state.position; + sample.velocity = joint_state.velocity; + joint_history_.push_back(std::move(sample)); + } + } + + if (level != previous_level) { + if (level == CollisionSafetyLevel::SAFE) { + CMVR_LOG(INFO) << "[SelfCollisionMonitor] level=" << safetyLevelToString(level) + << ", distance_m=" << result.minimum_distance_m + << ", pair=" << result.first << "/" << result.second; + } else { + CMVR_LOG(WARNING) << "[SelfCollisionMonitor] level=" << safetyLevelToString(level) + << ", distance_m=" << result.minimum_distance_m + << ", pair=" << result.first << "/" << result.second; + } + } + + if (abort_recovery) { + (void)arm->protectiveStop(); + } else if (trigger_stop) { + const auto stop_result = arm->protectiveStop(); + if (!stop_result.ok()) { + std::lock_guard lock(mutex_); + last_error_ = "Protective stop failed: " + stop_result.message; + state_ = State::FAILED; + return false; + } + } + return true; +} + +void SelfCollisionMonitor::recordJointSample_( + const device::JointGroupState& joint_state, + const DistanceSamplingPolicy::Clock::time_point now) +{ + std::lock_guard lock(mutex_); + if (state_ != State::RUNNING || latest_status_.stop_latched) { + return; + } + + device::JointTrajectoryPoint sample; + sample.time_s = std::chrono::duration(now - history_epoch_).count(); + sample.position = joint_state.position; + sample.velocity = joint_state.velocity; + if (!joint_history_.empty() && sample.time_s <= joint_history_.back().time_s) { + return; + } + joint_history_.push_back(std::move(sample)); + + const double oldest_time_s = joint_history_.back().time_s - + config_.recovery().history_duration_s(); + while (joint_history_.size() > 1 && + joint_history_.front().time_s < oldest_time_s) { + joint_history_.pop_front(); + } +} + +device::Result SelfCollisionMonitor::requestRecovery(const std::uint64_t event_id) +{ + auto* arm = &arm_; + device::JointTrajectory path; + device::MotionOptions options; + { + std::lock_guard lock(mutex_); + if (state_ != State::RUNNING) { + return device::Result::failure( + device::ArmErrorCode::RobotNotReady, + "Protective recovery rejected: collision monitor is not running"); + } + if (!latest_status_.stop_latched || + latest_status_.recovery_state != ProtectiveRecoveryState::AVAILABLE) { + return device::Result::failure( + device::ArmErrorCode::CommandRejected, + "Protective recovery rejected: no recoverable collision stop is available"); + } + if (event_id == 0 || event_id != latest_status_.event_id) { + return device::Result::failure( + device::ArmErrorCode::InvalidArgument, + "Protective recovery rejected: event_id does not match the active stop"); + } + if (!arm_.isProtectiveStopped() || arm_.isEmergencyStopped()) { + return device::Result::failure( + arm_.isEmergencyStopped() + ? device::ArmErrorCode::RobotInEmergencyStop + : device::ArmErrorCode::RobotNotReady, + "Protective recovery rejected: arm safety state is invalid"); + } + if (recovery_path_.size() < 2) { + latest_status_.recovery_state = ProtectiveRecoveryState::FAILED; + latest_status_.recovery_error = + "Protective recovery path contains fewer than two samples"; + return device::Result::failure( + device::ArmErrorCode::CommandRejected, + latest_status_.recovery_error); + } + + path = recovery_path_; + options.velocity = config_.recovery().max_joint_velocity_rad_s(); + options.acceleration = + config_.recovery().max_joint_acceleration_rad_s2(); + latest_status_.recovery_state = ProtectiveRecoveryState::RECOVERING; + latest_status_.recovery_error.clear(); + recovery_best_distance_m_ = latest_status_.result.minimum_distance_m; + recovery_clear_since_.reset(); + recovery_clear_confirmed_ = false; + } + + CMVR_LOG(INFO) << "[SelfCollisionMonitor] recovery requested event_id=" + << event_id << ", samples=" << path.size() + << ", max_joint_velocity_rad_s=" + << options.velocity + << ", max_joint_acceleration_rad_s2=" + << options.acceleration; + const auto playback_result = arm->recoverProtectiveStop(path, options); + if (!playback_result.ok()) { + std::lock_guard lock(mutex_); + if (latest_status_.recovery_state == ProtectiveRecoveryState::RECOVERING) { + latest_status_.recovery_state = ProtectiveRecoveryState::FAILED; + latest_status_.recovery_error = playback_result.message; + } + const std::string recovery_error = latest_status_.recovery_error; + recovery_cv_.notify_all(); + return device::Result::failure(playback_result.code, recovery_error); + } + + { + std::unique_lock lock(mutex_); + const auto clear_timeout = std::chrono::duration( + config_.recovery().stable_period_s() + 2.0); + const bool completed = recovery_cv_.wait_for(lock, clear_timeout, [&] { + return state_ != State::RUNNING || recovery_clear_confirmed_ || + latest_status_.recovery_state != ProtectiveRecoveryState::RECOVERING; + }); + if (!completed || !recovery_clear_confirmed_) { + if (latest_status_.recovery_state == ProtectiveRecoveryState::RECOVERING) { + latest_status_.recovery_state = ProtectiveRecoveryState::FAILED; + latest_status_.recovery_error = completed + ? "Protective recovery ended before the clear distance was confirmed" + : "Protective recovery clear-distance confirmation timed out"; + } + const std::string error = latest_status_.recovery_error; + lock.unlock(); + (void)arm->protectiveStop(); + return device::Result::failure( + device::ArmErrorCode::CommandFailed, error); + } + + latest_status_.stop_latched = false; + latest_status_.recovery_state = ProtectiveRecoveryState::SUCCEEDED; + latest_status_.recovery_error.clear(); + joint_history_.clear(); + joint_history_.push_back(path.front()); + recovery_path_.clear(); + latest_status_.recovery_sample_count = 0; + } + + const auto unlock_result = arm->unlockProtectiveStop(); + if (!unlock_result.ok()) { + std::lock_guard lock(mutex_); + latest_status_.stop_latched = true; + latest_status_.recovery_state = ProtectiveRecoveryState::FAILED; + latest_status_.recovery_error = + "Failed to unlock protective stop: " + unlock_result.message; + return device::Result::failure( + unlock_result.code, latest_status_.recovery_error); + } + + CMVR_LOG(INFO) << "[SelfCollisionMonitor] recovery completed event_id=" + << event_id << ", clear_distance_m=" + << config_.recovery().clear_distance_m(); + return device::Result::success(); +} + +void SelfCollisionMonitor::stop() +{ + auto* arm = &arm_; + bool cancel_recovery = false; + { + std::lock_guard lock(mutex_); + cancel_recovery = + latest_status_.recovery_state == ProtectiveRecoveryState::RECOVERING; + if (state_ != State::FAILED) { + state_ = State::STOPPED; + } + recovery_cv_.notify_all(); + } + if (cancel_recovery) { + (void)arm->protectiveStop(); + } +} + +SelfCollisionMonitor::State SelfCollisionMonitor::state() const +{ + std::lock_guard lock(mutex_); + return state_; +} + +std::string SelfCollisionMonitor::detailStatusString() const +{ + std::lock_guard lock(mutex_); + if (!last_error_.empty()) { + return std::string(monitorStateToString(state_)) + " " + last_error_; + } + std::ostringstream stream; + stream << monitorStateToString(state_) + << " level=" << safetyLevelToString(latest_status_.level) + << " stop_latched=" << latest_status_.stop_latched + << " event_id=" << latest_status_.event_id + << " recovery=" + << recoveryStateToString(latest_status_.recovery_state); + if (latest_status_.result.valid) { + stream << " distance_m=" << std::setprecision(6) + << latest_status_.result.minimum_distance_m + << " pair=" << latest_status_.result.first + << "/" << latest_status_.result.second; + } + if (!latest_status_.recovery_error.empty()) { + stream << " recovery_error=" << latest_status_.recovery_error; + } + return stream.str(); +} + +SelfCollisionStatus SelfCollisionMonitor::latestStatus() const +{ + std::lock_guard lock(mutex_); + return latest_status_; +} + +const char* SelfCollisionMonitor::safetyLevelToString(const CollisionSafetyLevel level) +{ + switch (level) { + case CollisionSafetyLevel::UNKNOWN: return "UNKNOWN"; + case CollisionSafetyLevel::SAFE: return "SAFE"; + case CollisionSafetyLevel::WARNING: return "WARNING"; + case CollisionSafetyLevel::STOP: return "STOP"; + } + return "UNKNOWN"; +} + +const char* SelfCollisionMonitor::recoveryStateToString( + const ProtectiveRecoveryState state) +{ + switch (state) { + case ProtectiveRecoveryState::IDLE: return "IDLE"; + case ProtectiveRecoveryState::AVAILABLE: return "AVAILABLE"; + case ProtectiveRecoveryState::RECOVERING: return "RECOVERING"; + case ProtectiveRecoveryState::SUCCEEDED: return "SUCCEEDED"; + case ProtectiveRecoveryState::FAILED: return "FAILED"; + } + return "UNKNOWN"; +} + +} // namespace cmvr::safety diff --git a/cmvr-es/service/grpc/action/tests/action_queue_test.cpp b/cmvr-es/service/grpc/action/tests/action_queue_test.cpp index 54a8da3f..edc2f15e 100644 --- a/cmvr-es/service/grpc/action/tests/action_queue_test.cpp +++ b/cmvr-es/service/grpc/action/tests/action_queue_test.cpp @@ -29,7 +29,7 @@ public: std::string typeName() const override { return "FakeActionQueueArm"; } bool stop() override { return stopMotion().ok(); } - device::RobotModel getRobotModel() const override { return model_; } + RobotModel getRobotModel() const override { return model_; } std::size_t getDof() const override { return model_.dof; } device::ArmState getRobotState() const override { return {}; } device::JointGroupState getJointState() const override { return {}; } @@ -204,7 +204,7 @@ private: : device::Result::success(); } - device::RobotModel model_; + RobotModel model_; mutable std::mutex mutex_; std::condition_variable cv_; std::vector calls_; diff --git a/cmvr-es/simulate/mujoco/mujoco_world/include/mujoco_world.h b/cmvr-es/simulate/mujoco/mujoco_world/include/mujoco_world.h index 1ebd4bf9..7ec76dee 100644 --- a/cmvr-es/simulate/mujoco/mujoco_world/include/mujoco_world.h +++ b/cmvr-es/simulate/mujoco/mujoco_world/include/mujoco_world.h @@ -2,6 +2,7 @@ #define CMVR_ES_MUJOCO_WORLD_H #include +#include #include #include #include @@ -46,6 +47,12 @@ public: bool isLoaded() const; bool isRunning() const; double timestep() const; + // Pair one online control update with one physics step. The caller may + // read feedback and submit commands between begin/end without a world lock. + // finished=false submits this cycle; finished=true also unregisters the + // controller and must be called on every exit, even between cycles. + double beginControlCycle(const std::string& controller); + void endControlCycle(const std::string& controller, bool finished); const std::string& lastError() const; const std::string& modelPath() const; @@ -54,6 +61,9 @@ public: bool getJointPosition(const std::string& joint_name, double& position) const; bool getJointVelocity(const std::string& joint_name, double& velocity) const; + bool getJointStates(const std::vector& joint_names, + std::vector& positions, + std::vector& velocities) const; bool setJointPosition(const std::string& joint_name, double position); bool setJointVelocity(const std::string& joint_name, double velocity); bool setJointTargetPosition(const std::string& joint_name, double position); @@ -66,6 +76,8 @@ public: const std::vector& positions, const std::vector& velocities); bool setJointTargetVelocity(const std::string& joint_name, double velocity); + bool setJointTargetVelocities(const std::vector& joint_names, + const std::vector& velocities); mjModel* model(); mjData* data(); @@ -110,6 +122,15 @@ private: void applyDirectControlLocked(double dt); mutable std::mutex mutex_; + struct ControlCycle { + bool granted{false}; + bool acquired{false}; + bool submitted{false}; + }; + std::mutex control_mutex_; + std::condition_variable control_cv_; + std::unordered_map control_cycles_; + bool control_window_open_{false}; Options options_; mjModel* model_{nullptr}; mjData* data_{nullptr}; diff --git a/cmvr-es/simulate/mujoco/mujoco_world/src/mujoco_world.cpp b/cmvr-es/simulate/mujoco/mujoco_world/src/mujoco_world.cpp index 0f29ad02..b5f1d873 100644 --- a/cmvr-es/simulate/mujoco/mujoco_world/src/mujoco_world.cpp +++ b/cmvr-es/simulate/mujoco/mujoco_world/src/mujoco_world.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include "common/base/logging/logger.h" @@ -167,11 +168,56 @@ bool MujocoWorld::start() void MujocoWorld::stop() { - stop_requested_.store(true); + { + std::lock_guard lock(control_mutex_); + stop_requested_.store(true); + } + control_cv_.notify_all(); if (simulation_thread_.joinable()) { simulation_thread_.join(); } running_.store(false); + std::lock_guard lock(control_mutex_); + control_cycles_.clear(); + control_window_open_ = false; +} + +double MujocoWorld::beginControlCycle(const std::string& controller) +{ + const double dt = timestep(); + std::unique_lock lock(control_mutex_); + if (!running_.load() || stop_requested_.load() || controller.empty()) { + throw std::runtime_error("MuJoCo control cycle is unavailable"); + } + auto inserted = control_cycles_.try_emplace(controller); + if (inserted.second && control_window_open_) inserted.first->second.granted = true; + const bool ready = control_cv_.wait_for(lock, std::chrono::seconds(1), [&] { + const auto it = control_cycles_.find(controller); + return stop_requested_.load() || !running_.load() || + (it != control_cycles_.end() && it->second.granted && !it->second.acquired); + }); + if (!ready || stop_requested_.load() || !running_.load()) { + control_cycles_.erase(controller); + control_cv_.notify_all(); + throw std::runtime_error("MuJoCo control cycle stopped or timed out"); + } + control_cycles_.at(controller).acquired = true; + return dt; +} + +void MujocoWorld::endControlCycle(const std::string& controller, const bool finished) +{ + std::lock_guard lock(control_mutex_); + const auto it = control_cycles_.find(controller); + if (it == control_cycles_.end()) return; + if (finished) { + control_cycles_.erase(it); + } else if (it->second.acquired) { + it->second.acquired = false; + it->second.granted = false; + it->second.submitted = true; + } + control_cv_.notify_all(); } void MujocoWorld::reset() @@ -277,6 +323,35 @@ bool MujocoWorld::setJointPosition(const std::string& joint_name, const double p return true; } +bool MujocoWorld::getJointStates(const std::vector& joint_names, + std::vector& positions, + std::vector& velocities) const +{ + if (joint_names.empty() || &positions == &velocities) { + return false; + } + std::lock_guard lock(mutex_); + std::vector joints; + joints.reserve(joint_names.size()); + for (const auto& name : joint_names) { + const JointHandle* joint = nullptr; + if (!findJointLocked(name, joint) || + std::find(joints.begin(), joints.end(), joint) != joints.end() || + !std::isfinite(data_->qpos[joint->qpos_adr]) || + !std::isfinite(data_->qvel[joint->qvel_adr])) { + return false; + } + joints.push_back(joint); + } + positions.resize(joints.size()); + velocities.resize(joints.size()); + for (std::size_t i = 0; i < joints.size(); ++i) { + positions[i] = data_->qpos[joints[i]->qpos_adr]; + velocities[i] = data_->qvel[joints[i]->qvel_adr]; + } + return true; +} + bool MujocoWorld::setJointVelocity(const std::string& joint_name, const double velocity) { std::lock_guard lock(mutex_); @@ -410,6 +485,35 @@ bool MujocoWorld::setJointTargetVelocity(const std::string& joint_name, const do return true; } +bool MujocoWorld::setJointTargetVelocities(const std::vector& joint_names, + const std::vector& velocities) +{ + if (joint_names.empty() || joint_names.size() != velocities.size()) { + return false; + } + std::lock_guard lock(mutex_); + std::vector joints; + joints.reserve(joint_names.size()); + for (std::size_t i = 0; i < joint_names.size(); ++i) { + JointHandle* joint = nullptr; + if (!std::isfinite(velocities[i]) || !findJointLocked(joint_names[i], joint) || + std::find(joints.begin(), joints.end(), joint) != joints.end()) { + return false; + } + joints.push_back(joint); + } + // Validate the entire batch before changing any target or control mode. + for (std::size_t i = 0; i < joints.size(); ++i) { + auto* joint = joints[i]; + if (joint->mode != TargetMode::DirectVelocity) { + joint->position_reference = data_->qpos[joint->qpos_adr]; + } + joint->target_velocity = velocities[i]; + joint->mode = TargetMode::DirectVelocity; + } + return true; +} + mjModel* MujocoWorld::model() { return model_; @@ -621,6 +725,22 @@ void MujocoWorld::simulationLoop() while (!stop_requested_.load()) { { + std::unique_lock control_lock(control_mutex_); + control_window_open_ = true; + for (auto& item : control_cycles_) { + item.second.granted = true; + item.second.submitted = false; + } + control_cv_.notify_all(); + control_cv_.wait(control_lock, [&] { + return stop_requested_.load() || std::all_of( + control_cycles_.begin(), control_cycles_.end(), + [](const auto& item) { return item.second.submitted; }); + }); + control_window_open_ = false; + if (stop_requested_.load()) break; + // Keep the cycle gate closed until this complete command has been + // consumed; the controller then observes the resulting feedback. std::lock_guard lock(mutex_); if (model_ == nullptr || data_ == nullptr) { break; @@ -640,6 +760,7 @@ void MujocoWorld::simulationLoop() running_.store(false); CMVR_LOG(INFO) << "[MujocoWorld] simulation stopped"; + control_cv_.notify_all(); } void MujocoWorld::applyControlLocked() diff --git a/cmvr-es/task/CMakeLists.txt b/cmvr-es/task/CMakeLists.txt index b10b0978..8cdabc3c 100644 --- a/cmvr-es/task/CMakeLists.txt +++ b/cmvr-es/task/CMakeLists.txt @@ -11,7 +11,7 @@ target_link_libraries(task cmvr_es::common cmvr_es::ik_solver cmvr_es::base_motion - cmvr_es::self_collision_checker + cmvr_es::self_collision_monitor PRIVATE cmvr_es::device_manager ) @@ -25,6 +25,8 @@ add_executable(touch_screen_task_test target_link_libraries(touch_screen_task_test PRIVATE cmvr_es::task + cmvr_es::joint_path_planner + cmvr_es::collision_checker cmvr_es::device::arm cmvr_es::device::motor_manager cmvr_es::device::mujoco_motor_driver diff --git a/cmvr-es/task/self_collision_task/include/self_collision_task.h b/cmvr-es/task/self_collision_task/include/self_collision_task.h index 938207e8..527b39f5 100644 --- a/cmvr-es/task/self_collision_task/include/self_collision_task.h +++ b/cmvr-es/task/self_collision_task/include/self_collision_task.h @@ -1,53 +1,20 @@ #ifndef CMVR_ES_SELF_COLLISION_TASK_H #define CMVR_ES_SELF_COLLISION_TASK_H -#include -#include -#include #include -#include -#include #include -#include -#include "algorithms/collision_detection/self_collision/include/distance_sampling_policy.h" -#include "algorithms/collision_detection/self_collision/include/self_collision_checker.h" #include "cmvr/config/self_collision_task_config/self_collision_task_config.pb.h" -#include "devices/arm/robot_arm.h" +#include "safety/self_collision/include/self_collision_monitor.h" #include "task/task.h" namespace cmvr::task { -enum class CollisionSafetyLevel { - UNKNOWN = 0, - SAFE, - WARNING, - STOP, -}; - -enum class ProtectiveRecoveryState { - IDLE = 0, - AVAILABLE, - RECOVERING, - SUCCEEDED, - FAILED, -}; - -struct SelfCollisionTaskStatus { - CollisionSafetyLevel level{CollisionSafetyLevel::UNKNOWN}; - SelfCollisionResult result; - bool stop_latched{false}; - std::uint64_t event_id{0}; - ProtectiveRecoveryState recovery_state{ProtectiveRecoveryState::IDLE}; - std::size_t recovery_sample_count{0}; - std::string recovery_error; -}; - class SelfCollisionTask final : public Task { public: explicit SelfCollisionTask(const config::SelfCollisionTaskConfig& config); - const std::string& id() const override { return id_; } + const std::string& id() const override { return config_.id(); } TaskRunMode runMode() const override { return TaskRunMode::PERIODIC_STEP; } bool init() override; @@ -56,41 +23,22 @@ public: void stop() override; TaskState state() const override; - bool isBusy() const override; - bool isFinished() const override; - bool isFailed() const override; - std::string stateString() const override; + bool isBusy() const override { return state() == TaskState::RUNNING; } + bool isFinished() const override { return state() == TaskState::STOPPED; } + bool isFailed() const override { return state() == TaskState::FAILED; } + std::string stateString() const override { return taskStateToString(state()); } std::string detailStatusString() const override; - SelfCollisionTaskStatus latestStatus() const; + safety::SelfCollisionStatus latestStatus() const; device::Result requestRecovery(std::uint64_t event_id); private: - static bool validateConfig(const config::SelfCollisionTaskConfig& config, - std::string* error); - static const char* safetyLevelToString(CollisionSafetyLevel level); - static const char* recoveryStateToString(ProtectiveRecoveryState state); - void recordJointSample_(const device::JointGroupState& joint_state, - DistanceSamplingPolicy::Clock::time_point now); - config::SelfCollisionTaskConfig config_; - std::string id_; + // Bound by init() before scheduling; the arm outlives the monitor. std::shared_ptr arm_; - SelfCollisionChecker checker_; - DistanceSamplingPolicy sampling_; - - mutable std::mutex mutex_; - std::condition_variable recovery_cv_; - TaskState state_{TaskState::UNINITIALIZED}; - SelfCollisionTaskStatus latest_status_{}; - std::deque joint_history_; - device::JointTrajectory recovery_path_; - DistanceSamplingPolicy::Clock::time_point history_epoch_{}; - std::optional recovery_clear_since_; - double recovery_best_distance_m_{0.0}; - bool recovery_clear_confirmed_{false}; - std::uint64_t next_event_id_{1}; - std::string last_error_; + std::unique_ptr monitor_; + TaskState init_state_{TaskState::UNINITIALIZED}; + std::string init_error_; }; } // namespace cmvr::task diff --git a/cmvr-es/task/self_collision_task/src/self_collision_task.cpp b/cmvr-es/task/self_collision_task/src/self_collision_task.cpp index 00464c60..9c7b064a 100644 --- a/cmvr-es/task/self_collision_task/src/self_collision_task.cpp +++ b/cmvr-es/task/self_collision_task/src/self_collision_task.cpp @@ -1,597 +1,106 @@ #include "task/self_collision_task/include/self_collision_task.h" -#include -#include -#include -#include -#include -#include - -#include "common/base/logging/logger.h" #include "manager/device_manager/include/device_manager.h" namespace cmvr::task { SelfCollisionTask::SelfCollisionTask(const config::SelfCollisionTaskConfig& config) - : config_(config), - id_(config.id()) + : config_(config) { } -bool SelfCollisionTask::validateConfig(const config::SelfCollisionTaskConfig& config, - std::string* error) -{ - auto fail = [error](const std::string& message) { - if (error) { - *error = message; - } - return false; - }; - - if (config.id().empty()) { - return fail("Self-collision task id is empty"); - } - if (config.arm_id().empty()) { - return fail("Self-collision task arm_id is empty"); - } - if (config.checker().urdf_path().empty()) { - return fail("Self-collision checker URDF path is empty"); - } - const auto& sampling = config.sampling(); - if (!std::isfinite(sampling.max_geometry_displacement_m()) || - sampling.max_geometry_displacement_m() <= 0.0) { - return fail("max_geometry_displacement_m must be finite and positive"); - } - if (!std::isfinite(sampling.max_check_period_s()) || - sampling.max_check_period_s() <= 0.0) { - return fail("max_check_period_s must be finite and positive"); - } - - const auto& safety = config.safety(); - if (!std::isfinite(safety.stop_distance_m()) || safety.stop_distance_m() < 0.0) { - return fail("stop_distance_m must be finite and non-negative"); - } - if (!std::isfinite(safety.warning_distance_m()) || - safety.warning_distance_m() < safety.stop_distance_m()) { - return fail("warning_distance_m must be finite and not less than stop_distance_m"); - } - const auto& recovery = config.recovery(); - if (!std::isfinite(recovery.clear_distance_m()) || - recovery.clear_distance_m() <= safety.warning_distance_m()) { - return fail("recovery clear_distance_m must be finite and greater than warning_distance_m"); - } - if (!std::isfinite(recovery.stable_period_s()) || - recovery.stable_period_s() <= 0.0) { - return fail("recovery stable_period_s must be finite and positive"); - } - if (!std::isfinite(recovery.max_joint_velocity_rad_s()) || - recovery.max_joint_velocity_rad_s() <= 0.0) { - return fail("recovery max_joint_velocity_rad_s must be finite and positive"); - } - if (!std::isfinite(recovery.max_joint_acceleration_rad_s2()) || - recovery.max_joint_acceleration_rad_s2() <= 0.0) { - return fail("recovery max_joint_acceleration_rad_s2 must be finite and positive"); - } - if (!std::isfinite(recovery.history_duration_s()) || - recovery.history_duration_s() <= 0.0) { - return fail("recovery history_duration_s must be finite and positive"); - } - if (!std::isfinite(recovery.max_distance_regression_m()) || - recovery.max_distance_regression_m() < 0.0) { - return fail("recovery max_distance_regression_m must be finite and non-negative"); - } - for (const auto& pair : config.checker().ignored_pairs()) { - if (pair.first().empty() || pair.second().empty() || pair.first() == pair.second()) { - return fail("ignored_pairs entries require two different non-empty links"); - } - } - if (error) { - error->clear(); - } - return true; -} - bool SelfCollisionTask::init() { - std::string error; - if (!validateConfig(config_, &error)) { - std::lock_guard lock(mutex_); - last_error_ = std::move(error); - state_ = TaskState::FAILED; + monitor_.reset(); + arm_.reset(); + init_error_.clear(); + init_state_ = TaskState::FAILED; + if (config_.id().empty()) { + init_error_ = "Self-collision task id is empty"; + return false; + } + if (config_.arm_id().empty()) { + init_error_ = "Self-collision task arm_id is empty"; return false; } - auto arm = device::DeviceManager::getInstance().getDevice( + arm_ = device::DeviceManager::getInstance().getDevice( config_.arm_id()); - if (!arm) { - std::lock_guard lock(mutex_); - last_error_ = "Robot arm not found: " + config_.arm_id(); - state_ = TaskState::FAILED; + if (!arm_) { + init_error_ = "Robot arm not found: " + config_.arm_id(); return false; } - const auto model = arm->getRobotModel(); - if (!model.valid()) { - std::lock_guard lock(mutex_); - last_error_ = "Robot arm model is invalid: " + config_.arm_id(); - state_ = TaskState::FAILED; - return false; - } - - SelfCollisionOptions checker_options; - checker_options.ignored_pairs.reserve(config_.checker().ignored_pairs_size()); - for (const auto& pair : config_.checker().ignored_pairs()) { - checker_options.ignored_pairs.push_back({pair.first(), pair.second()}); - } - if (!checker_.init(config_.checker().urdf_path(), - model.joint_names, - checker_options, - &error)) { - std::lock_guard lock(mutex_); - last_error_ = std::move(error); - state_ = TaskState::FAILED; - return false; - } - - const DistanceSamplingOptions sampling_options{ - config_.sampling().max_geometry_displacement_m(), - config_.sampling().max_check_period_s(), - }; - if (!sampling_.configure(sampling_options, &error)) { - std::lock_guard lock(mutex_); - last_error_ = std::move(error); - state_ = TaskState::FAILED; - return false; - } - - { - std::lock_guard lock(mutex_); - arm_ = std::move(arm); - latest_status_ = {}; - joint_history_.clear(); - recovery_path_.clear(); - history_epoch_ = DistanceSamplingPolicy::Clock::now(); - recovery_clear_since_.reset(); - recovery_best_distance_m_ = 0.0; - recovery_clear_confirmed_ = false; - next_event_id_ = 1; - last_error_.clear(); - state_ = TaskState::IDLE; - } - CMVR_LOG(INFO) << "[SelfCollisionTask] Initialized id=" << id_ - << ", arm=" << config_.arm_id() - << ", dof=" << checker_.dof() - << ", active_pairs=" << checker_.activePairCount(); - return true; + config::SelfCollisionMonitorConfig monitor_config; + *monitor_config.mutable_checker() = config_.checker(); + *monitor_config.mutable_sampling() = config_.sampling(); + *monitor_config.mutable_safety() = config_.safety(); + *monitor_config.mutable_recovery() = config_.recovery(); + monitor_ = std::make_unique(monitor_config, *arm_); + return monitor_->init(); } bool SelfCollisionTask::start() { - std::lock_guard lock(mutex_); - if (state_ == TaskState::RUNNING) { - return true; - } - if (state_ != TaskState::IDLE && state_ != TaskState::STOPPED) { - last_error_ = "Self-collision task is not initialized"; - state_ = TaskState::FAILED; + if (!monitor_) { + init_error_ = "Self-collision task is not initialized"; + init_state_ = TaskState::FAILED; return false; } - sampling_.reset(); - latest_status_ = {}; - joint_history_.clear(); - recovery_path_.clear(); - history_epoch_ = DistanceSamplingPolicy::Clock::now(); - recovery_clear_since_.reset(); - recovery_best_distance_m_ = 0.0; - recovery_clear_confirmed_ = false; - last_error_.clear(); - state_ = TaskState::RUNNING; - return true; + return monitor_->start(); } -bool SelfCollisionTask::step(const double dt) +bool SelfCollisionTask::step(double /*dt*/) { - (void)dt; - std::shared_ptr arm; - { - std::lock_guard lock(mutex_); - if (state_ != TaskState::RUNNING) { - return false; - } - arm = arm_; - } - - const auto fail_monitoring = [&](std::string error) { - bool cancel_recovery = false; - { - std::lock_guard lock(mutex_); - cancel_recovery = - latest_status_.recovery_state == ProtectiveRecoveryState::RECOVERING; - if (cancel_recovery) { - latest_status_.recovery_state = ProtectiveRecoveryState::FAILED; - latest_status_.recovery_error = error; - } - last_error_ = std::move(error); - state_ = TaskState::FAILED; - recovery_cv_.notify_all(); - } - if (cancel_recovery) { - (void)arm->protectiveStop(); - } - return false; - }; - - const auto joint_state = arm->getJointState(); - const auto model = arm->getRobotModel(); - if (!joint_state.validForModel(model)) { - return fail_monitoring("Robot arm returned an invalid joint state"); - } - - const auto now = DistanceSamplingPolicy::Clock::now(); - recordJointSample_(joint_state, now); - - CollisionGeometrySnapshot snapshot; - std::string error; - if (!checker_.makeSnapshot(joint_state.position, &snapshot, &error)) { - return fail_monitoring(std::move(error)); - } - - if (!sampling_.shouldCheck(snapshot, now)) { - return true; - } - - SelfCollisionResult result = checker_.check(snapshot); - if (!result.valid) { - return fail_monitoring( - result.error.empty() ? "Self-collision distance check failed" : result.error); - } - sampling_.markChecked(snapshot, now); - - CollisionSafetyLevel level = CollisionSafetyLevel::SAFE; - if (result.minimum_distance_m <= config_.safety().stop_distance_m()) { - level = CollisionSafetyLevel::STOP; - } else if (result.minimum_distance_m <= config_.safety().warning_distance_m()) { - level = CollisionSafetyLevel::WARNING; - } - - bool trigger_stop = false; - bool abort_recovery = false; - CollisionSafetyLevel previous_level = CollisionSafetyLevel::UNKNOWN; - { - std::lock_guard lock(mutex_); - if (state_ != TaskState::RUNNING) { - return true; - } - previous_level = latest_status_.level; - latest_status_.level = level; - latest_status_.result = result; - - if (latest_status_.recovery_state == ProtectiveRecoveryState::RECOVERING) { - if (arm->isEmergencyStopped()) { - latest_status_.recovery_state = ProtectiveRecoveryState::FAILED; - latest_status_.recovery_error = - "Protective recovery interrupted by emergency stop"; - recovery_clear_since_.reset(); - abort_recovery = true; - recovery_cv_.notify_all(); - } else if (result.minimum_distance_m + - config_.recovery().max_distance_regression_m() < - recovery_best_distance_m_) { - std::ostringstream stream; - stream << "Protective recovery distance regressed from " - << recovery_best_distance_m_ << " m to " - << result.minimum_distance_m << " m"; - latest_status_.recovery_state = ProtectiveRecoveryState::FAILED; - latest_status_.recovery_error = stream.str(); - recovery_clear_since_.reset(); - abort_recovery = true; - recovery_cv_.notify_all(); - } else { - recovery_best_distance_m_ = std::max( - recovery_best_distance_m_, result.minimum_distance_m); - if (result.minimum_distance_m >= - config_.recovery().clear_distance_m()) { - if (!recovery_clear_since_) { - recovery_clear_since_ = now; - } else if (std::chrono::duration( - now - *recovery_clear_since_).count() >= - config_.recovery().stable_period_s()) { - recovery_clear_confirmed_ = true; - recovery_cv_.notify_all(); - } - } else { - recovery_clear_since_.reset(); - recovery_clear_confirmed_ = false; - } - } - } else if (level == CollisionSafetyLevel::STOP && - !latest_status_.stop_latched) { - latest_status_.stop_latched = true; - latest_status_.event_id = next_event_id_++; - latest_status_.recovery_state = ProtectiveRecoveryState::AVAILABLE; - latest_status_.recovery_error.clear(); - recovery_path_.assign(joint_history_.begin(), joint_history_.end()); - latest_status_.recovery_sample_count = recovery_path_.size(); - trigger_stop = true; - } else if (!latest_status_.stop_latched && - result.minimum_distance_m >= - config_.recovery().clear_distance_m()) { - joint_history_.clear(); - device::JointTrajectoryPoint sample; - sample.time_s = std::chrono::duration(now - history_epoch_).count(); - sample.position = joint_state.position; - sample.velocity = joint_state.velocity; - joint_history_.push_back(std::move(sample)); - } - } - - if (level != previous_level) { - if (level == CollisionSafetyLevel::SAFE) { - CMVR_LOG(INFO) << "[SelfCollisionTask] level=" << safetyLevelToString(level) - << ", distance_m=" << result.minimum_distance_m - << ", pair=" << result.first << "/" << result.second; - } else { - CMVR_LOG(WARNING) << "[SelfCollisionTask] level=" << safetyLevelToString(level) - << ", distance_m=" << result.minimum_distance_m - << ", pair=" << result.first << "/" << result.second; - } - } - - if (abort_recovery) { - (void)arm->protectiveStop(); - } else if (trigger_stop) { - const auto stop_result = arm->protectiveStop(); - if (!stop_result.ok()) { - std::lock_guard lock(mutex_); - last_error_ = "Protective stop failed: " + stop_result.message; - state_ = TaskState::FAILED; - return false; - } - } - return true; -} - -void SelfCollisionTask::recordJointSample_( - const device::JointGroupState& joint_state, - const DistanceSamplingPolicy::Clock::time_point now) -{ - std::lock_guard lock(mutex_); - if (state_ != TaskState::RUNNING || latest_status_.stop_latched) { - return; - } - - device::JointTrajectoryPoint sample; - sample.time_s = std::chrono::duration(now - history_epoch_).count(); - sample.position = joint_state.position; - sample.velocity = joint_state.velocity; - if (!joint_history_.empty() && sample.time_s <= joint_history_.back().time_s) { - return; - } - joint_history_.push_back(std::move(sample)); - - const double oldest_time_s = joint_history_.back().time_s - - config_.recovery().history_duration_s(); - while (joint_history_.size() > 1 && - joint_history_.front().time_s < oldest_time_s) { - joint_history_.pop_front(); - } -} - -device::Result SelfCollisionTask::requestRecovery(const std::uint64_t event_id) -{ - std::shared_ptr arm; - device::JointTrajectory path; - device::MotionOptions options; - { - std::lock_guard lock(mutex_); - if (state_ != TaskState::RUNNING) { - return device::Result::failure( - device::ArmErrorCode::RobotNotReady, - "Protective recovery rejected: collision task is not running"); - } - if (!latest_status_.stop_latched || - latest_status_.recovery_state != ProtectiveRecoveryState::AVAILABLE) { - return device::Result::failure( - device::ArmErrorCode::CommandRejected, - "Protective recovery rejected: no recoverable collision stop is available"); - } - if (event_id == 0 || event_id != latest_status_.event_id) { - return device::Result::failure( - device::ArmErrorCode::InvalidArgument, - "Protective recovery rejected: event_id does not match the active stop"); - } - if (!arm_ || !arm_->isProtectiveStopped() || arm_->isEmergencyStopped()) { - return device::Result::failure( - arm_ && arm_->isEmergencyStopped() - ? device::ArmErrorCode::RobotInEmergencyStop - : device::ArmErrorCode::RobotNotReady, - "Protective recovery rejected: arm safety state is invalid"); - } - if (recovery_path_.size() < 2) { - latest_status_.recovery_state = ProtectiveRecoveryState::FAILED; - latest_status_.recovery_error = - "Protective recovery path contains fewer than two samples"; - return device::Result::failure( - device::ArmErrorCode::CommandRejected, - latest_status_.recovery_error); - } - - arm = arm_; - path = recovery_path_; - options.velocity = config_.recovery().max_joint_velocity_rad_s(); - options.acceleration = - config_.recovery().max_joint_acceleration_rad_s2(); - latest_status_.recovery_state = ProtectiveRecoveryState::RECOVERING; - latest_status_.recovery_error.clear(); - recovery_best_distance_m_ = latest_status_.result.minimum_distance_m; - recovery_clear_since_.reset(); - recovery_clear_confirmed_ = false; - } - - CMVR_LOG(INFO) << "[SelfCollisionTask] recovery requested event_id=" - << event_id << ", samples=" << path.size() - << ", max_joint_velocity_rad_s=" - << options.velocity - << ", max_joint_acceleration_rad_s2=" - << options.acceleration; - const auto playback_result = arm->recoverProtectiveStop(path, options); - if (!playback_result.ok()) { - std::lock_guard lock(mutex_); - if (latest_status_.recovery_state == ProtectiveRecoveryState::RECOVERING) { - latest_status_.recovery_state = ProtectiveRecoveryState::FAILED; - latest_status_.recovery_error = playback_result.message; - } - const std::string recovery_error = latest_status_.recovery_error; - recovery_cv_.notify_all(); - return device::Result::failure(playback_result.code, recovery_error); - } - - { - std::unique_lock lock(mutex_); - const auto clear_timeout = std::chrono::duration( - config_.recovery().stable_period_s() + 2.0); - const bool completed = recovery_cv_.wait_for(lock, clear_timeout, [&] { - return state_ != TaskState::RUNNING || recovery_clear_confirmed_ || - latest_status_.recovery_state != ProtectiveRecoveryState::RECOVERING; - }); - if (!completed || !recovery_clear_confirmed_) { - if (latest_status_.recovery_state == ProtectiveRecoveryState::RECOVERING) { - latest_status_.recovery_state = ProtectiveRecoveryState::FAILED; - latest_status_.recovery_error = completed - ? "Protective recovery ended before the clear distance was confirmed" - : "Protective recovery clear-distance confirmation timed out"; - } - const std::string error = latest_status_.recovery_error; - lock.unlock(); - (void)arm->protectiveStop(); - return device::Result::failure( - device::ArmErrorCode::CommandFailed, error); - } - - latest_status_.stop_latched = false; - latest_status_.recovery_state = ProtectiveRecoveryState::SUCCEEDED; - latest_status_.recovery_error.clear(); - joint_history_.clear(); - joint_history_.push_back(path.front()); - recovery_path_.clear(); - latest_status_.recovery_sample_count = 0; - } - - const auto unlock_result = arm->unlockProtectiveStop(); - if (!unlock_result.ok()) { - std::lock_guard lock(mutex_); - latest_status_.stop_latched = true; - latest_status_.recovery_state = ProtectiveRecoveryState::FAILED; - latest_status_.recovery_error = - "Failed to unlock protective stop: " + unlock_result.message; - return device::Result::failure( - unlock_result.code, latest_status_.recovery_error); - } - - CMVR_LOG(INFO) << "[SelfCollisionTask] recovery completed event_id=" - << event_id << ", clear_distance_m=" - << config_.recovery().clear_distance_m(); - return device::Result::success(); + return monitor_ && monitor_->step(); } void SelfCollisionTask::stop() { - std::shared_ptr arm; - bool cancel_recovery = false; - { - std::lock_guard lock(mutex_); - cancel_recovery = - latest_status_.recovery_state == ProtectiveRecoveryState::RECOVERING; - arm = arm_; - if (state_ != TaskState::FAILED) { - state_ = TaskState::STOPPED; - } - recovery_cv_.notify_all(); - } - if (cancel_recovery && arm) { - (void)arm->protectiveStop(); + if (monitor_) { + monitor_->stop(); + } else if (init_state_ != TaskState::FAILED) { + init_state_ = TaskState::STOPPED; } } TaskState SelfCollisionTask::state() const { - std::lock_guard lock(mutex_); - return state_; -} - -bool SelfCollisionTask::isBusy() const -{ - return state() == TaskState::RUNNING; -} - -bool SelfCollisionTask::isFinished() const -{ - return state() == TaskState::STOPPED; -} - -bool SelfCollisionTask::isFailed() const -{ - return state() == TaskState::FAILED; -} - -std::string SelfCollisionTask::stateString() const -{ - return taskStateToString(state()); + if (!monitor_) { + return init_state_; + } + using State = safety::SelfCollisionMonitor::State; + switch (monitor_->state()) { + case State::UNINITIALIZED: return TaskState::UNINITIALIZED; + case State::IDLE: return TaskState::IDLE; + case State::RUNNING: return TaskState::RUNNING; + case State::STOPPED: return TaskState::STOPPED; + case State::FAILED: return TaskState::FAILED; + } + return TaskState::FAILED; } std::string SelfCollisionTask::detailStatusString() const { - std::lock_guard lock(mutex_); - if (!last_error_.empty()) { - return std::string(taskStateToString(state_)) + " " + last_error_; + if (monitor_) { + return monitor_->detailStatusString(); } - std::ostringstream stream; - stream << taskStateToString(state_) - << " level=" << safetyLevelToString(latest_status_.level) - << " stop_latched=" << latest_status_.stop_latched - << " event_id=" << latest_status_.event_id - << " recovery=" - << recoveryStateToString(latest_status_.recovery_state); - if (latest_status_.result.valid) { - stream << " distance_m=" << std::setprecision(6) - << latest_status_.result.minimum_distance_m - << " pair=" << latest_status_.result.first - << "/" << latest_status_.result.second; - } - if (!latest_status_.recovery_error.empty()) { - stream << " recovery_error=" << latest_status_.recovery_error; - } - return stream.str(); + return init_error_.empty() ? stateString() : stateString() + " " + init_error_; } -SelfCollisionTaskStatus SelfCollisionTask::latestStatus() const +safety::SelfCollisionStatus SelfCollisionTask::latestStatus() const { - std::lock_guard lock(mutex_); - return latest_status_; + return monitor_ ? monitor_->latestStatus() : safety::SelfCollisionStatus{}; } -const char* SelfCollisionTask::safetyLevelToString(const CollisionSafetyLevel level) +device::Result SelfCollisionTask::requestRecovery(const std::uint64_t event_id) { - switch (level) { - case CollisionSafetyLevel::UNKNOWN: return "UNKNOWN"; - case CollisionSafetyLevel::SAFE: return "SAFE"; - case CollisionSafetyLevel::WARNING: return "WARNING"; - case CollisionSafetyLevel::STOP: return "STOP"; + if (!monitor_) { + return device::Result::failure( + device::ArmErrorCode::RobotNotReady, + "Protective recovery rejected: collision task is not initialized"); } - return "UNKNOWN"; -} - -const char* SelfCollisionTask::recoveryStateToString( - const ProtectiveRecoveryState state) -{ - switch (state) { - case ProtectiveRecoveryState::IDLE: return "IDLE"; - case ProtectiveRecoveryState::AVAILABLE: return "AVAILABLE"; - case ProtectiveRecoveryState::RECOVERING: return "RECOVERING"; - case ProtectiveRecoveryState::SUCCEEDED: return "SUCCEEDED"; - case ProtectiveRecoveryState::FAILED: return "FAILED"; - } - return "UNKNOWN"; + return monitor_->requestRecovery(event_id); } } // namespace cmvr::task diff --git a/cmvr-es/task/touch_screen_task/include/touch_screen_task.h b/cmvr-es/task/touch_screen_task/include/touch_screen_task.h index 4e8decfc..4a9009c1 100644 --- a/cmvr-es/task/touch_screen_task/include/touch_screen_task.h +++ b/cmvr-es/task/touch_screen_task/include/touch_screen_task.h @@ -4,8 +4,10 @@ #define CMVR_ES_TOUCH_SCREEN_TASK_H #include +#include #include #include +#include #include #include #include @@ -36,7 +38,9 @@ public: DWELLING, // 已检测到接触,保持当前位置短暂停留。 RETRACTING, // 回退阶段:沿设定回退方向离开屏幕。 DONE, // 整个流程成功完成。 - FAILED // 流程失败并已停止。 + FAILED, // 流程失败并已停止。 + PREPARING, // 视觉定位预接近目标。 + APPROACHING // MoveP 预接近,完成后进入视觉对齐。 }; enum class Status { @@ -59,7 +63,11 @@ public: STOPPED, // 被外部 stop() 主动停止。 ROBOT_STATE_FAILED, // 读取机器人状态失败。 ROBOT_COMMAND_FAILED, // 向机器人下发控制命令失败。 - TASK_BUSY // 已有触屏流程正在运行,新的 touch 请求被拒绝。 + TASK_BUSY, // 已有触屏流程正在运行,新的 touch 请求被拒绝。 + PREPARING, + APPROACHING, + APPROACH_FAILED, + APPROACH_TIMEOUT }; explicit TouchScreenTask(const cmvr::config::TouchScreenTaskConfig& cfg); @@ -116,8 +124,22 @@ private: bool isBusyUnlocked() const; bool startFromPixelUnlocked(int u, int v); void stopUnlocked(); + void resetRunState(); bool applyConfig(); + bool stepPreparing(); + bool stepApproaching(); + void cancelApproach(); bool stepAligning(double dt); + // Perception helpers return readiness; waiting keeps stepAligning active. + bool updateAlignmentAnchor(Eigen::Vector3d& p_target_G); + bool updateAlignmentTcpPose(); + bool updatePbvsTarget(const Eigen::Vector3d& p_target_G, + const Eigen::Matrix4d& T_G_P); + bool mapAlignmentCommandToBase(const Eigen::Matrix4d& T_G_P, + const PbvsController::Output& output, + device::CartesianVelocity& twist_B); + bool applyAlignmentCommand(const PbvsController::Output& output, + const device::CartesianVelocity& twist_B); bool stepTouching(); bool stepDwelling(); bool stepRetracting(); @@ -125,8 +147,7 @@ private: void stopPbvsMotion(); bool buildInitJointPositions(std::vector& positions_out) const; bool isAtInitPosition(const std::vector& positions) const; - bool moveToInitPositionBeforeStartIfEnabled(); - bool moveToInitPositionIfEnabled() const; + bool moveToInitPositionIfEnabled(bool enabled, bool use_move_j = false); bool readCurrentTouchPointPositionBase(Eigen::Vector3d& p_out) const; void logTouchingSpeedLState() const; @@ -147,6 +168,9 @@ private: private: mutable std::mutex mutex_; + // The motion worker captures values only; it never takes the task mutex. + std::future approach_motion_; + std::shared_ptr> approach_cancel_; // The display worker never takes mutex_ or uses the PBVS perception state. std::mutex coordinate_overlay_mutex_; std::condition_variable coordinate_overlay_cv_; @@ -164,8 +188,11 @@ private: perception::TagRelativeTarget3D tracker_; perception::TagRelativeTcpPose tcp_pose_tracker_; PbvsController pbvs_; - cmvr::config::TouchScreenTaskConfig config_{}; - bool config_valid_{false}; + const cmvr::config::TouchScreenTaskConfig config_; + const bool config_valid_; + device::AbstractDexHand::TactileRegionKey tactile_region_{ + device::AbstractDexHand::FingerType::INDEX, + device::AbstractDexHand::TactileRegion::TIP}; Phase phase_{Phase::IDLE}; Phase phase_after_retract_{Phase::DONE}; @@ -190,7 +217,7 @@ private: Eigen::Vector3d last_align_error_screen_tag_{Eigen::Vector3d::Zero()}; Eigen::Matrix4d T_H_P_{Eigen::Matrix4d::Identity()}; double pbvs_command_acceleration_{0.25}; - // Initialization MoveJ is skipped only when both position and velocity + // Initialization MoveP is skipped only when both position and velocity // are within these configured limits. double init_skip_position_tolerance_rad_{1e-3}; double init_skip_velocity_tolerance_rad_s_{1e-2}; diff --git a/cmvr-es/task/touch_screen_task/src/touch_screen_task.cpp b/cmvr-es/task/touch_screen_task/src/touch_screen_task.cpp index 98374c3b..1605bd8d 100644 --- a/cmvr-es/task/touch_screen_task/src/touch_screen_task.cpp +++ b/cmvr-es/task/touch_screen_task/src/touch_screen_task.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include @@ -21,19 +22,6 @@ namespace cmvr::task { namespace { -// The initialization move is a safety repositioning step. Avoid replanning -// an already settled arm, while still requiring a stopped joint velocity so a -// moving arm is never mistaken for being at the initial pose. -device::CartesianVelocity toCartesianVelocity(const Eigen::Matrix& twist) { - return {twist[0], twist[1], twist[2], twist[3], twist[4], twist[5]}; -} - -Eigen::Matrix toEigen6(const device::CartesianVelocity& twist) { - Eigen::Matrix out; - out << twist.vx, twist.vy, twist.vz, twist.wx, twist.wy, twist.wz; - return out; -} - bool computeLinearMoveDeltaTool(const Eigen::Matrix& twist_base, const double move_length, Eigen::Vector3d& delta_out) { @@ -167,30 +155,20 @@ bool extractProjectedYawAboutTargetNormal(const Eigen::Matrix3d& R_target, return std::isfinite(yaw_rad_out); } -bool appendRequestedTactileRegions( +bool isTactileRegionSupported( const device::AbstractDexHand::FingerType finger, - const device::AbstractDexHand::TactileRegion region, - std::vector& regions_out) { - using DeviceTactileRegion = device::AbstractDexHand::TactileRegion; - + const device::AbstractDexHand::TactileRegion region) { + using Region = device::AbstractDexHand::TactileRegion; switch (region) { - case device::AbstractDexHand::TactileRegion::TIP: - regions_out.emplace_back(finger, DeviceTactileRegion::TIP); - return true; - case device::AbstractDexHand::TactileRegion::FINGER: - regions_out.emplace_back(finger, DeviceTactileRegion::FINGER); - return true; - case device::AbstractDexHand::TactileRegion::PAD: - regions_out.emplace_back(finger, DeviceTactileRegion::PAD); - return true; - case device::AbstractDexHand::TactileRegion::THUMB_MIDDLE: - if (finger != device::AbstractDexHand::FingerType::THUMB) { - return false; - } - regions_out.emplace_back(finger, DeviceTactileRegion::THUMB_MIDDLE); + case Region::TIP: + case Region::FINGER: + case Region::PAD: return true; + case Region::THUMB_MIDDLE: + return finger == device::AbstractDexHand::FingerType::THUMB; + default: + return false; } - return false; } perception::AprilTagPerception::DepthPolicy toDepthPolicy( @@ -233,29 +211,6 @@ device::AbstractDexHand::FingerType toFingerType(const cmvr::config::TouchScreen return device::AbstractDexHand::FingerType::INDEX; } -const char* fingerTypeToString(const device::AbstractDexHand::FingerType finger) { - switch (finger) { - case device::AbstractDexHand::FingerType::PINKY: return "PINKY"; - case device::AbstractDexHand::FingerType::RING: return "RING"; - case device::AbstractDexHand::FingerType::MIDDLE: return "MIDDLE"; - case device::AbstractDexHand::FingerType::INDEX: return "INDEX"; - case device::AbstractDexHand::FingerType::THUMB: return "THUMB"; - case device::AbstractDexHand::FingerType::PALM: return "PALM"; - } - return "UNKNOWN"; -} - -const char* tactileRegionToString(const device::AbstractDexHand::TactileRegion region) { - switch (region) { - case device::AbstractDexHand::TactileRegion::TIP: return "TIP"; - case device::AbstractDexHand::TactileRegion::FINGER: return "FINGER"; - case device::AbstractDexHand::TactileRegion::PAD: return "PAD"; - case device::AbstractDexHand::TactileRegion::THUMB_MIDDLE: return "THUMB_MIDDLE"; - case device::AbstractDexHand::TactileRegion::PALM_PAD: return "PALM_PAD"; - } - return "UNKNOWN"; -} - device::AbstractDexHand::TactileRegion toTactileRegion( const cmvr::config::TouchScreenTactileRegion region) { switch (region) { @@ -276,52 +231,42 @@ device::AbstractDexHand::TactileRegion toTactileRegion( TouchScreenTask::TouchScreenTask(const cmvr::config::TouchScreenTaskConfig& cfg) : id_(cfg.id()), tracker_(nullptr), - config_(cfg) { - config_valid_ = validateConfig(config_); + config_(cfg), + config_valid_(validateConfig(config_)) { if (!config_valid_) { last_status_ = Status::INVALID_CONFIG; } } TouchScreenTask::~TouchScreenTask() { + cancelApproach(); stopCoordinateOverlayWorker(); } bool TouchScreenTask::init() { - if (!config_valid_) { - last_status_ = Status::INVALID_CONFIG; - return false; + { + std::lock_guard lock(mutex_); + stopUnlocked(); + stopCoordinateOverlayWorker(); + initialized_ = false; + last_status_ = config_valid_ ? Status::NOT_INITIALIZED : Status::INVALID_CONFIG; + if (!config_valid_) return false; } const auto& devices = config_.devices(); - const auto& perception_config = config_.perception(); - if (!devices.has_arm_id() || devices.arm_id().empty() || - !devices.has_dexhand_id() || devices.dexhand_id().empty() || - !devices.has_camera_id() || devices.camera_id().empty() || - !devices.has_external_camera_id() || devices.external_camera_id().empty() || - !perception_config.has_hand_camera() || - !perception_config.hand_camera().has_depth_policy() || - !perception_config.hand_camera().has_target_point_method()) { - last_status_ = Status::INVALID_CONFIG; - return false; - } - auto& dm = device::DeviceManager::getInstance(); auto arm = dm.getDevice(devices.arm_id()); auto dexhand = dm.getDevice(devices.dexhand_id()); - const auto& hand_camera_config = perception_config.hand_camera(); auto camera = dm.getDevice(devices.camera_id()); auto external_camera = dm.getDevice(devices.external_camera_id()); if (!camera || !camera->start()) { CMVR_LOG(ERROR) << "[TouchScreenTask] Failed to start camera: " << devices.camera_id(); - last_status_ = Status::NOT_INITIALIZED; return false; } if (!external_camera || !external_camera->start()) { CMVR_LOG(ERROR) << "[TouchScreenTask] Failed to start external camera: " << devices.external_camera_id(); - last_status_ = Status::NOT_INITIALIZED; return false; } return init(arm, dexhand, camera, external_camera); @@ -343,6 +288,8 @@ bool TouchScreenTask::init(const std::shared_ptr& arm, const std::shared_ptr& camera, const std::shared_ptr& external_camera) { std::lock_guard lock(mutex_); + stopUnlocked(); + initialized_ = false; stopCoordinateOverlayWorker(); arm_ = arm; dexhand_ = dexhand; @@ -355,33 +302,10 @@ bool TouchScreenTask::init(const std::shared_ptr& arm, return false; } - if ((config_.initialization().before_start() || config_.initialization().after_finish()) && - config_.initialization().joint_positions().empty()) { - initialized_ = false; - last_status_ = Status::INVALID_CONFIG; - return false; - } - - const auto& perception_config = config_.perception(); - const auto& tags = perception_config.tags(); - const auto& hand_camera_config = perception_config.hand_camera(); perception_ = std::make_shared(camera_); - perception_->setTagSize(tags.screen().size_m()); external_perception_ = std::make_shared(external_camera_); - external_perception_->setTagSize(tags.screen().size_m()); - tracker_.setPerception(perception_); - tracker_.setTargetPointMethod(toTargetPointMethod( - hand_camera_config.target_point_method())); - - tcp_pose_tracker_.setPerception(external_perception_); - tcp_pose_tracker_.setScreenTagId(tags.screen().id()); - tcp_pose_tracker_.setHandTagId(tags.hand().id()); - - // Publish the presentation settings immediately so a gRPC stream started - // before the first periodic task tick uses the configured behavior. - publishCoordinateOverlay(); initialized_ = applyConfig(); if (initialized_) { @@ -390,28 +314,10 @@ bool TouchScreenTask::init(const std::shared_ptr& arm, tcp_pose_tracker_.clear(); pbvs_.reset(); phase_ = Phase::IDLE; - phase_after_retract_ = Phase::DONE; - final_status_after_retract_ = Status::DONE; - target_locked_ = false; - pbvs_target_initialized_ = false; - touch_command_started_ = false; - retract_command_started_ = false; - align_stable_count_ = 0; - last_active_tag_id_ = -1; - last_touch_pressure_sum_ = 0.0; - last_touch_resultant_fz_ = 0.0; - last_touch_nonzero_count_ = 0; - last_align_error_screen_tag_.setZero(); - touch_start_position_valid_ = false; - touch_start_position_base_.setZero(); - retract_start_position_valid_ = false; - retract_start_position_base_.setZero(); - have_last_T_B_G_ = false; - last_T_B_G_.setIdentity(); - max_T_B_G_translation_delta_m_ = 0.0; - max_T_B_G_rotation_delta_rad_ = 0.0; - last_touch_pressure_log_time_ = Clock::time_point{}; + resetRunState(); last_status_ = Status::IDLE; + // Make presentation settings available before the first task tick. + publishCoordinateOverlay(); startCoordinateOverlayWorker(); } else { last_status_ = Status::INVALID_CONFIG; @@ -443,8 +349,33 @@ bool TouchScreenTask::startFromPixelUnlocked(int u, int v) { return false; } + // A failed run keeps its original status until a new run passes preflight. + // In particular, do not move to the initial/approach pose with a latched speedL fault. + const auto reject_start = [&](const std::string& message) { + CMVR_LOG(ERROR) << "[TouchScreenTask][START_REJECTED] " << message; + if (phase_ != Phase::FAILED) last_status_ = Status::ROBOT_COMMAND_FAILED; + phase_ = Phase::FAILED; + setCoordinateOverlayEnabled(true); + return false; + }; + cancelApproach(); + try { + if (arm_->isEmergencyStopped() || arm_->isProtectiveStopped()) { + return reject_start("safety stop active"); + } + if (!arm_->isConnected()) return reject_start("arm is not connected"); + const auto stopped = arm_->stopMotion(); + if (!stopped.ok()) return reject_start("stop failed: " + stopped.message); + const auto recovered = arm_->recoverSpeedLPlanningFault(); + if (!recovered.ok()) return reject_start(recovered.message); + } catch (const std::exception& error) { + return reject_start(error.what()); + } catch (...) { + return reject_start("unknown stop/recovery error"); + } + stopUnlocked(); - if (!moveToInitPositionBeforeStartIfEnabled()) { + if (!moveToInitPositionIfEnabled(config_.initialization().before_start(), true)) { return false; } @@ -455,35 +386,11 @@ bool TouchScreenTask::startFromPixelUnlocked(int u, int v) { target_u_ = u; target_v_ = v; - target_locked_ = false; - pbvs_target_initialized_ = false; - touch_command_started_ = false; - retract_command_started_ = false; - align_stable_count_ = 0; - align_debug_count_ = 0; - pbvs_debug_count_ = 0; - last_touch_pressure_sum_ = 0.0; - last_touch_resultant_fz_ = 0.0; - last_touch_nonzero_count_ = 0; - last_active_tag_id_ = -1; - last_align_error_screen_tag_.setZero(); - locked_target_rotation_valid_ = false; - locked_target_rotation_.setIdentity(); - touch_start_position_valid_ = false; - touch_start_position_base_.setZero(); - retract_start_position_valid_ = false; - retract_start_position_base_.setZero(); - have_last_T_B_G_ = false; - last_T_B_G_.setIdentity(); - max_T_B_G_translation_delta_m_ = 0.0; - max_T_B_G_rotation_delta_rad_ = 0.0; - phase_ = Phase::ALIGNING; + phase_ = config_.approach().enable() ? Phase::PREPARING : Phase::ALIGNING; setCoordinateOverlayEnabled(false); startCoordinateOverlayWorker(); - phase_after_retract_ = Phase::DONE; - final_status_after_retract_ = Status::DONE; phase_start_time_ = Clock::now(); - last_status_ = Status::ALIGN_WAITING_TRACK; + last_status_ = config_.approach().enable() ? Status::PREPARING : Status::ALIGN_WAITING_TRACK; return true; } @@ -504,6 +411,10 @@ bool TouchScreenTask::step(const double dt) { } switch (phase_) { + case Phase::PREPARING: + return stepPreparing(); + case Phase::APPROACHING: + return stepApproaching(); case Phase::IDLE: last_status_ = Status::IDLE; return true; @@ -520,7 +431,7 @@ bool TouchScreenTask::step(const double dt) { CMVR_LOG(WARNING) << "[TouchScreenTask][ALIGN_PAUSE_TIMEOUT]" << " elapsed_s=" << paused_s << ", timeout_s=" << config_.alignment().timeout_s() - << ", move_to_init=" << config_.initialization().after_finish(); + << ", move_to_init=" << config_.initialization().after_failure(); enterFailed(Status::ALIGN_TIMEOUT); return false; } @@ -701,6 +612,7 @@ void TouchScreenTask::stop() { } void TouchScreenTask::stopUnlocked() { + cancelApproach(); if (arm_) { try { arm_->stopL(); @@ -712,6 +624,11 @@ void TouchScreenTask::stopUnlocked() { phase_ = Phase::IDLE; setCoordinateOverlayEnabled(true); + resetRunState(); + last_status_ = Status::STOPPED; +} + +void TouchScreenTask::resetRunState() { phase_after_retract_ = Phase::DONE; final_status_after_retract_ = Status::DONE; target_locked_ = false; @@ -719,6 +636,8 @@ void TouchScreenTask::stopUnlocked() { touch_command_started_ = false; retract_command_started_ = false; align_stable_count_ = 0; + align_debug_count_ = 0; + pbvs_debug_count_ = 0; last_active_tag_id_ = -1; last_touch_pressure_sum_ = 0.0; last_touch_resultant_fz_ = 0.0; @@ -734,7 +653,7 @@ void TouchScreenTask::stopUnlocked() { last_T_B_G_.setIdentity(); max_T_B_G_translation_delta_m_ = 0.0; max_T_B_G_rotation_delta_rad_ = 0.0; - last_status_ = Status::STOPPED; + last_touch_pressure_log_time_ = Clock::time_point{}; } TouchScreenTask::Phase TouchScreenTask::phase() const { @@ -748,7 +667,8 @@ TouchScreenTask::Status TouchScreenTask::lastStatus() const { } bool TouchScreenTask::isBusyUnlocked() const { - return phase_ == Phase::ALIGNING || phase_ == Phase::ALIGN_REACHED || + return phase_ == Phase::PREPARING || phase_ == Phase::APPROACHING || + phase_ == Phase::ALIGNING || phase_ == Phase::ALIGN_REACHED || phase_ == Phase::TOUCHING || phase_ == Phase::DWELLING || phase_ == Phase::RETRACTING; } @@ -830,6 +750,8 @@ std::string TouchScreenTask::detailStatusString() const { const char* TouchScreenTask::phaseToString(const Phase phase) { switch (phase) { case Phase::IDLE: return "IDLE"; + case Phase::PREPARING: return "PREPARING"; + case Phase::APPROACHING: return "APPROACHING"; case Phase::ALIGNING: return "ALIGNING"; case Phase::ALIGN_REACHED: return "ALIGN_REACHED"; case Phase::TOUCHING: return "TOUCHING"; @@ -863,6 +785,10 @@ const char* TouchScreenTask::statusToString(const Status status) { case Status::ROBOT_STATE_FAILED: return "ROBOT_STATE_FAILED"; case Status::ROBOT_COMMAND_FAILED: return "ROBOT_COMMAND_FAILED"; case Status::TASK_BUSY: return "TASK_BUSY"; + case Status::PREPARING: return "PREPARING"; + case Status::APPROACHING: return "APPROACHING"; + case Status::APPROACH_FAILED: return "APPROACH_FAILED"; + case Status::APPROACH_TIMEOUT: return "APPROACH_TIMEOUT"; } return "UNKNOWN"; } @@ -965,6 +891,20 @@ bool TouchScreenTask::validateConfig(const cmvr::config::TouchScreenTaskConfig& cmvr::common::math::toEigenVec6(pbvs.amax6()); const Eigen::Matrix4d T_H_P = toEigenMat4(calibration.hand_tag_to_tcp()); + const auto& approach = config.approach(); + if (approach.enable()) { + for (const double value : {approach.velocity(), approach.acceleration(), + approach.jerk(), approach.timeout_s()}) { + if (!std::isfinite(value) || value <= 0.0) return false; + } + if (!approach.has_minimum_clearance_m() || + !std::isfinite(approach.minimum_clearance_m()) || + approach.minimum_clearance_m() < 0.0 || + position_offset_G.z() <= approach.minimum_clearance_m()) { + return false; + } + } + if (screen_tag.id() < 0 || hand_tag.id() < 0 || screen_tag.id() == hand_tag.id() || !std::isfinite(screen_tag.size_m()) || screen_tag.size_m() <= 0.0 || @@ -1013,19 +953,20 @@ bool TouchScreenTask::validateConfig(const cmvr::config::TouchScreenTaskConfig& return false; } - if (config.initialization().before_start() || config.initialization().after_finish()) { - std::vector init_joint_names; - init_joint_names.reserve(static_cast( - config.initialization().joint_positions_size())); - for (const auto& joint : config.initialization().joint_positions()) { - init_joint_names.push_back(joint.joint_name()); - } - std::vector init_positions; - if (!buildInitJointPositionsFromConfig(config, init_joint_names, init_positions) || - static_cast(init_positions.size()) != - config.initialization().joint_positions_size()) { + if (config.initialization().before_start() || config.initialization().after_finish() || + config.initialization().after_failure()) { + const auto& joints = config.initialization().joint_positions(); + if (joints.empty()) { return false; } + std::unordered_set names; + for (const auto& joint : joints) { + if (!joint.has_joint_name() || joint.joint_name().empty() || + !joint.has_rad() || !std::isfinite(joint.rad()) || + !names.insert(joint.joint_name()).second) { + return false; + } + } } const auto& initialization = config.initialization(); @@ -1040,10 +981,8 @@ bool TouchScreenTask::validateConfig(const cmvr::config::TouchScreenTaskConfig& return false; } - std::vector tactile_regions; - if (!appendRequestedTactileRegions(toFingerType(tactile.finger()), - toTactileRegion(tactile.region()), - tactile_regions)) { + if (!isTactileRegionSupported(toFingerType(tactile.finger()), + toTactileRegion(tactile.region()))) { return false; } @@ -1103,10 +1042,6 @@ bool TouchScreenTask::applyConfig() { if (!perception_ || !external_perception_) { return false; } - if (!validateConfig(config_)) { - return false; - } - init_skip_position_tolerance_rad_ = config_.initialization().has_skip_position_tolerance_rad() ? config_.initialization().skip_position_tolerance_rad() @@ -1116,16 +1051,11 @@ bool TouchScreenTask::applyConfig() { ? config_.initialization().skip_velocity_tolerance_rad_s() : 1e-2; + const auto& tactile = config_.touch().tactile(); + tactile_region_ = {toFingerType(tactile.finger()), toTactileRegion(tactile.region())}; if (dexhand_) { - const auto& tactile = config_.touch().tactile(); - std::vector tactile_regions; - if (!appendRequestedTactileRegions(toFingerType(tactile.finger()), - toTactileRegion(tactile.region()), - tactile_regions)) { - return false; - } try { - dexhand_->setTactilePollingRegions(tactile_regions); + dexhand_->setTactilePollingRegion(tactile_region_.first, tactile_region_.second); } catch (...) { return false; } @@ -1177,41 +1107,180 @@ bool TouchScreenTask::applyConfig() { return true; } -bool TouchScreenTask::stepAligning(const double dt) { - const auto& alignment = config_.alignment(); - const auto target_orientation = - cmvr::common::math::toEigenEuler(alignment.target().hand_orientation_g()); - const auto& target = alignment.target(); - const Eigen::Vector3d position_offset_G = - target.has_position_offset_g() - ? cmvr::common::math::toEigenVec3(target.position_offset_g()) - : Eigen::Vector3d::Zero(); - const Eigen::Vector3d rotation_offset_G = - target.has_rotation_offset_g() - ? cmvr::common::math::toEigenVec3(target.rotation_offset_g()) - : Eigen::Vector3d::Zero(); +void TouchScreenTask::cancelApproach() { + if (approach_cancel_) approach_cancel_->store(true); + if (approach_motion_.valid()) { + // Safe to join under mutex_: the worker and its callbacks own no task state. + try { + (void)approach_motion_.get(); + } catch (const std::exception& error) { + CMVR_LOG(ERROR) << "[TouchScreenTask][APPROACH] " << error.what(); + } catch (...) { + CMVR_LOG(ERROR) << "[TouchScreenTask][APPROACH] unknown motion error"; + } + } + approach_cancel_.reset(); +} - const auto now = Clock::now(); - const double elapsed = std::chrono::duration(now - phase_start_time_).count(); - if (elapsed > alignment.timeout_s()) { +bool TouchScreenTask::stepPreparing() { + if (std::chrono::duration(Clock::now() - phase_start_time_).count() > + config_.alignment().timeout_s()) { + enterFailed(Status::APPROACH_TIMEOUT); + return false; + } + // Take the visual/FK snapshot only after the previous velocity motion stops. + if (arm_->busy()) return true; + + Eigen::Vector3d anchor_G; + if (!updateAlignmentAnchor(anchor_G) || !updateAlignmentTcpPose()) return true; + const Eigen::Matrix4d T_G_P = tcp_pose_tracker_.T_G_P(); + if (!updatePbvsTarget(anchor_G, T_G_P)) return false; + + try { + const Eigen::Matrix4d T_B_P = common::math::poseToMatrix(arm_->fk(true)); + const Eigen::Matrix4d T_B_G = T_B_P * T_G_P.inverse(); + const Eigen::Matrix4d target_B = T_B_G * pbvs_.targetPose(); + if (!isHomogeneousTransform(T_B_G) || !isHomogeneousTransform(target_B)) { + enterFailed(Status::ROBOT_STATE_FAILED); + return false; + } + + const auto& cfg = config_.approach(); + device::MotionOptions options; + options.velocity = cfg.velocity(); + options.acceleration = cfg.acceleration(); + options.jerk = cfg.jerk(); + const Eigen::Vector3d normal_B = T_B_G.block<3, 3>(0, 0).col(2); + const Eigen::Vector3d anchor_B = + T_B_G.block<3, 3>(0, 0) * anchor_G + T_B_G.block<3, 1>(0, 3); + // A fixed screen-plane constraint, including the start and the smoothed + // path. It guards TCP samples only, not the hand/arm's swept geometry. + options.is_tcp_pose_valid = + [normal_B, anchor_B, clearance = cfg.minimum_clearance_m()] + (const device::CartesianPose& pose) { + const Eigen::Vector3d p(pose.x, pose.y, pose.z); + return p.allFinite() && normal_B.dot(p - anchor_B) >= clearance; + }; + const auto target = common::math::matrixToPose(target_B); + if (!options.is_tcp_pose_valid(common::math::matrixToPose(T_B_P)) || + !options.is_tcp_pose_valid(target)) { + CMVR_LOG(ERROR) << "[TouchScreenTask][APPROACH] TCP start/target violates screen clearance"; + enterFailed(Status::APPROACH_FAILED); + return false; + } + + phase_start_time_ = Clock::now(); + const auto started = phase_start_time_; + const double timeout_s = cfg.timeout_s(); + approach_cancel_ = std::make_shared>(false); + options.cancellation_requested = [cancel = approach_cancel_, started, timeout_s] { + return cancel->load() || + std::chrono::duration(Clock::now() - started).count() >= timeout_s; + }; + approach_motion_ = std::async(std::launch::async, [arm = arm_, target, options, started, timeout_s] { + const auto result = arm->moveP(target, options, device::FrameType::Base); + // Record deadline failure on the worker, not on a potentially late + // TaskManager polling tick after successful completion. + return std::chrono::duration(Clock::now() - started).count() >= timeout_s + ? device::Result::failure(device::ArmErrorCode::Timeout, "approach timed out") + : result; + }); + phase_ = Phase::APPROACHING; + last_status_ = Status::APPROACHING; + CMVR_LOG(INFO) << "[TouchScreenTask][APPROACH_START] target_base=[" + << target.x << ", " << target.y << ", " << target.z + << "], velocity_rad_s=" << options.velocity; + return true; + } catch (const std::exception& error) { + CMVR_LOG(ERROR) << "[TouchScreenTask][APPROACH] " << error.what(); + enterFailed(Status::APPROACH_FAILED); + return false; + } +} + +bool TouchScreenTask::stepApproaching() { + const double elapsed = std::chrono::duration(Clock::now() - phase_start_time_).count(); + // The shared TaskManager thread never waits for planning or motion here. + if (approach_motion_.wait_for(std::chrono::seconds(0)) != std::future_status::ready) { + if (elapsed >= config_.approach().timeout_s()) { + approach_cancel_->store(true); + last_status_ = Status::APPROACH_TIMEOUT; + } + return true; + } + + try { + const auto result = approach_motion_.get(); + approach_cancel_.reset(); + if (!result.ok()) { + CMVR_LOG(ERROR) << "[TouchScreenTask][APPROACH_FAILED] elapsed_s=" << elapsed + << ", error=" << result.message; + enterFailed(result.code == device::ArmErrorCode::Timeout + ? Status::APPROACH_TIMEOUT : Status::APPROACH_FAILED); + return false; + } + } catch (const std::exception& error) { + CMVR_LOG(ERROR) << "[TouchScreenTask][APPROACH_FAILED] " << error.what(); + enterFailed(Status::APPROACH_FAILED); + return false; + } + + // Keep the original screen anchor and desired pose, but reacquire the live + // TCP pose and start PBVS with zero command history and its own timeout. + tcp_pose_tracker_.clear(); + pbvs_.resetTwistCommandState(); + align_stable_count_ = 0; + phase_ = Phase::ALIGNING; + phase_start_time_ = Clock::now(); + last_status_ = Status::ALIGN_WAITING_TRACK; + CMVR_LOG(INFO) << "[TouchScreenTask][APPROACH_DONE] elapsed_s=" << elapsed; + return true; +} + +bool TouchScreenTask::stepAligning(const double dt) { + const double elapsed = + std::chrono::duration(Clock::now() - phase_start_time_).count(); + if (elapsed > config_.alignment().timeout_s()) { enterFailed(Status::ALIGN_TIMEOUT); return false; } - const double pbvs_dt = std::clamp(dt, 0.0001, 0.05); + Eigen::Vector3d p_target_G = Eigen::Vector3d::Zero(); + // Missing perception is temporary: the helpers stop PBVS and record the + // waiting status, while step() keeps the alignment phase active. + if (!updateAlignmentAnchor(p_target_G) || !updateAlignmentTcpPose()) { + return true; + } + + const Eigen::Matrix4d& T_G_P = tcp_pose_tracker_.T_G_P(); + if (!updatePbvsTarget(p_target_G, T_G_P)) { + return false; + } + PbvsController::Output output; + if (!pbvs_.compute(T_G_P, std::clamp(dt, 0.0001, 0.05), output)) { + enterFailed(Status::ALIGN_COMPUTE_FAILED); + return false; + } + + device::CartesianVelocity twist_B; + if (!mapAlignmentCommandToBase(T_G_P, output, twist_B)) { + return false; + } + return applyAlignmentCommand(output, twist_B); +} + +bool TouchScreenTask::updateAlignmentAnchor(Eigen::Vector3d& p_target_G) { // The hand camera is only needed to establish the target anchor once. // After the first successful PBVS target initialization, tracker_ keeps // that anchor fixed and the external camera supplies the live TCP pose. const bool hand_camera_needed = !target_locked_ || !pbvs_target_initialized_; - bool hand_perception_ok = true; if (hand_camera_needed) { perception::AprilTagPerception::Options hand_options; hand_options.depth_policy = toDepthPolicy(config_.perception().hand_camera().depth_policy()); hand_options.detect_tags = true; hand_options.fetch_encoded = false; - hand_perception_ok = perception_->update(hand_options); - if (!hand_perception_ok) { + if (!perception_->update(hand_options)) { if (align_debug_count_ == 0 && !perception_->color().empty()) { cv::imwrite("/tmp/cmvr_hand_camera_perception.png", perception_->color()); } @@ -1231,7 +1300,7 @@ bool TouchScreenTask::stepAligning(const double dt) { } stopPbvsMotion(); last_status_ = Status::ALIGN_WAITING_PERCEPTION; - return true; + return false; } } @@ -1243,7 +1312,7 @@ bool TouchScreenTask::stepAligning(const double dt) { pbvs_target_initialized_ = false; align_stable_count_ = 0; } - } else if (hand_camera_needed && hand_perception_ok) { + } else if (hand_camera_needed) { tracking_ok = tracker_.track(); } @@ -1264,42 +1333,37 @@ bool TouchScreenTask::stepAligning(const double dt) { stopPbvsMotion(); align_stable_count_ = 0; last_status_ = Status::ALIGN_WAITING_TRACK; - return true; + return false; } const int tag_id = tracker_.activeTagId(); last_active_tag_id_ = tag_id; const int screen_tag_id = config_.perception().tags().screen().id(); - if (tag_id != screen_tag_id) { + if (tag_id != screen_tag_id || !tracker_.getAnchorInTag(tag_id, p_target_G)) { stopPbvsMotion(); align_stable_count_ = 0; last_status_ = Status::ALIGN_WAITING_TRACK; - return true; + return false; } - Eigen::Vector3d p_target_G = Eigen::Vector3d::Zero(); - if (!tracker_.getAnchorInTag(tag_id, p_target_G)) { - stopPbvsMotion(); - align_stable_count_ = 0; - last_status_ = Status::ALIGN_WAITING_TRACK; - return true; - } + return true; +} +bool TouchScreenTask::updateAlignmentTcpPose() { perception::AprilTagPerception::Options external_options; external_options.depth_policy = perception::AprilTagPerception::DepthPolicy::NONE; external_options.detect_tags = true; external_options.fetch_encoded = false; - if (!external_perception_->update(external_options)) { - publishCoordinateOverlay(); + const bool perception_ok = external_perception_->update(external_options); + publishCoordinateOverlay(); + if (!perception_ok) { stopPbvsMotion(); align_stable_count_ = 0; last_status_ = Status::ALIGN_WAITING_PERCEPTION; - return true; + return false; } - publishCoordinateOverlay(); - - tcp_pose_tracker_.setScreenTagId(screen_tag_id); + tcp_pose_tracker_.setScreenTagId(config_.perception().tags().screen().id()); if (!tcp_pose_tracker_.update(T_H_P_)) { if (align_debug_count_ == 0 && !external_perception_->color().empty()) { cv::imwrite("/tmp/cmvr_external_camera_perception.png", @@ -1325,10 +1389,27 @@ bool TouchScreenTask::stepAligning(const double dt) { stopPbvsMotion(); align_stable_count_ = 0; last_status_ = Status::ALIGN_WAITING_TRACK; - return true; + return false; } - const Eigen::Matrix4d& T_G_P = tcp_pose_tracker_.T_G_P(); + return true; +} + +bool TouchScreenTask::updatePbvsTarget(const Eigen::Vector3d& p_target_G, + const Eigen::Matrix4d& T_G_P) { + const auto& alignment = config_.alignment(); + const auto target_orientation = + cmvr::common::math::toEigenEuler(alignment.target().hand_orientation_g()); + const auto& target = alignment.target(); + const Eigen::Vector3d position_offset_G = + target.has_position_offset_g() + ? cmvr::common::math::toEigenVec3(target.position_offset_g()) + : Eigen::Vector3d::Zero(); + const Eigen::Vector3d rotation_offset_G = + target.has_rotation_offset_g() + ? cmvr::common::math::toEigenVec3(target.rotation_offset_g()) + : Eigen::Vector3d::Zero(); + const Eigen::Matrix3d R_G_H_target = rotationFromTargetEuler(target_orientation.x(), target_orientation.y(), @@ -1379,12 +1460,12 @@ bool TouchScreenTask::stepAligning(const double dt) { pbvs_target_initialized_ = true; } - PbvsController::Output output; - if (!pbvs_.compute(T_G_P, pbvs_dt, output)) { - enterFailed(Status::ALIGN_COMPUTE_FAILED); - return false; - } + return true; +} +bool TouchScreenTask::mapAlignmentCommandToBase(const Eigen::Matrix4d& T_G_P, + const PbvsController::Output& output, + device::CartesianVelocity& twist_B) { Eigen::Matrix4d T_B_P = Eigen::Matrix4d::Identity(); try { T_B_P = cmvr::common::math::poseToMatrix(arm_->fk(true)); @@ -1426,7 +1507,7 @@ bool TouchScreenTask::stepAligning(const double dt) { return false; } - const device::CartesianVelocity twist_B{ + twist_B = { linear_B.x(), linear_B.y(), linear_B.z(), angular_B.x(), angular_B.y(), angular_B.z()}; @@ -1501,6 +1582,11 @@ bool TouchScreenTask::stepAligning(const double dt) { << twist_B.wx << ' ' << twist_B.wy << ' ' << twist_B.wz << ']'; } + return true; +} + +bool TouchScreenTask::applyAlignmentCommand(const PbvsController::Output& output, + const device::CartesianVelocity& twist_B) { last_align_error_screen_tag_ = output.position_error_G; if (output.reached) { ++align_stable_count_; @@ -1508,8 +1594,8 @@ bool TouchScreenTask::stepAligning(const double dt) { align_stable_count_ = 0; } - if (align_stable_count_ >= alignment.stable_frames()) { - CMVR_LOG(INFO) << "[TouchScreenTask][ALIGN_REACHED] tag_id=" << tag_id + if (align_stable_count_ >= config_.alignment().stable_frames()) { + CMVR_LOG(INFO) << "[TouchScreenTask][ALIGN_REACHED] tag_id=" << last_active_tag_id_ << ", err_xyz_G=[" << output.position_error_G.x() << ", " << output.position_error_G.y() << ", " << output.position_error_G.z() << "]" @@ -1588,7 +1674,7 @@ bool TouchScreenTask::stepTouching() { << ", fz_N=" << last_touch_resultant_fz_ << ", criterion_value_N=" << last_touch_pressure_sum_ << ", threshold_N=" << config_.touch().tactile().force_threshold() - << "; check preceding CartesianVelocityController/planner errors"; + << "; check preceding SpeedLExecutor/planner errors"; enterFailed(Status::ROBOT_COMMAND_FAILED); return false; } @@ -1727,6 +1813,9 @@ bool TouchScreenTask::stepRetracting() { const bool have_final_position = readCurrentTouchPointPositionBase(final_position_base); Eigen::Vector3d final_delta_base = Eigen::Vector3d::Zero(); const bool have_final_delta = retract_start_position_valid_ && have_final_position; + const bool return_to_init = phase_after_retract_ == Phase::FAILED + ? config_.initialization().after_failure() + : config_.initialization().after_finish(); if (have_final_delta) { final_delta_base = final_position_base - retract_start_position_base_; max_forward_after_retract_m_ = std::max(max_forward_after_retract_m_, @@ -1736,7 +1825,7 @@ bool TouchScreenTask::stepRetracting() { CMVR_LOG(INFO) << "[TouchScreenTask][RETRACT_DONE] elapsed=" << elapsed << ", target_distance_m=" << retract_distance_m << ", max_forward_after_retract_mm=" << max_forward_after_retract_m_ * 1000.0 - << ", move_to_init=" << (config_.initialization().after_finish() ? 1 : 0) + << ", move_to_init=" << return_to_init << ", final_tcp_delta_base=[" << final_delta_base.x() << ", " << final_delta_base.y() << ", " << final_delta_base.z() << "], final_tcp_dist=" << final_delta_base.norm(); @@ -1744,10 +1833,15 @@ bool TouchScreenTask::stepRetracting() { CMVR_LOG(INFO) << "[TouchScreenTask][RETRACT_DONE] elapsed=" << elapsed << ", target_distance_m=" << retract_distance_m << ", max_forward_after_retract_mm=" << max_forward_after_retract_m_ * 1000.0 - << ", move_to_init=" << (config_.initialization().after_finish() ? 1 : 0) + << ", move_to_init=" << return_to_init << ", final_tcp_delta_base=unavailable"; } + if (phase_after_retract_ == Phase::FAILED) { + enterFailed(final_status_after_retract_); + return false; + } + // Stop the retract worker synchronously before switching to the final // joint-position trajectory. stopL() only requests deceleration and can // return while the worker still owns the velocity-control mode. @@ -1756,8 +1850,7 @@ bool TouchScreenTask::stepRetracting() { enterFailed(Status::ROBOT_COMMAND_FAILED); return false; } - if ((phase_after_retract_ == Phase::DONE || phase_after_retract_ == Phase::FAILED) && - !moveToInitPositionIfEnabled()) { + if (phase_after_retract_ == Phase::DONE && !moveToInitPositionIfEnabled(return_to_init)) { phase_ = Phase::FAILED; last_status_ = Status::ROBOT_COMMAND_FAILED; return false; @@ -1797,7 +1890,7 @@ void TouchScreenTask::logTouchingSpeedLState() const { return; } - const Eigen::Matrix cmd_twist_base = toEigen6(arm_->getSpeedLCommandTwistBase()); + const Eigen::Matrix cmd_twist_base = cmvr::common::math::velocityToVector(arm_->getSpeedLCommandTwistBase()); Eigen::Vector3d current_position_base = Eigen::Vector3d::Zero(); const bool have_current_position = readCurrentTouchPointPositionBase(current_position_base); const bool have_delta = touch_start_position_valid_ && have_current_position; @@ -1834,6 +1927,7 @@ bool TouchScreenTask::buildInitJointPositions(std::vector& positions_out config_, arm_->getRobotModel().joint_names, positions_out); } +// Skip initialization only if both joint position and measured velocity are settled. bool TouchScreenTask::isAtInitPosition(const std::vector& positions) const { if (!arm_ || arm_->busy()) { return false; @@ -1855,8 +1949,8 @@ bool TouchScreenTask::isAtInitPosition(const std::vector& positions) con return true; } -bool TouchScreenTask::moveToInitPositionBeforeStartIfEnabled() { - if (!config_.initialization().before_start()) { +bool TouchScreenTask::moveToInitPositionIfEnabled(const bool enabled, const bool use_move_j) { + if (!enabled) { return true; } if (!arm_) { @@ -1870,8 +1964,9 @@ bool TouchScreenTask::moveToInitPositionBeforeStartIfEnabled() { return false; } + const char* motion = use_move_j ? "moveJ" : "moveP"; if (isAtInitPosition(init_positions)) { - CMVR_LOG(INFO) << "[TouchScreenTask] initial position already reached; skipping moveJ" + CMVR_LOG(INFO) << "[TouchScreenTask] initial position already reached; skipping " << motion << ", arm=" << id_; return true; } @@ -1880,40 +1975,15 @@ bool TouchScreenTask::moveToInitPositionBeforeStartIfEnabled() { device::MotionOptions options; options.velocity = config_.initialization().velocity(); options.acceleration = config_.initialization().acceleration(); - const auto result = arm_->moveJ(init_cmd, options); + const auto result = use_move_j ? arm_->moveJ(init_cmd, options) : arm_->moveP(init_cmd, options); if (!result.ok()) { + CMVR_LOG(ERROR) << "[TouchScreenTask][RETURN_TO_INIT] " << motion << " failed: " << result.message; last_status_ = Status::ROBOT_COMMAND_FAILED; return false; } return true; } -bool TouchScreenTask::moveToInitPositionIfEnabled() const { - if (!config_.initialization().after_finish()) { - return true; - } - std::vector init_positions; - if (!arm_ || !buildInitJointPositions(init_positions)) { - return false; - } - - if (isAtInitPosition(init_positions)) { - CMVR_LOG(INFO) << "[TouchScreenTask] final initial position already reached; skipping moveJ" - << ", arm=" << id_; - return true; - } - - device::JointPositionCommand init_cmd{init_positions}; - device::MotionOptions options; - options.velocity = config_.initialization().velocity(); - options.acceleration = config_.initialization().acceleration(); - const auto result = arm_->moveJ(init_cmd, options); - if (!result.ok()) { - return false; - } - return true; -} - bool TouchScreenTask::handleTouchTriggered(const bool stop_forward_motion) { if (config_.touch().dwell_time_s() <= 0.0) { // Submit reversal in this tick, before any synchronous FK or logging. @@ -1966,7 +2036,7 @@ bool TouchScreenTask::startTouchPhase() { options.acceleration = speed_l.acceleration(); if (speed_l.has_linear_jerk()) options.linear_jerk = speed_l.linear_jerk(); options.continuous_linear_reversal = true; - const auto result = arm_->speedL(toCartesianVelocity( + const auto result = arm_->speedL(cmvr::common::math::vectorToVelocity( cmvr::common::math::toEigenVec6(speed_l.twist_tool())), options, 0.0, @@ -2003,7 +2073,7 @@ bool TouchScreenTask::startTouchPhase() { return false; } - if (!moveToInitPositionIfEnabled()) { + if (!moveToInitPositionIfEnabled(config_.initialization().after_finish())) { last_status_ = Status::ROBOT_COMMAND_FAILED; return false; } @@ -2027,7 +2097,7 @@ bool TouchScreenTask::startRetractPhase(const Phase next_phase_after_retract, retract_start_position_valid_ = false; retract_direction_base_.setZero(); max_forward_after_retract_m_ = 0.0; - const auto retract_cmd = toCartesianVelocity( + const auto retract_cmd = cmvr::common::math::vectorToVelocity( cmvr::common::math::toEigenVec6(retract.twist_tool())); device::SpeedLOptions options; options.acceleration = retract.acceleration(); @@ -2060,7 +2130,8 @@ bool TouchScreenTask::startRetractPhase(const Phase next_phase_after_retract, } void TouchScreenTask::enterFailed(const Status status) { - stopPbvsMotion(); + cancelApproach(); + pbvs_.resetTwistCommandState(); if (phase_ == Phase::RETRACTING && retract_start_position_valid_) { CMVR_LOG(WARNING) << "[TouchScreenTask][RETRACT_FAILED] status=" << statusToString(status) << ", max_forward_after_retract_mm=" << max_forward_after_retract_m_ * 1000.0; @@ -2069,7 +2140,34 @@ void TouchScreenTask::enterFailed(const Status status) { setCoordinateOverlayEnabled(true); touch_command_started_ = false; retract_command_started_ = false; - last_status_ = moveToInitPositionIfEnabled() ? status : Status::ROBOT_COMMAND_FAILED; + last_status_ = status; + if (!arm_) return; + + try { + // stopL only requests deceleration. Confirm the velocity worker has + // stopped before allowing a joint-position return after a failure. + const auto stopped = arm_->stopMotion(); + if (!stopped.ok()) { + CMVR_LOG(ERROR) << "[TouchScreenTask][FAILURE_RETURN_SKIPPED] status=" + << statusToString(status) << ", stop failed: " << stopped.message; + return; + } + if (!config_.initialization().after_failure()) return; + if (arm_->isEmergencyStopped() || arm_->isProtectiveStopped()) { + CMVR_LOG(WARNING) << "[TouchScreenTask][FAILURE_RETURN_SKIPPED] safety stop active" + << ", status=" << statusToString(status); + return; + } + CMVR_LOG(INFO) << "[TouchScreenTask][FAILURE_RETURN_START] status=" << statusToString(status); + const bool returned = moveToInitPositionIfEnabled(true); + CMVR_LOG(INFO) << "[TouchScreenTask][FAILURE_RETURN_DONE] success=" << returned + << ", status=" << statusToString(status); + } catch (const std::exception& error) { + CMVR_LOG(ERROR) << "[TouchScreenTask][FAILURE_RETURN_FAILED] " << error.what(); + } catch (...) { + CMVR_LOG(ERROR) << "[TouchScreenTask][FAILURE_RETURN_FAILED] unknown error"; + } + last_status_ = status; } bool TouchScreenTask::updateTouchPressure() { @@ -2080,31 +2178,16 @@ bool TouchScreenTask::updateTouchPressure() { return false; } - const auto& tactile = config_.touch().tactile(); - std::vector tactile_regions; - if (!appendRequestedTactileRegions(toFingerType(tactile.finger()), - toTactileRegion(tactile.region()), - tactile_regions)) { - return false; - } - - double resultant_value = 0.0; - double resultant_fz = 0.0; try { - for (const auto& tactile_region : tactile_regions) { - const auto resultant_force = dexhand_->getResultantForceNewtons( - tactile_region.first, tactile_region.second); - resultant_value += tactileForceValue(resultant_force, tactile.criterion()); - resultant_fz += resultant_force.fz; - } + const auto force = dexhand_->getResultantForceNewtons( + tactile_region_.first, tactile_region_.second); + last_touch_pressure_sum_ = tactileForceValue(force, config_.touch().tactile().criterion()); + last_touch_resultant_fz_ = force.fz; + last_touch_nonzero_count_ = std::abs(last_touch_pressure_sum_) > 1e-9 ? 1 : 0; + return true; } catch (...) { return false; } - - last_touch_nonzero_count_ = std::abs(resultant_value) > 1e-9 ? 1 : 0; - last_touch_pressure_sum_ = resultant_value; - last_touch_resultant_fz_ = resultant_fz; - return true; } void TouchScreenTask::logTouchPressure(const bool force) { diff --git a/cmvr-es/task/touch_screen_task/src/touch_screen_task_test.cpp b/cmvr-es/task/touch_screen_task/src/touch_screen_task_test.cpp index 7098140c..2363bf46 100644 --- a/cmvr-es/task/touch_screen_task/src/touch_screen_task_test.cpp +++ b/cmvr-es/task/touch_screen_task/src/touch_screen_task_test.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -19,6 +20,8 @@ #include #include "task/touch_screen_task/include/touch_screen_task.h" +#include "algorithms/collision_detection/include/collision_checker.h" +#include "algorithms/planner/joint/joint_path_planner_factory.h" #include "common/config/config_files.h" #include "common/vision/image_projection.h" @@ -154,6 +157,164 @@ cmvr::config::TouchScreenTaskConfig loadMujocoTouchConfig(const std::filesystem: return root_config.touch_screen_task(); } +class FailureReturnCamera final : public cmvr::device::AbstractCamera { +public: + std::string typeName() const override { return "FailureReturnCamera"; } + void getState(cmvr::device::CameraState& state) override { state = {}; } +}; + +class FailureReturnArm final : public cmvr::device::RobotArm { +public: + using Result = cmvr::device::Result; + explicit FailureReturnArm(const cmvr::config::TouchScreenTaskConfig& config) { + for (const auto& joint : config.initialization().joint_positions()) { + model.joint_names.push_back(joint.joint_name()); + state.position.push_back(joint.rad() + 0.1); + state.velocity.push_back(0.0); + } + model.dof = model.joint_names.size(); + } + + std::string typeName() const override { return "FailureReturnArm"; } + cmvr::RobotModel getRobotModel() const override { return model; } + std::size_t getDof() const override { return model.dof; } + cmvr::device::ArmState getRobotState() const override { return {}; } + cmvr::device::JointGroupState getJointState() const override { return state; } + cmvr::device::CartesianPose getTcpPose(cmvr::device::FrameType) const override { return {}; } + cmvr::device::RobotMode getRobotMode() const override { return cmvr::device::RobotMode::Idle; } + cmvr::device::SafetyMode getSafetyMode() const override { + return emergency ? cmvr::device::SafetyMode::EmergencyStop + : protective ? cmvr::device::SafetyMode::ProtectiveStop + : cmvr::device::SafetyMode::Normal; + } + cmvr::device::ControlMode getControlMode() const override { return cmvr::device::ControlMode::Position; } + bool isProtectiveStopped() const override { return protective; } + bool isEmergencyStopped() const override { return emergency; } + bool isFault() const override { return planning_fault; } + bool isConnected() const override { return connected; } + bool busy() const override { return false; } + double getSpeedScaling() const override { return 1.0; } + + Result stopL(std::optional) override { return Result::success(); } + Result stopMotion() override { + calls.push_back("stopMotion"); + return stop_result; + } + Result recoverSpeedLPlanningFault() override { + calls.push_back("recoverSpeedLPlanningFault"); + if (recovery_result.ok()) planning_fault = false; + return recovery_result; + } + Result moveP(const cmvr::device::JointPositionCommand& target, + const cmvr::device::MotionOptions& options) override { + calls.push_back("moveP"); + return_target = target.position; + return_options = options; + return move_result; + } + Result moveJ(const cmvr::device::JointPositionCommand& target, + const cmvr::device::MotionOptions& options) override { + calls.push_back("moveJ"); + startup_target = target.position; + startup_options = options; + return move_result; + } + + Result torqueOn() override { return unsupported(); } + Result moveP(const cmvr::device::CartesianPose&, const cmvr::device::MotionOptions&, + cmvr::device::FrameType) override { return unsupported(); } + Result torqueOff() override { return unsupported(); } + Result calibrateZeroQ(const std::string&) override { return unsupported(); } + Result emergencyStop() override { return unsupported(); } + Result protectiveStop() override { return unsupported(); } + Result recoverProtectiveStop(const cmvr::device::JointTrajectory&, + const cmvr::device::MotionOptions&) override { return unsupported(); } + Result setSpeedScaling(double) override { return unsupported(); } + Result speedJ(const cmvr::device::JointVelocityCommand&, double, double) override { return unsupported(); } + Result stopJ(double) override { return unsupported(); } + Result moveL(const cmvr::device::CartesianPose&, const cmvr::device::MotionOptions&, + cmvr::device::FrameType) override { return unsupported(); } + Result speedL(const cmvr::device::CartesianVelocity&, double, double, + cmvr::device::FrameType) override { return unsupported(); } + Result startServoMode(const cmvr::device::ServoOptions&) override { return unsupported(); } + Result servoJ(const cmvr::device::JointPositionCommand&) override { return unsupported(); } + Result servoL(const cmvr::device::CartesianPose&, cmvr::device::FrameType) override { return unsupported(); } + Result servoSpeedJ(const cmvr::device::JointVelocityCommand&) override { return unsupported(); } + Result servoSpeedL(const cmvr::device::CartesianVelocity&, cmvr::device::FrameType) override { return unsupported(); } + Result stopServoMode() override { return unsupported(); } + Result connect(const std::string&, int) override { return unsupported(); } + Result disconnect() override { return unsupported(); } + Result powerOn() override { return unsupported(); } + Result powerOff() override { return unsupported(); } + Result brakeRelease() override { return unsupported(); } + Result shutdown() override { return unsupported(); } + Result clearFault() override { return unsupported(); } + Result unlockProtectiveStop() override { return unsupported(); } + Result loadProgram(const std::string&) override { return unsupported(); } + Result playProgram() override { return unsupported(); } + Result pauseProgram() override { return unsupported(); } + Result stopProgram() override { return unsupported(); } + std::vector ik(const std::string&, const std::string&, + const cmvr::device::CartesianPose&) override { return {}; } + std::shared_ptr kinematicsSolver() const override { return nullptr; } + cmvr::device::CartesianPose fk(const std::string&, const std::string&) override { return {}; } + cmvr::device::CartesianPose fk(bool) override { return {}; } + cmvr::device::CartesianVelocity getSpeedLCommandTwistBase() const override { return {}; } + + cmvr::RobotModel model; + cmvr::device::JointGroupState state; + Result stop_result{Result::success()}; + Result move_result{Result::success()}; + Result recovery_result{Result::success()}; + bool planning_fault{false}; + bool connected{true}; + bool emergency{false}; + bool protective{false}; + std::vector calls; + std::vector return_target; + cmvr::device::MotionOptions return_options; + std::vector startup_target; + cmvr::device::MotionOptions startup_options; + +private: + static Result unsupported() { + ADD_FAILURE() << "unexpected robot command in failure-return test"; + return Result::failure(cmvr::device::ArmErrorCode::UnsupportedCommand, "not used"); + } +}; + +class TouchScreenFailureReturnTest : public ::testing::Test { +protected: + void SetUp() override { + config = loadMujocoTouchConfig(findProjectRoot()); + config.mutable_approach()->set_enable(false); + config.mutable_initialization()->set_before_start(false); + config.mutable_initialization()->set_after_finish(true); + // Trigger the shared failure handler via public APIs, without camera input. + config.mutable_alignment()->set_timeout_s(1e-9); + arm = std::make_shared(config); + } + + void expectTimeoutFailure() { + cmvr::task::TouchScreenTask task(config); + const auto camera = std::make_shared(); + ASSERT_TRUE(task.init(arm, nullptr, camera, camera)); + ASSERT_TRUE(task.touch(320, 240)); + arm->calls.clear(); + EXPECT_FALSE(task.step(0.02)); + EXPECT_EQ(task.lastStatus(), cmvr::task::TouchScreenTask::Status::ALIGN_TIMEOUT); + EXPECT_TRUE(task.isFailed()); + EXPECT_FALSE(task.isFinished()); + EXPECT_FALSE(task.isBusy()); + const auto calls = arm->calls; + EXPECT_FALSE(task.step(0.02)); + EXPECT_EQ(arm->calls, calls) << "failure return must run only once"; + } + + cmvr::config::TouchScreenTaskConfig config; + std::shared_ptr arm; +}; + cmvr::device::DeviceManager& getTestDeviceManager() { static bool initialized = [] { cmvr::ConfigHelper::setConfigRootFromFile("cmvr-es/config/cmvr_es.pb.txt"); @@ -257,12 +418,188 @@ void run_touch_once(int u, int v) { } // namespace +TEST_F(TouchScreenFailureReturnTest, FailureReturnIsOptionalAndIndependentOfSuccessReturn) { + for (const bool explicitly_disabled : {false, true}) { + SCOPED_TRACE(explicitly_disabled); + config.mutable_initialization()->clear_after_failure(); + if (explicitly_disabled) config.mutable_initialization()->set_after_failure(false); + EXPECT_FALSE(config.initialization().after_failure()); + arm->calls.clear(); + expectTimeoutFailure(); + EXPECT_EQ(arm->calls, std::vector{"stopMotion"}); + } +} + +TEST_F(TouchScreenFailureReturnTest, EnabledFailureReturnStopsBeforeMovingAndPreservesFailure) { + config.mutable_initialization()->set_after_finish(false); + config.mutable_initialization()->set_after_failure(true); + expectTimeoutFailure(); + EXPECT_EQ(arm->calls, (std::vector{"stopMotion", "moveP"})); + std::vector expected_target; + for (const auto& joint : config.initialization().joint_positions()) { + expected_target.push_back(joint.rad()); + } + EXPECT_EQ(arm->return_target, expected_target); + EXPECT_DOUBLE_EQ(arm->return_options.velocity, config.initialization().velocity()); + EXPECT_DOUBLE_EQ(arm->return_options.acceleration, config.initialization().acceleration()); +} + +TEST_F(TouchScreenFailureReturnTest, InitializationStopsBeforeMoveJ) { + config.mutable_initialization()->set_before_start(true); + const auto camera = std::make_shared(); + cmvr::task::TouchScreenTask task(config); + ASSERT_TRUE(task.init(arm, nullptr, camera, camera)); + ASSERT_TRUE(task.touch(320, 240)); + EXPECT_EQ(arm->calls, (std::vector{ + "stopMotion", "recoverSpeedLPlanningFault", "moveJ"})); + std::vector expected_target; + for (const auto& joint : config.initialization().joint_positions()) { + expected_target.push_back(joint.rad()); + } + EXPECT_EQ(arm->startup_target, expected_target); + EXPECT_DOUBLE_EQ(arm->startup_options.velocity, config.initialization().velocity()); + EXPECT_DOUBLE_EQ(arm->startup_options.acceleration, config.initialization().acceleration()); + + task.stop(); + arm->calls.clear(); + arm->stop_result = cmvr::device::Result::failure( + cmvr::device::ArmErrorCode::CommandFailed, "injected stop failure"); + EXPECT_FALSE(task.touch(320, 240)); + EXPECT_EQ(arm->calls, std::vector{"stopMotion"}); +} + +TEST_F(TouchScreenFailureReturnTest, FailedStopOrSafetyStopPreventsFailureReturn) { + config.mutable_initialization()->set_after_failure(true); + for (const auto* reason : {"failed_stop", "emergency", "protective"}) { + SCOPED_TRACE(reason); + arm->stop_result = cmvr::device::Result::success(); + arm->emergency = false; + arm->protective = false; + cmvr::task::TouchScreenTask task(config); + const auto camera = std::make_shared(); + ASSERT_TRUE(task.init(arm, nullptr, camera, camera)); + ASSERT_TRUE(task.touch(320, 240)); + arm->calls.clear(); + arm->stop_result = std::string(reason) == "failed_stop" + ? cmvr::device::Result::failure(cmvr::device::ArmErrorCode::CommandFailed, + "injected stop failure") + : cmvr::device::Result::success(); + arm->emergency = std::string(reason) == "emergency"; + arm->protective = std::string(reason) == "protective"; + EXPECT_FALSE(task.step(0.02)); + EXPECT_TRUE(task.isFailed()); + EXPECT_EQ(task.lastStatus(), cmvr::task::TouchScreenTask::Status::ALIGN_TIMEOUT); + EXPECT_EQ(arm->calls, std::vector{"stopMotion"}); + } +} + +TEST_F(TouchScreenFailureReturnTest, NextRunRecoversPlanningFaultBeforeInitialization) { + config.mutable_initialization()->set_before_start(true); + config.mutable_initialization()->set_after_failure(true); + cmvr::task::TouchScreenTask task(config); + const auto camera = std::make_shared(); + ASSERT_TRUE(task.init(arm, nullptr, camera, camera)); + ASSERT_TRUE(task.touch(320, 240)); + arm->calls.clear(); + arm->planning_fault = true; + + EXPECT_FALSE(task.step(0.02)); + ASSERT_TRUE(task.isFailed()); + ASSERT_EQ(task.lastStatus(), cmvr::task::TouchScreenTask::Status::ALIGN_TIMEOUT); + EXPECT_TRUE(arm->isFault()) << "failure return must retain the original fault"; + EXPECT_EQ(arm->calls, (std::vector{"stopMotion", "moveP"})); + + arm->calls.clear(); + ASSERT_TRUE(task.touch(350, 260)); + EXPECT_EQ(arm->calls, (std::vector{ + "stopMotion", "recoverSpeedLPlanningFault", "moveJ"})); + EXPECT_FALSE(arm->isFault()); + EXPECT_TRUE(task.isBusy()); + EXPECT_FALSE(task.isFailed()); +} + +TEST_F(TouchScreenFailureReturnTest, DisabledInitializationStillRecoversBeforeStarting) { + config.mutable_initialization()->set_before_start(false); + cmvr::task::TouchScreenTask task(config); + const auto camera = std::make_shared(); + ASSERT_TRUE(task.init(arm, nullptr, camera, camera)); + arm->planning_fault = true; + ASSERT_TRUE(task.touch(320, 240)); + EXPECT_EQ(arm->calls, (std::vector{ + "stopMotion", "recoverSpeedLPlanningFault"})); + EXPECT_FALSE(arm->isFault()); + EXPECT_TRUE(task.isBusy()); +} + +TEST_F(TouchScreenFailureReturnTest, RejectedRestartPreservesPreviousFailureAndDoesNotMove) { + config.mutable_initialization()->set_before_start(true); + config.mutable_initialization()->set_after_failure(false); + for (const auto* reason : {"failed_stop", "fatal_fault", "emergency", "protective", "disconnected"}) { + SCOPED_TRACE(reason); + arm = std::make_shared(config); + cmvr::task::TouchScreenTask task(config); + const auto camera = std::make_shared(); + ASSERT_TRUE(task.init(arm, nullptr, camera, camera)); + ASSERT_TRUE(task.touch(320, 240)); + ASSERT_FALSE(task.step(0.02)); + ASSERT_TRUE(task.isFailed()); + ASSERT_EQ(task.lastStatus(), cmvr::task::TouchScreenTask::Status::ALIGN_TIMEOUT); + arm->calls.clear(); + const std::string failure = reason; + arm->planning_fault = true; + arm->emergency = failure == "emergency"; + arm->protective = failure == "protective"; + arm->connected = failure != "disconnected"; + if (failure == "failed_stop") { + arm->stop_result = cmvr::device::Result::failure( + cmvr::device::ArmErrorCode::CommandFailed, "injected stop failure"); + } + if (failure == "fatal_fault") { + arm->recovery_result = cmvr::device::Result::failure( + cmvr::device::ArmErrorCode::CommandFailed, "injected nonrecoverable fault"); + } + + EXPECT_FALSE(task.touch(350, 260)); + EXPECT_TRUE(task.isFailed()); + EXPECT_FALSE(task.isBusy()); + EXPECT_EQ(task.lastStatus(), cmvr::task::TouchScreenTask::Status::ALIGN_TIMEOUT); + EXPECT_TRUE(arm->isFault()); + if (failure == "fatal_fault") { + EXPECT_EQ(arm->calls, (std::vector{ + "stopMotion", "recoverSpeedLPlanningFault"})); + } else if (failure == "failed_stop") { + EXPECT_EQ(arm->calls, std::vector{"stopMotion"}); + } else { + EXPECT_TRUE(arm->calls.empty()); + } + } +} + +TEST_F(TouchScreenFailureReturnTest, FailedReturnPreservesOriginalFailure) { + config.mutable_initialization()->set_after_failure(true); + arm->move_result = cmvr::device::Result::failure( + cmvr::device::ArmErrorCode::CommandFailed, "injected return failure"); + expectTimeoutFailure(); + EXPECT_EQ(arm->calls, (std::vector{"stopMotion", "moveP"})); +} + +TEST(TouchScreenTaskTest, FailureReturnRequiresValidInitialJointPositions) { + auto config = loadMujocoTouchConfig(findProjectRoot()); + config.mutable_initialization()->set_before_start(false); + config.mutable_initialization()->set_after_finish(false); + config.mutable_initialization()->set_after_failure(true); + config.mutable_initialization()->clear_joint_positions(); + cmvr::task::TouchScreenTask task(config); + EXPECT_EQ(task.lastStatus(), cmvr::task::TouchScreenTask::Status::INVALID_CONFIG); +} + TEST(TouchScreenTaskTest, ConfigFilesUseStructuredSchema) { const auto project_root = findProjectRoot(); ASSERT_FALSE(project_root.empty()); for (const auto* file_name : {"touch_screen_task.pb.txt", "touch_screen_task_mujoco.pb.txt"}) { + SCOPED_TRACE(file_name); cmvr::config::TouchScreenTaskRootConfig root_config; const auto config_path = project_root / "cmvr-es/config/tasks/touch_screen_task" / file_name; @@ -271,39 +608,164 @@ TEST(TouchScreenTaskTest, ConfigFilesUseStructuredSchema) { const auto& config = root_config.touch_screen_task(); EXPECT_TRUE(config.has_initialization()); + EXPECT_TRUE(config.initialization().after_failure()); EXPECT_TRUE(config.has_perception()); ASSERT_TRUE(config.perception().has_tags()); - EXPECT_EQ(config.perception().tags().screen().id(), 1); - EXPECT_EQ(config.perception().tags().hand().id(), 0); - EXPECT_DOUBLE_EQ(config.perception().tags().screen().size_m(), 0.03); - EXPECT_DOUBLE_EQ(config.perception().tags().hand().size_m(), 0.03); + const auto& tags = config.perception().tags(); + EXPECT_GE(tags.screen().id(), 0); + EXPECT_GE(tags.hand().id(), 0); + EXPECT_NE(tags.screen().id(), tags.hand().id()); + EXPECT_GT(tags.screen().size_m(), 0.0); + EXPECT_GT(tags.hand().size_m(), 0.0); EXPECT_TRUE(config.perception().has_hand_camera()); const bool is_mujoco = std::string(file_name).find("mujoco") != std::string::npos; - EXPECT_EQ(config.devices().camera_id(), - is_mujoco ? "mujoco_hand_cam" : "right_hand_cam"); - EXPECT_EQ(config.devices().external_camera_id(), - is_mujoco ? "mujoco_external_touch_cam" : "cam5"); + EXPECT_FALSE(config.devices().camera_id().empty()); + EXPECT_FALSE(config.devices().external_camera_id().empty()); EXPECT_TRUE(config.has_alignment()); ASSERT_TRUE(config.alignment().has_calibration()); EXPECT_TRUE(config.alignment().calibration().has_hand_tag_to_tcp()); ASSERT_TRUE(config.alignment().target().has_hand_orientation_g()); - EXPECT_DOUBLE_EQ(config.alignment().target().hand_orientation_g().rx(), 0.0); - EXPECT_DOUBLE_EQ(config.alignment().target().hand_orientation_g().ry(), 0.0); - EXPECT_DOUBLE_EQ(config.alignment().target().hand_orientation_g().rz(), - 3.141592653589793); + const auto& orientation = config.alignment().target().hand_orientation_g(); + EXPECT_TRUE(std::isfinite(orientation.rx())); + EXPECT_TRUE(std::isfinite(orientation.ry())); + EXPECT_TRUE(std::isfinite(orientation.rz())); ASSERT_TRUE(config.alignment().has_pbvs()); const auto& pbvs = config.alignment().pbvs(); - EXPECT_DOUBLE_EQ(pbvs.position_gain().x(), 2.0); - EXPECT_DOUBLE_EQ(pbvs.rotation_gain().z(), 1.5); - EXPECT_DOUBLE_EQ(pbvs.vmax6().z(), 0.05); - EXPECT_DOUBLE_EQ(pbvs.amax6().rz(), 2.0); - EXPECT_DOUBLE_EQ(pbvs.twist_filter_alpha(), 1.0); + EXPECT_GE(pbvs.position_gain().x(), 0.0); + EXPECT_GE(pbvs.rotation_gain().z(), 0.0); + EXPECT_GT(pbvs.vmax6().z(), 0.0); + EXPECT_GE(pbvs.amax6().rz(), 0.0); + EXPECT_GE(pbvs.twist_filter_alpha(), 0.0); + EXPECT_LE(pbvs.twist_filter_alpha(), 1.0); + if (is_mujoco) { + ASSERT_TRUE(config.has_approach()); + const auto& approach = config.approach(); + EXPECT_TRUE(approach.enable()); + EXPECT_DOUBLE_EQ(approach.velocity(), 0.65); + EXPECT_DOUBLE_EQ(approach.acceleration(), 1.7); + EXPECT_DOUBLE_EQ(approach.jerk(), 30.0); + EXPECT_DOUBLE_EQ(approach.timeout_s(), 10.0); + EXPECT_DOUBLE_EQ(approach.minimum_clearance_m(), 0.01); + EXPECT_DOUBLE_EQ(config.alignment().target().position_offset_g().z(), 0.05); + EXPECT_EQ(tags.screen().id(), 1); + EXPECT_EQ(tags.hand().id(), 0); + EXPECT_DOUBLE_EQ(tags.screen().size_m(), 0.03); + EXPECT_DOUBLE_EQ(tags.hand().size_m(), 0.03); + EXPECT_EQ(config.devices().camera_id(), "mujoco_hand_cam"); + EXPECT_EQ(config.devices().external_camera_id(), "mujoco_external_touch_cam"); + EXPECT_DOUBLE_EQ(orientation.rx(), 0.0); + EXPECT_DOUBLE_EQ(orientation.ry(), 0.0); + EXPECT_DOUBLE_EQ(orientation.rz(), 3.141592653589793); + EXPECT_DOUBLE_EQ(pbvs.position_gain().x(), 2.0); + EXPECT_DOUBLE_EQ(pbvs.rotation_gain().z(), 1.5); + EXPECT_DOUBLE_EQ(pbvs.vmax6().z(), 0.05); + EXPECT_DOUBLE_EQ(pbvs.amax6().rz(), 2.0); + EXPECT_DOUBLE_EQ(pbvs.twist_filter_alpha(), 1.0); + } EXPECT_TRUE(config.has_touch()); EXPECT_EQ(config.touch().motion_case(), cmvr::config::TouchScreenTaskTouchConfig::kSpeedL); EXPECT_TRUE(config.has_retract()); EXPECT_TRUE(config.retract().has_distance_m()); EXPECT_GT(config.retract().distance_m(), 0.0); + cmvr::task::TouchScreenTask task(config); + EXPECT_EQ(task.lastStatus(), cmvr::task::TouchScreenTask::Status::NOT_INITIALIZED); + } +} + +TEST(TouchScreenTaskTest, MotorArmConfigurationsSupportMoveP) { + const auto project_root = findProjectRoot(); + ASSERT_FALSE(project_root.empty()); + for (const auto* file_name : {"arm.pb.txt", "arm_qp.pb.txt", "arm_mujoco.pb.txt", + "arm_mujoco_qp.pb.txt", "ethercat_dual_arm.pb.txt", + "arm_gen2_mujoco.pb.txt"}) { + SCOPED_TRACE(file_name); + cmvr::config::ArmRootConfig root; + ASSERT_TRUE(ProtoMessageIo::getProtoFromAsciiFile( + (project_root / "cmvr-es/config/devices/arm" / file_name).string(), &root)); + ASSERT_GT(root.arm().robot_arms_size(), 0); + for (const auto& arm : root.arm().robot_arms()) { + SCOPED_TRACE(arm.id()); + ASSERT_TRUE(arm.motion().has_joint_path()); + const auto& path = arm.motion().joint_path(); + ASSERT_NE(cmvr::JointPathPlannerFactory::create(path), nullptr); + EXPECT_TRUE(std::isfinite(path.minimum_distance_m())); + EXPECT_GE(path.minimum_distance_m(), 0.0); + const auto& joints = arm.motor().joint_names(); + cmvr::CollisionOptions options; + for (const auto& pair : path.collision_checker().ignored_pairs()) { + options.ignored_pairs.push_back({pair.first(), pair.second()}); + } + cmvr::CollisionChecker checker; + std::string error; + ASSERT_TRUE(checker.init( + (project_root / path.collision_checker().urdf_path()).string(), + std::vector(joints.begin(), joints.end()), options, &error)) << error; + EXPECT_EQ(checker.dof(), arm.motor().dof()); + EXPECT_GT(checker.activePairCount(), 0); + } + } +} + +TEST(TouchScreenTaskTest, DisabledApproachPreservesExistingConfigBehavior) { + auto config = loadMujocoTouchConfig(findProjectRoot()); + config.clear_approach(); + { + cmvr::task::TouchScreenTask task(config); + EXPECT_EQ(task.lastStatus(), cmvr::task::TouchScreenTask::Status::NOT_INITIALIZED); + } + auto* approach = config.mutable_approach(); + approach->set_enable(false); + approach->set_velocity(std::numeric_limits::quiet_NaN()); + approach->set_acceleration(-1.0); + approach->set_jerk(0.0); + approach->set_timeout_s(std::numeric_limits::infinity()); + approach->set_minimum_clearance_m(-1.0); + cmvr::task::TouchScreenTask task(config); + EXPECT_EQ(task.lastStatus(), cmvr::task::TouchScreenTask::Status::NOT_INITIALIZED); +} + +TEST(TouchScreenTaskTest, EnabledApproachRequiresFinitePositiveMotionLimits) { + const auto valid_config = loadMujocoTouchConfig(findProjectRoot()); + ASSERT_TRUE(valid_config.approach().enable()); + using Approach = cmvr::config::TouchScreenTaskApproachConfig; + using Setter = void (Approach::*)(double); + const std::array, 4> setters{{ + {"velocity", &Approach::set_velocity}, + {"acceleration", &Approach::set_acceleration}, + {"jerk", &Approach::set_jerk}, + {"timeout_s", &Approach::set_timeout_s}, + }}; + for (const auto& [name, setter] : setters) { + for (const double value : {0.0, -1.0, std::numeric_limits::infinity(), + std::numeric_limits::quiet_NaN()}) { + SCOPED_TRACE(::testing::Message() << name << "=" << value); + auto config = valid_config; + (config.mutable_approach()->*setter)(value); + cmvr::task::TouchScreenTask task(config); + EXPECT_EQ(task.lastStatus(), cmvr::task::TouchScreenTask::Status::INVALID_CONFIG); + } + } + for (const double clearance : {-1.0, std::numeric_limits::infinity(), + std::numeric_limits::quiet_NaN()}) { + SCOPED_TRACE(::testing::Message() << "minimum_clearance_m=" << clearance); + auto config = valid_config; + config.mutable_approach()->set_minimum_clearance_m(clearance); + cmvr::task::TouchScreenTask task(config); + EXPECT_EQ(task.lastStatus(), cmvr::task::TouchScreenTask::Status::INVALID_CONFIG); + } + { + auto config = valid_config; + config.mutable_approach()->set_minimum_clearance_m(0.0); + cmvr::task::TouchScreenTask task(config); + EXPECT_EQ(task.lastStatus(), cmvr::task::TouchScreenTask::Status::NOT_INITIALIZED); + } + for (const double target_z : {0.0, valid_config.approach().minimum_clearance_m()}) { + SCOPED_TRACE(::testing::Message() << "target_z=" << target_z); + auto config = valid_config; + config.mutable_alignment()->mutable_target()->mutable_position_offset_g()->set_z(target_z); + cmvr::task::TouchScreenTask task(config); + EXPECT_EQ(task.lastStatus(), cmvr::task::TouchScreenTask::Status::INVALID_CONFIG); } } @@ -346,6 +808,61 @@ TEST(TouchScreenTaskTest, TouchSpeedLJerkIsOptionalAndMustBeFinitePositive) { } } +TEST(TouchScreenTaskTest, TactileRegionMustMatchSelectedFinger) { + auto config = loadMujocoTouchConfig(findProjectRoot()); + for (const auto finger : {cmvr::config::TOUCH_SCREEN_FINGER_TYPE_PINKY, + cmvr::config::TOUCH_SCREEN_FINGER_TYPE_RING, + cmvr::config::TOUCH_SCREEN_FINGER_TYPE_MIDDLE, + cmvr::config::TOUCH_SCREEN_FINGER_TYPE_INDEX, + cmvr::config::TOUCH_SCREEN_FINGER_TYPE_THUMB}) { + for (const auto region : {cmvr::config::TOUCH_SCREEN_TACTILE_REGION_TIP, + cmvr::config::TOUCH_SCREEN_TACTILE_REGION_FINGER, + cmvr::config::TOUCH_SCREEN_TACTILE_REGION_PAD, + cmvr::config::TOUCH_SCREEN_TACTILE_REGION_THUMB_MIDDLE}) { + SCOPED_TRACE(::testing::Message() << "finger=" << finger << ", region=" << region); + config.mutable_touch()->mutable_tactile()->set_finger(finger); + config.mutable_touch()->mutable_tactile()->set_region(region); + const bool valid = region != cmvr::config::TOUCH_SCREEN_TACTILE_REGION_THUMB_MIDDLE || + finger == cmvr::config::TOUCH_SCREEN_FINGER_TYPE_THUMB; + cmvr::task::TouchScreenTask task(config); + EXPECT_EQ(task.lastStatus(), valid + ? cmvr::task::TouchScreenTask::Status::NOT_INITIALIZED + : cmvr::task::TouchScreenTask::Status::INVALID_CONFIG); + } + } +} + +TEST(TouchScreenTaskTest, InitializationRequiresUniqueCompleteFiniteJointPositions) { + const auto valid_config = loadMujocoTouchConfig(findProjectRoot()); + ASSERT_TRUE(valid_config.initialization().before_start()); + ASSERT_GT(valid_config.initialization().joint_positions_size(), 0); + const auto expect_invalid = [](const cmvr::config::TouchScreenTaskConfig& config) { + cmvr::task::TouchScreenTask task(config); + EXPECT_EQ(task.lastStatus(), cmvr::task::TouchScreenTask::Status::INVALID_CONFIG); + }; + for (const auto* invalid_case : {"empty", "missing_name", "empty_name", "missing_position", + "duplicate", "nan", "infinity"}) { + SCOPED_TRACE(invalid_case); + auto config = valid_config; + auto* initialization = config.mutable_initialization(); + const std::string name(invalid_case); + if (name == "empty") { + initialization->clear_joint_positions(); + } else if (name == "duplicate") { + const auto joint = initialization->joint_positions(0); + *initialization->add_joint_positions() = joint; + } else { + auto* joint = initialization->mutable_joint_positions(0); + if (name == "missing_name") joint->clear_joint_name(); + if (name == "empty_name") joint->set_joint_name(""); + if (name == "missing_position") joint->clear_rad(); + if (name == "nan") joint->set_rad(std::numeric_limits::quiet_NaN()); + if (name == "infinity") joint->set_rad(std::numeric_limits::infinity()); + } + expect_invalid(config); + } +} + TEST(TouchScreenTaskTest, CoordinateFrameProjectionUsesBgrAxisColors) { cv::Mat image = cv::Mat::zeros(240, 320, CV_8UC3); cmvr::device::Rs2Intrinsics intrinsics{}; @@ -388,12 +905,46 @@ TEST(TouchScreenTaskTest, RunEyeToHandTouchInMujoco) { cmvr::ConfigHelper::setConfigRootFromFile( (project_root / "cmvr-es/config/cmvr_es.pb.txt").string()); + const auto touch_config = loadMujocoTouchConfig(project_root); + cmvr::config::DeviceManagerRootConfig runtime_devices; + ASSERT_TRUE(cmvr::ConfigHelper::loadConfigFile( + "manager/device_manager.pb.txt", runtime_devices)); + const auto& entries = runtime_devices.device_manager().devices(); + const auto arm_entry = std::find_if(entries.begin(), entries.end(), [](const auto& entry) { + return entry.id() == "mujoco_right_arm"; + }); + ASSERT_NE(arm_entry, entries.end()); + ASSERT_TRUE(arm_entry->enable()); + ASSERT_EQ(arm_entry->type(), cmvr::config::DeviceConfigEntry::DEVICE_TYPE_ROBOT_ARM); + ASSERT_FALSE(arm_entry->config_file().empty()); + const auto arm_config_path = cmvr::ConfigHelper::resolveConfigFile(arm_entry->config_file()); + std::cout << "[TouchScreenTaskMujocoTest] selected arm config: " + << arm_config_path << std::endl; + cmvr::config::ArmRootConfig arm_root; + ASSERT_TRUE(ProtoMessageIo::getProtoFromAsciiFile(arm_config_path, &arm_root)); + const auto& arms = arm_root.arm().robot_arms(); + const auto arm_config = std::find_if(arms.begin(), arms.end(), [](const auto& config) { + return config.id() == "mujoco_right_arm"; + }); + ASSERT_NE(arm_config, arms.end()); + ASSERT_EQ(arm_config->motor().motor_system_id(), "right_arm_mujoco_motors"); + ASSERT_EQ(arm_config->motor().motor_group_ids_size(), 1); + ASSERT_EQ(arm_config->motor().motor_group_ids(0), "right_arm_mujoco_motors"); + const auto& kinematics = arm_config->kinematics(); + const auto& urdf_path = kinematics.has_pinocchio_qp_ik_solver() + ? kinematics.pinocchio_qp_ik_solver().urdf_path() + : kinematics.pinocchio_dls_ik_solver().urdf_path(); + ASSERT_EQ(urdf_path, "model/xiaoyan_description/dual_arm.urdf"); + if (touch_config.approach().enable()) { + ASSERT_TRUE(arm_config->motion().has_joint_path()) + << arm_config_path << " requires motion.joint_path for touch approach MoveP"; + } + cmvr::task::TaskManager::destroyInstance(); cmvr::device::DeviceManager::destroyInstance(); - // This test intentionally builds only the devices required by the - // MuJoCo Eye-to-Hand task. The task itself is still loaded from - // touch_screen_task_mujoco.pb.txt below. + // Build only the MuJoCo Eye-to-Hand devices while using the arm config + // selected by the runtime manager and the task's checked-in config. cmvr::config::DeviceManagerConfig device_manager_config; device_manager_config.set_name("touch_screen_eye_to_hand_mujoco_test"); device_manager_config.set_version("test"); @@ -416,7 +967,7 @@ TEST(TouchScreenTaskTest, RunEyeToHandTouchInMujoco) { "devices/motor/mujoco_motors.pb.txt"); add_device("mujoco_right_arm", cmvr::config::DeviceConfigEntry::DEVICE_TYPE_ROBOT_ARM, - "devices/arm/arm_mujoco.pb.txt"); + arm_entry->config_file().c_str()); add_device("mujoco_zero_touch_dexhand", cmvr::config::DeviceConfigEntry::DEVICE_TYPE_DEXHAND, "devices/dexhand/dexhand.pb.txt"); @@ -504,9 +1055,23 @@ TEST(TouchScreenTaskTest, RunEyeToHandTouchInMujoco) { add_configured_pip(*external_mujoco_camera); add_configured_pip(*hand_mujoco_camera); + const char* autoclose_env = std::getenv("CMVR_TOUCH_TEST_AUTOCLOSE"); + const bool auto_close = autoclose_env && std::string(autoclose_env) == "1"; + const char* cancel_env = std::getenv("CMVR_TOUCH_TEST_CANCEL_APPROACH"); + const bool cancel_approach = cancel_env && std::string(cancel_env) == "1"; + const char* failure_env = std::getenv("CMVR_TOUCH_TEST_APPROACH_FAILURES"); + const bool check_approach_failures = failure_env && std::string(failure_env) == "1"; + struct Outcome { bool init_ok{false}; bool touch_ok{false}; + bool approach_seen{false}; + bool alignment_seen{false}; + bool alignment_before_approach{false}; + bool cancellation_ok{false}; + double cancellation_duration_s{0.0}; + bool rejection_ok{false}; + bool timeout_ok{false}; bool align_reached{false}; bool retracting_seen{false}; bool finished{false}; @@ -520,12 +1085,11 @@ TEST(TouchScreenTaskTest, RunEyeToHandTouchInMujoco) { std::string error; } outcome; - // The viewer owns the lifetime of this test. Closing its window asks the - // worker to stop; a completed touch cycle must not close the viewer. + // Interactive runs keep the viewer open; automated runs opt in to closing + // after the scenario so gtest can report its assertions and exit. std::atomic stop_requested{false}; std::thread scenario([&] { try { - const auto touch_config = loadMujocoTouchConfig(project_root); if (touch_config.devices().arm_id() != "mujoco_right_arm" || touch_config.devices().camera_id() != "mujoco_hand_cam" || touch_config.devices().external_camera_id() != @@ -568,6 +1132,72 @@ TEST(TouchScreenTaskTest, RunEyeToHandTouchInMujoco) { std::cout << "[TouchScreenTaskMujocoTest] touch target pixel: u=" << target_u << ", v=" << target_v << std::endl; + const auto max_joint_change = [](const std::vector& before, + const std::vector& after) { + if (before.empty() || before.size() != after.size()) { + throw std::runtime_error("invalid joint feedback in approach scenario"); + } + double change = 0.0; + for (std::size_t i = 0; i < before.size(); ++i) { + if (!std::isfinite(before[i]) || !std::isfinite(after[i])) { + throw std::runtime_error("nonfinite joint feedback in approach scenario"); + } + change = std::max(change, std::abs(after[i] - before[i])); + } + return change; + }; + + if (cancel_approach) { + if (!touch_config.approach().enable() || + !task->touch(target_u, target_v)) { + throw std::runtime_error("failed to start approach cancellation scenario"); + } + const auto cancel_deadline = std::chrono::steady_clock::now() + + std::chrono::duration(touch_config.approach().timeout_s() + 2.0); + const auto approach_start_joints = arm->getJointState().position; + bool approach_in_progress = false; + while (!stop_requested.load(std::memory_order_acquire) && + task->isBusy() && std::chrono::steady_clock::now() < cancel_deadline) { + if (task->phase() == cmvr::task::TouchScreenTask::Phase::APPROACHING && + arm->busy()) { + const auto joints = arm->getJointState(); + const bool moving = max_joint_change(approach_start_joints, joints.position) > 1e-4 || + std::any_of(joints.velocity.begin(), joints.velocity.end(), + [](double velocity) { return std::abs(velocity) > 0.01; }); + if (moving && task->phase() == cmvr::task::TouchScreenTask::Phase::APPROACHING) { + approach_in_progress = true; + break; + } + } + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + const auto stop_start = std::chrono::steady_clock::now(); + task->stop(); + outcome.cancellation_duration_s = std::chrono::duration( + std::chrono::steady_clock::now() - stop_start).count(); + if (!approach_in_progress) { + throw std::runtime_error("never observed active MoveP before cancellation"); + } + // Keep periodic stepping active: neither the stopped worker nor + // a later step may resume commands or advance the stopped run. + const auto idle_deadline = std::chrono::steady_clock::now() + + std::chrono::milliseconds(100); + do { + const auto status = task->lastStatus(); + if (task->isBusy() || arm->busy() || + task->phase() != cmvr::task::TouchScreenTask::Phase::IDLE || + (status != cmvr::task::TouchScreenTask::Status::STOPPED && + status != cmvr::task::TouchScreenTask::Status::IDLE)) { + throw std::runtime_error("approach cancellation left active motion or task state"); + } + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } while (std::chrono::steady_clock::now() < idle_deadline); + outcome.cancellation_ok = true; + std::cout << "[TouchScreenTaskMujocoTest] approach cancelled in " + << outcome.cancellation_duration_s << " s; restarting touch" + << std::endl; + } + const bool touch_started = task->touch(target_u, target_v); if (!touch_started) { throw std::runtime_error( @@ -599,6 +1229,13 @@ TEST(TouchScreenTaskTest, RunEyeToHandTouchInMujoco) { std::sqrt(speedl.vx * speedl.vx + speedl.vy * speedl.vy + speedl.vz * speedl.vz)); const auto phase = task->phase(); + if (phase == cmvr::task::TouchScreenTask::Phase::APPROACHING) { + outcome.approach_seen = true; + } + if (phase == cmvr::task::TouchScreenTask::Phase::ALIGNING) { + outcome.alignment_seen = true; + outcome.alignment_before_approach |= !outcome.approach_seen; + } if (task->lastStatus() == cmvr::task::TouchScreenTask::Status::ALIGN_REACHED || phase == cmvr::task::TouchScreenTask::Phase::TOUCHING || @@ -623,9 +1260,6 @@ TEST(TouchScreenTaskTest, RunEyeToHandTouchInMujoco) { << cmvr::task::TouchScreenTask::statusToString( task->lastStatus()) << ", active_tag=" << task->lastActiveTagId() - << ", tcp_pose=" - << cmvr::perception::TagRelativeTcpPose::statusToString( - task->tcpPoseTracker().lastStatus()) << ", pressure=" << task->lastTouchPressureSum() << std::endl; } @@ -642,22 +1276,92 @@ TEST(TouchScreenTaskTest, RunEyeToHandTouchInMujoco) { outcome.finished = task->isFinished(); outcome.final_phase = task->phase(); outcome.final_status = task->lastStatus(); + outcome.max_pressure = std::max( + outcome.max_pressure, task->lastTouchPressureSum()); + + if (check_approach_failures) { + task->stop(); + task_manager.stopRunTask(); + const auto stays_stationary = [&](const std::vector& positions) { + const auto until = std::chrono::steady_clock::now() + std::chrono::milliseconds(100); + do { + if (arm->busy() || max_joint_change(positions, arm->getJointState().position) > 1e-4) { + return false; + } + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } while (std::chrono::steady_clock::now() < until); + return true; + }; + const auto before_rejection = arm->getJointState().position; + cmvr::device::MotionOptions reject_options; + reject_options.velocity = touch_config.approach().velocity(); + reject_options.acceleration = touch_config.approach().acceleration(); + reject_options.jerk = touch_config.approach().jerk(); + bool predicate_called = false; + reject_options.is_tcp_pose_valid = [&](const cmvr::device::CartesianPose&) { + predicate_called = true; + return false; + }; + const auto rejected = arm->moveP(arm->getTcpPose(), reject_options); + outcome.rejection_ok = !rejected.ok() && predicate_called && stays_stationary(before_rejection); + if (!outcome.rejection_ok) { + throw std::runtime_error("MoveP did not reject the TCP constraint without motion"); + } + + auto timeout_config = touch_config; + timeout_config.mutable_approach()->set_timeout_s(0.001); + timeout_config.mutable_initialization()->set_before_start(false); + timeout_config.mutable_initialization()->set_after_finish(true); + timeout_config.mutable_initialization()->set_after_failure(false); + // A different return target makes an unintended automatic MoveJ observable. + auto* return_joint = timeout_config.mutable_initialization()->mutable_joint_positions(0); + return_joint->set_rad(return_joint->rad() + 0.05); + cmvr::task::TouchScreenTask timeout_task(timeout_config); + auto dexhand = device_manager.getDevice( + touch_config.devices().dexhand_id()); + if (!timeout_task.init(arm, dexhand, hand_camera, external_camera) || + !timeout_task.touch(target_u, target_v)) { + throw std::runtime_error("failed to start approach timeout scenario"); + } + const auto before_timeout = arm->getJointState().position; + const auto timeout_deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5); + bool timeout_approach_seen = false; + bool timeout_alignment_seen = false; + while (!stop_requested.load(std::memory_order_acquire) && timeout_task.isBusy() && + std::chrono::steady_clock::now() < timeout_deadline) { + const bool step_ok = timeout_task.step(0.001); + timeout_approach_seen |= timeout_task.phase() == cmvr::task::TouchScreenTask::Phase::APPROACHING; + timeout_alignment_seen |= timeout_task.phase() == cmvr::task::TouchScreenTask::Phase::ALIGNING; + if (!step_ok) break; + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + outcome.timeout_ok = timeout_approach_seen && !timeout_alignment_seen && + timeout_task.phase() == cmvr::task::TouchScreenTask::Phase::FAILED && + timeout_task.lastStatus() == cmvr::task::TouchScreenTask::Status::APPROACH_TIMEOUT && + stays_stationary(before_timeout); + timeout_task.stop(); + if (!outcome.timeout_ok) { + throw std::runtime_error("approach timeout advanced alignment or moved after failure"); + } + std::cout << "[TouchScreenTaskMujocoTest] constraint rejection and timeout passed" << std::endl; + } + std::cout << "[TouchScreenTaskMujocoTest] touch finished once, phase=" << cmvr::task::TouchScreenTask::phaseToString( outcome.final_phase) - << "; viewer remains running" << std::endl; + << (auto_close ? "; closing viewer" : "; viewer remains running") + << std::endl; - // Keep the viewer and its camera frames alive after the task has - // run once. The main thread sets stop_requested when the window - // is closed. - while (!stop_requested.load(std::memory_order_acquire)) { - std::this_thread::sleep_for(std::chrono::milliseconds(100)); + if (auto_close) { + viewer.requestStop(); + } else { + while (!stop_requested.load(std::memory_order_acquire)) { + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + } } task->stop(); task_manager.stopRunTask(); - std::cout << "[TouchScreenTaskMujocoTest] viewer is still running; " - "close the MuJoCo window to finish gtest." << std::endl; } catch (const std::exception& error) { try { cmvr::task::TaskManager::getInstance().stopRunTask(); @@ -665,9 +1369,11 @@ TEST(TouchScreenTaskTest, RunEyeToHandTouchInMujoco) { } outcome.error = error.what(); stop_requested.store(true, std::memory_order_release); + if (auto_close) viewer.requestStop(); std::cerr << "[TouchScreenTaskMujocoTest] scenario error: " << outcome.error - << "; viewer remains open, close it manually to finish gtest." + << (auto_close ? "; closing viewer" + : "; viewer remains open, close it manually to finish gtest.") << std::endl; } }); @@ -684,8 +1390,31 @@ TEST(TouchScreenTaskTest, RunEyeToHandTouchInMujoco) { EXPECT_TRUE(outcome.error.empty()) << outcome.error; EXPECT_TRUE(outcome.init_ok); EXPECT_TRUE(outcome.touch_ok); + if (touch_config.approach().enable()) { + EXPECT_TRUE(outcome.approach_seen); + EXPECT_TRUE(outcome.alignment_seen); + EXPECT_FALSE(outcome.alignment_before_approach); + } + if (cancel_approach) { + EXPECT_TRUE(outcome.cancellation_ok); + EXPECT_LT(outcome.cancellation_duration_s, 1.0); + } + if (check_approach_failures) { + EXPECT_TRUE(outcome.rejection_ok); + EXPECT_TRUE(outcome.timeout_ok); + } EXPECT_TRUE(outcome.align_reached); EXPECT_GT(outcome.speedl_command_norm, 0.005); + if (!touch_config.alignment().pause_when_reached()) { + // ZeroSimTouchDexHand always reports zero force. This scenario must + // reach the forward-distance limit, retract, and report no contact. + EXPECT_DOUBLE_EQ(outcome.max_pressure, 0.0); + EXPECT_TRUE(outcome.retracting_seen); + EXPECT_FALSE(outcome.finished); + EXPECT_EQ(outcome.final_phase, cmvr::task::TouchScreenTask::Phase::FAILED); + EXPECT_EQ(outcome.final_status, + cmvr::task::TouchScreenTask::Status::TOUCH_FORWARD_TIMEOUT); + } } TEST(TouchScreenTaskTest, DISABLED_RunTouchOnceInMujoco) { diff --git a/data/ik/plot_joint_traj.py b/data/ik/plot_joint_traj.py deleted file mode 100644 index 01c4a884..00000000 --- a/data/ik/plot_joint_traj.py +++ /dev/null @@ -1,59 +0,0 @@ -# pip install toppra numpy scipy pandas matplotlib -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -import toppra as ta -import toppra.algorithm as algo -import toppra.constraint as constraint -import toppra.interpolator as interp - -# === 1) 读取 CSV(只取 q1..q7)=== -CSV_PATH = "/home/lgv/cmvr/cmvr-es/data/ik_psi_sweep.csv" # -joint_cols = ["q1","q2","q3","q4","q5","q6","q7"] -df = pd.read_csv(CSV_PATH) -assert all(c in df.columns for c in joint_cols), "CSV 缺少关节列 q1..q7" -waypoints = df[joint_cols].to_numpy() -N, dof = waypoints.shape -assert N >= 2, "至少需要两行关节路点" - -# === 2) 构造样条路径(路径参数 s∈[0,1])=== -s_grid = np.linspace(0, 1, N) -path = interp.SplineInterpolator(s_grid, waypoints) - -# === 3) 约束(示例值:请改成你的真实上限)=== -vmax = np.array([1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5]) # rad/s -amax = np.array([1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]) # rad/s^2 -vlim = np.vstack([-vmax, vmax]).T -alim = np.vstack([-amax, amax]).T -pc_vel = constraint.JointVelocityConstraint(vlim) -pc_acc = constraint.JointAccelerationConstraint(alim) - -# === 4) toppra 时间最优轨迹(起止速度=0)=== -topp = algo.TOPPRA([pc_vel, pc_acc], path, solver_wrapper="seidel") -traj = topp.compute_trajectory(0.0, 0.0) -T = traj.get_duration() -print(f"Total duration: {T:.4f} s") - -# === 5) 采样并绘图 === -ts = np.linspace(0, T, 300) -q = traj.eval(ts) # (300,7) -qd = traj.evald(ts) -qdd = traj.evaldd(ts) - -# 位置 -plt.figure() -for i in range(dof): - plt.plot(ts, q[:, i], label=f"q{i+1}") -plt.xlabel("Time (s)"); plt.ylabel("Position (rad)"); plt.title("Joint Positions"); plt.legend(); plt.tight_layout(); plt.show() - -# 速度 -plt.figure() -for i in range(dof): - plt.plot(ts, qd[:, i], label=f"qd{i+1}") -plt.xlabel("Time (s)"); plt.ylabel("Velocity (rad/s)"); plt.title("Joint Velocities"); plt.legend(); plt.tight_layout(); plt.show() - -# 加速度 -plt.figure() -for i in range(dof): - plt.plot(ts, qdd[:, i], label=f"qdd{i+1}") -plt.xlabel("Time (s)"); plt.ylabel("Acceleration (rad/s²)"); plt.title("Joint Accelerations"); plt.legend(); plt.tight_layout(); plt.show() diff --git a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/algorithm.hpp b/dependency/arm/third_party/toppra/v0.6.2/include/toppra/algorithm.hpp deleted file mode 100644 index 84a8f2ee..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/algorithm.hpp +++ /dev/null @@ -1,168 +0,0 @@ -#ifndef TOPPRA_ALGORITHM_HPP -#define TOPPRA_ALGORITHM_HPP - -#include -#include -#include -#include -#include -#include - -namespace toppra { - -/// Return code for Path Parametrization algorithm. -enum class ReturnCode { - - /// Success - OK = 0, - - /// Unknown error - ERR_UNKNOWN = 1, - - /// Fail during computing controllable sets. Problem might be infeasible. - ERR_FAIL_CONTROLLABLE = 2, - - /// Fail during forward pass. Numerical error occured. - ERR_FAIL_FORWARD_PASS = 3, - - /// Problem is not initialized - ERR_UNINITIALIZED = 4, - - /// Fail to ocmpute feasible sets. - ERR_FAIL_FEASIBLE = 5, -}; - -struct ParametrizationData { - /// \brief Grid-points used for solving the discretized problem. - /// The number of points must equal m_N + 1. - Vector gridpoints; - - /// Output parametrization (squared path velocity) - Vector parametrization; - - Matrix controllable_sets; - Matrix feasible_sets; - - /// Return code of the algorithm. - ReturnCode ret_code = ReturnCode::ERR_UNINITIALIZED; -}; - -/** \brief Base class for time parametrization algorithms. - * - */ -class PathParametrizationAlgorithm { - public: - /** Construct the problem instance. - * - * \param constraints List of constraints. - * \param path The geometric path. - * - */ - PathParametrizationAlgorithm(LinearConstraintPtrs constraints, - const GeometricPathPtr &path); - - /** \brief Set the level of discretization used by the solver. - * - * If is zero, will attempt to detect automatically the most - * suitable grid. - * - * TODO: Automatic gridpoint selection is not implemented in the CPP - * API. - */ - void setN(int N) { m_N = N; m_initialized = false; }; - - /** \brief Set the gridpoints (points with the path intervals) - * - * If not set manually, then N equally distributed points is used. - */ - void setGridpoints(const Vector& gridpoints); - - /** \brief Set the LP/QP solver - * - * Default to \ref solver::qpOASESWrapper - */ - void solver(SolverPtr solver) { m_solver.swap(solver); }; - - /** \brief Get output or result of algorithm. - */ - const ParametrizationData& getParameterizationData() const { return m_data; }; - - /** Compute the time parametrization of the given path. - * - * \param vel_start - * \param vel_end - * \return Return code. When not ReturnCode::OK, - * check PathParametrizationAlgorithm::getErrorMessage - */ - virtual ReturnCode computePathParametrization(value_type vel_start = 0, - value_type vel_end = 0); - - /** Compute the sets of feasible squared velocities. - */ - ReturnCode computeFeasibleSets(); - - /** Set initial bounds on \f$ \dot{s}^2. - * This is helpfull when the solver encounters numerical issues. - */ - void setInitialXBounds (const Bound& xbound) - { - m_initXBound = xbound; - } - - /** Get the error message when PathParametrizationAlgorithm::computePathParametrization - * failed. - */ - std::string getErrorMessage() const { - return m_errorStream.str(); - } - - virtual ~PathParametrizationAlgorithm() {} - - protected: - /** \brief Select solver and gridpoints to use. - * - * This method implements a simple way to select gridpoints. - */ - virtual void initialize(); - - /** \brief Compute the forward pass. - * - * Derived class should provide a suitable forward pass function, - * depending on the desired objective. - */ - virtual ReturnCode computeForwardPass(value_type vel_start) = 0; - - /** Compute the sets of controllable squared path velocities. - */ - ReturnCode computeControllableSets(const Bound &vel_ends); - - /** To be implemented in child method. */ - LinearConstraintPtrs m_constraints; - GeometricPathPtr m_path; - SolverPtr m_solver; - - std::stringstream m_errorStream; - - /// Struct containing algorithm output. - ParametrizationData m_data; - - /// \brief Number of segments in the discretized problems. - /// See m_gridpoints for more information. - int m_N = 100; - - int m_initialized = false; - - /** Set initial bounds on \f$ \dot{s}^2. - * \sa setInitialXBounds - * \todo The hard-coded bound below avoids numerical issues in LP / QP solvers - * when \f$ x \f$ becomes too big. This issue should be addressed in the - * solver wrapper themselfves as numerical behaviors is proper to each - * individual solver. - * See https://github.com/hungpham2511/toppra/issues/156 - */ - Bound m_initXBound = {0, 100}; -}; - -} // namespace toppra - -#endif diff --git a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/algorithm/toppra.hpp b/dependency/arm/third_party/toppra/v0.6.2/include/toppra/algorithm/toppra.hpp deleted file mode 100644 index 3956e87e..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/algorithm/toppra.hpp +++ /dev/null @@ -1,21 +0,0 @@ -#ifndef TOPPRA_ALGORITHM_TOPPRA_HPP -#define TOPPRA_ALGORITHM_TOPPRA_HPP - -#include -#include -#include -#include "toppra/toppra.hpp" - -namespace toppra { -namespace algorithm { -class TOPPRA : public PathParametrizationAlgorithm { - public: - TOPPRA(LinearConstraintPtrs constraints, const GeometricPathPtr &path); - - protected: - ReturnCode computeForwardPass(value_type vel_start); -}; -} // namespace algorithm -} // namespace toppra - -#endif diff --git a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint.hpp b/dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint.hpp deleted file mode 100644 index 97e0a666..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint.hpp +++ /dev/null @@ -1,174 +0,0 @@ -#ifndef TOPPRA_CONSTRAINT_HPP -#define TOPPRA_CONSTRAINT_HPP - -#include -#include - -namespace toppra { -/** Enum to mark different Discretization Scheme for LinearConstraint. - * In general, the difference in speed is not too large. Should use - * \ref Interpolation if possible. - * */ -enum DiscretizationType { - Collocation, ///< smaller problem size, but lower accuracy. - Interpolation, ///< larger problem size, but higher accuracy. -}; - -/** \brief Abstract interface for constraints used in TOPPRA. - * - * This class of constraint is also known as Second-order Constraint. - * - * A Canonical Linear Constraint has the following form: - * \f{eqnarray} - * \mathbf a_i u + \mathbf b_i x + \mathbf c_i &= v \\ - * \mathbf F_i v & \leq \mathbf g_i \\ - * x^b_{i, 0} \leq x & \leq x^b_{i, 1} \\ - * u^b_{i, 0} \leq u & \leq u^b_{i, 1} - * \f} - * - * Here \f$u\f$ and \f$x\f$ represent the path acceleration and path velocity - * square. \f$v$\f is an auxilliary variable that represents either the robot - * joint/taskspace velocity, acceleration or torque, or just the squared path - * velocity term only. - * - * Alternatively, if \f$ \mathbf F_i \f$ is constant for all values - * of \f$i\f$, then we can consider the simpler constraint: - * \f[ - * \mathbf{F} v \leq \mathbf g - * \f] - * - * In this case, the returned value of \f$F\f$ by - * LinearConstraint::computeParams has shape (k, m) instead of (N, k, m), - * \f$ g \f$ (k) instead of (N, k) and the class attribute - * LinearConstraint::constantF will be \c true. - * - * \note Derived classes should at least implement the method - * LinearConstraint::computeParams_impl. - * - * \sa JointAccelerationConstraint, JointVelocityConstraint, - * CanonicalLinearSecondOrderConstraint - * - * */ -class LinearConstraint { - public: - DiscretizationType discretizationType () const - { - return m_discretizationType; - } - - void discretizationType (DiscretizationType type); - - /** Tells whether \f$ F, g \f$ matrices are the same over all the grid points. - * In this case, LinearConstraint::computeParams F and g parameters should - * only be of size 1. - * */ - bool constantF () const - { - return m_constantF; - } - - /// Dimension of \f$g\f$. - Eigen::Index nbConstraints () const - { - return m_k; - } - - /// Dimension of \f$a, b, c, v\f$. - Eigen::Index nbVariables () const - { - return m_m; - } - - bool hasLinearInequalities () const - { - return nbConstraints() > 0; - } - - /** Whether this constraint has bounds on \f$u\f$. - * */ - bool hasUbounds () const - { - return m_hasUbounds; - } - - /** Whether this constraint has bounds on \f$x\f$. - * */ - bool hasXbounds () const - { - return m_hasXbounds; - } - - /** - * \param N number of gripoints (i.e. the number of intervals + 1) - * */ - void allocateParams (std::size_t N, - Vectors& a, Vectors& b, Vectors& c, - Matrices& F, Vectors& g, - Bounds ubound, Bounds& xbound); - - /** Compute numerical coefficients of the given constraint. - * - * \param[in] path The geometric path. - * \param[in] gridpoints Vector of size N+1. Gridpoint use for discretizing path. - * - * \param[out] a N+1 Vector of size m. - * \param[out] b N+1 Vector of size m. - * \param[out] c N+1 Vector of size m. - * \param[out] F N+1 Matrix of shape (k, m). If LinearConstraint::constantF - * is \c true, there is only one such Matrix. - * \param[out] g N+1 Vector of size m. - * \param[out] ubound Shape (N + 1, 2). See notes. - * \param[out] xbound Shape (N + 1, 2). See notes. - * - * \note the output must be allocated to correct sizes prior to calling this - * function. - * - * \todo check constness - * - * */ - void computeParams(const GeometricPath& path, const Vector& gridpoints, - Vectors& a, Vectors& b, Vectors& c, - Matrices& F, Vectors& g, - Bounds& ubound, Bounds& xbound); - - virtual std::ostream& print(std::ostream& os) const; - - virtual ~LinearConstraint () {} - - protected: - /** - * \param k number of inequality constraints. - * \param m number of internal variable (i.e. dimention of \f$v\f$). - * \param constantF whether \f$F\f$ and \f$g\f$ are constant. - * \param uBound whether \f$u\f$ is bounded. - * \param xBound whether \f$x\f$ is bounded. - * */ - LinearConstraint(Eigen::Index k, Eigen::Index m, bool constantF, - bool uBound, bool xBound) - : m_discretizationType (Interpolation) - , m_k (k), m_m (m) - , m_constantF (constantF) - , m_hasUbounds (uBound) - , m_hasXbounds (xBound) - {} - - virtual void computeParams_impl(const GeometricPath& path, - const Vector& gridpoints, - Vectors& a, Vectors& b, Vectors& c, - Matrices& F, Vectors& g, - Bounds& ubound, Bounds& xbound) = 0; - - Eigen::Index m_k, m_m; - DiscretizationType m_discretizationType; - bool m_constantF, m_hasUbounds, m_hasXbounds; -}; // class LinearConstraint - -/// \brief write a LinearConstraint to an output stream -inline std::ostream& operator<< (std::ostream& os, const LinearConstraint& lc) -{ - return lc.print(os); -} - -} // namespace toppra - -#endif diff --git a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint/cartesian_velocity_norm.hpp b/dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint/cartesian_velocity_norm.hpp deleted file mode 100644 index bb3d8515..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint/cartesian_velocity_norm.hpp +++ /dev/null @@ -1,94 +0,0 @@ -#ifndef TOPPRA_CONSTRAINT_CARTESIAN_VELOCITY_NORM_HPP -#define TOPPRA_CONSTRAINT_CARTESIAN_VELOCITY_NORM_HPP - -#include - -namespace toppra { -namespace constraint { - -/** -\brief A cartesian velocity constraint class. - -Given a path \f$ p(s) \f$, this class constraints the norm -\f$||v||_S^2 = v^T S v \leq limit \f$ of the velocity \f$v\f$ of a frame. -As \f$ v = J(p(s)) p'(s) \dot{s} \f$, it fits into a LinearConstraint as follows. - -\f{eqnarray} - p'(s)^T J(q)^T S J(q) p'(s) \dot{s}^2 &= w \\ - w & \leq \mathbf g_i \\ -\f} - -This class implements the case of constant velocity limits but can be derived to -achieve varying velocity limits. E.g. -\code -class CartesianVelocityVarying : public CartesianVelocityNorm { -public: - CartesianVelocityVarying(...) : CartesianVelocityNorm () {} -protected: - void computeVelocityLimit(value_type time) - { - // Eventually, if one of the two is constant, it can be set in the constructor. - m_limit = ...; - m_S = ...; - } -}; -\endcode -*/ -class CartesianVelocityNorm : public LinearConstraint { - public: - virtual std::ostream& print(std::ostream& os) const; - - protected: - /// Constructor for constant velocity limit. - CartesianVelocityNorm (const Matrix& S, const double& limit) - : LinearConstraint (1, 1, true, false, false) - , m_limit (limit) - , m_S (S) - { - check(); - } - - /// Constructor for varying velocity limit. - /// \note Attributes \ref m_S and \ref m_limit **must** be computed in - /// \ref computeVelocityLimit - CartesianVelocityNorm () - : LinearConstraint (1, 1, false, false, false) - , m_limit (1.) - , m_S (6,6) - { - check(); - } - - /// Pure abstract method to compute the velocity from - /// \param q the current configuration - /// \param qdot the current velocity - /// \retval v the 6D frame velocity - virtual void computeVelocity (const Vector& q, const Vector& qdot, - Vector& v) = 0; - - /** - \brief Computes the velocity limit at time \c time. - - The result must be stored into attribute - CartesianVelocityNorm::m_limit - */ - virtual void computeVelocityLimit(value_type time) { (void)time; } - - /// The velocity limit - value_type m_limit; - /// The selection matrix - Matrix m_S; - - private: - void check(); - - void computeParams_impl(const GeometricPath& path, - const Vector& gridpoints, - Vectors& a, Vectors& b, Vectors& c, - Matrices& F, Vectors& g, - Bounds& ubound, Bounds& xbound); -}; // class CartesianVelocityNorm -} // namespace constraint -} // namespace toppra - -#endif diff --git a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint/cartesian_velocity_norm/pinocchio.hpp b/dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint/cartesian_velocity_norm/pinocchio.hpp deleted file mode 100644 index 23515af2..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint/cartesian_velocity_norm/pinocchio.hpp +++ /dev/null @@ -1,86 +0,0 @@ -#ifndef TOPPRA_CONSTRAINT_CARTESIAN_VELOCITY_NORM_PINOCCIO_HPP -#define TOPPRA_CONSTRAINT_CARTESIAN_VELOCITY_NORM_PINOCCIO_HPP - -#include -#include - -#include -#include - -#include - -namespace toppra { -namespace constraint { -namespace cartesianVelocityNorm { - -/** Implementation of CartesianVelocityNorm using pinocchio function. - * \extends CartesianVelocityNorm - * */ -template -class Pinocchio; - -template -class Pinocchio : public CartesianVelocityNorm { - public: - typedef _Model Model; - typedef typename Model::Data Data; - - std::ostream& print(std::ostream& os) const - { - return CartesianVelocityNorm::print(os << "Pinocchio - "); - } - - void computeVelocity (const Vector& q, const Vector& qdot, Vector& v) - { - pinocchio::forwardKinematics(m_model, m_data, q, qdot); - v = pinocchio::getFrameVelocity(m_model, m_data, m_frame_id, m_reference_frame).toVector(); - } - - /// Constructor for constant velocity limit. - Pinocchio (const Model& model, const Matrix& S, const double& limit, - pinocchio::FrameIndex frame, - pinocchio::ReferenceFrame ref_frame = pinocchio::LOCAL_WORLD_ALIGNED) - : CartesianVelocityNorm (S, limit) - , m_model (model) - , m_data (model) - , m_frame_id (frame) - , m_reference_frame (ref_frame) - { - } - - /// Move-assignment operator - Pinocchio (Pinocchio&& other) - : CartesianVelocityNorm(other) - , m_model (other.m_model) - , m_data (std::move(other.m_data)) - , m_frame_id (m_frame_id) - , m_reference_frame (m_reference_frame) - {} - - const Model& model() const { return m_model; } - - protected: - /// Constructor for varying velocity limit. - Pinocchio (const Model& model, - pinocchio::FrameIndex frame, - pinocchio::ReferenceFrame ref_frame = pinocchio::LOCAL_WORLD_ALIGNED) - : CartesianVelocityNorm () - , m_model (model) - , m_data (model) - , m_frame_id (frame) - , m_reference_frame (ref_frame) - {} - - - private: - const Model& m_model; - Data m_data; - pinocchio::FrameIndex m_frame_id; - pinocchio::ReferenceFrame m_reference_frame; -}; // class Pinocchio - -} // namespace cartesianVelocityNorm -} // namespace constraint -} // namespace toppra - -#endif diff --git a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint/joint_torque.hpp b/dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint/joint_torque.hpp deleted file mode 100644 index ce36dc81..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint/joint_torque.hpp +++ /dev/null @@ -1,113 +0,0 @@ -#ifndef TOPPRA_CONSTRAINT_JOINT_TORQUE_HPP -#define TOPPRA_CONSTRAINT_JOINT_TORQUE_HPP - -#include - -namespace toppra { -namespace constraint { - -/** Base class for joint torque constraints. - * - * A joint torque constraint is given by - * \f[ - * A(q) \ddot q + \dot q^\top B(q) \dot q + C(q) + D( \dot q )= \tau - * \f] - * - * where w is a vector that satisfies the polyhedral constraint: - * \f[ F \tau \leq g \f] - * - * Notice that \f$ inverseDynamics(q, qd, qdd) = \tau\f$ and that - * \f$ F, g \f$ are independant of the GeometricPath. - * - * To evaluate the constraint on a geometric path `p(s)`, multiple - * calls to \ref computeInverseDynamics are made. Specifically one - * can derive the second-order equation as follows - * - * \f{eqnarray} - * A(q) p'(s) \ddot s &+ [A(q) p''(s) + p'(s)^\top B(q) p'(s)] \dot s^2 &+ C(q) + D( \dot q ) &= \tau \\ - * a(s) \ddot s &+ b(s) \dot s^2 &+ c(s) &= \tau - * \f} - * - * */ -class JointTorque : public LinearConstraint { - public: - virtual ~JointTorque () {} - - virtual std::ostream& print(std::ostream& os) const; - - /** Computes the joint torques from - * \param q robot configuration - * \param v robot velocity - * \param a robot acceleration - * \param[out] joint torques - * */ - virtual void computeInverseDynamics (const Vector& q, const Vector& v, const Vector& a, - Vector& tau) = 0; - - const Vector& lowerBounds () const - { return m_lower; } - - void lowerBounds (const Vector& lb) - { - assert(lb.size() == m_lower.size()); - m_lower = lb; - } - - const Vector& upperBounds () const - { return m_upper; } - - void upperBounds (const Vector& ub) - { - assert(ub.size() == m_upper.size()); - m_upper = ub; - } - - const Vector& frictionCoeffs () const - { return m_frictionCoeffs; } - - void frictionCoeffs (const Vector& fc) - { - assert(fc.size() == m_frictionCoeffs.size()); - m_frictionCoeffs = fc; - } - - protected: - /** - * \param lowerTlimit lower torque limit - * \param upperTlimit upper torque limit - * \param frictionCoeffs dry friction coefficients of each joint. - * size 0 when not considering friction. - * */ - JointTorque (const Vector& lowerTlimit, const Vector& upperTlimit, - const Vector& frictionCoeffs) - : LinearConstraint (2*lowerTlimit.size(), lowerTlimit.size(), true, false, false) - , m_lower (lowerTlimit) - , m_upper (upperTlimit) - , m_frictionCoeffs (frictionCoeffs) - { - check(); - } - - /// Move-assignment constructor - JointTorque (JointTorque&& other) - : LinearConstraint (other) - , m_lower(std::move(other.m_lower)) - , m_upper(std::move(other.m_upper)) - , m_frictionCoeffs(std::move(other.m_frictionCoeffs)) - {} - - private: - void check(); - - void computeParams_impl(const GeometricPath& path, - const Vector& gridpoints, - Vectors& a, Vectors& b, Vectors& c, - Matrices& F, Vectors& g, - Bounds& ubound, Bounds& xbound); - - Vector m_lower, m_upper, m_frictionCoeffs; -}; // class JointTorque -} // namespace constraint -} // namespace toppra - -#endif diff --git a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint/joint_torque/pinocchio.hpp b/dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint/joint_torque/pinocchio.hpp deleted file mode 100644 index 903abba1..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint/joint_torque/pinocchio.hpp +++ /dev/null @@ -1,87 +0,0 @@ -#ifndef TOPPRA_CONSTRAINT_JOINT_TORQUE_PINOCCIO_HPP -#define TOPPRA_CONSTRAINT_JOINT_TORQUE_PINOCCIO_HPP - -#include -#include -#include -#include - -#include - -namespace toppra { -namespace constraint { -namespace jointTorque { - -/** Implementation of JointTorque using pinocchio::rnea function. - * \extends JointTorque - * */ -template -class Pinocchio; - -template -class Pinocchio : public JointTorque { - public: - typedef _Model Model; - typedef typename Model::Data Data; - - std::ostream& print(std::ostream& os) const - { - return JointTorque::print(os << "Pinocchio - "); - } - - void computeInverseDynamics (const Vector& q, const Vector& v, const Vector& a, - Vector& tau) - { - tau = pinocchio::rnea(m_model, m_data, q, v, a); - } - - Pinocchio (const Model& model, const Vector& frictionCoeffs = Vector()) - : JointTorque (-model.effortLimit, model.effortLimit, frictionCoeffs) - , m_model (model) - , m_data (model) - { - } - - /// Move-assignment operator - Pinocchio (Pinocchio&& other) - : JointTorque(other) - , m_storage (std::move(other.m_storage)) - , m_model (other.m_model) - , m_data (std::move(other.m_data)) - {} - - Pinocchio (const std::string& urdfFilename, const Vector& friction = Vector()) - : Pinocchio (makeModel(urdfFilename), friction) {} - - const Model& model() const { return m_model; } - - private: - /// Build a pinocchio::Model - /// \param urdfFilename path to a URDF file. - static Model* makeModel (const std::string& urdfFilename) - { - Model* model (new Model); - pinocchio::urdf::buildModel(urdfFilename, *model); - return model; - } - - /// Constructor that takes ownership of the model - Pinocchio (Model* model, const Vector& friction) - : JointTorque (-model->effortLimit, model->effortLimit, friction) - , m_storage (model) - , m_model (*model) - , m_data (m_model) - { - } - - /// Store the pinocchio::Model object, in case this object owns it. - std::unique_ptr m_storage; - const Model& m_model; - Data m_data; -}; // class Pinocchio - -} // namespace jointTorque -} // namespace constraint -} // namespace toppra - -#endif diff --git a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint/linear_joint_acceleration.hpp b/dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint/linear_joint_acceleration.hpp deleted file mode 100644 index 2da8fda3..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint/linear_joint_acceleration.hpp +++ /dev/null @@ -1,36 +0,0 @@ -#ifndef TOPPRA_CONSTRAINT_LINEAR_JOINT_ACCELERATION_HPP -#define TOPPRA_CONSTRAINT_LINEAR_JOINT_ACCELERATION_HPP - -#include - -namespace toppra { -namespace constraint { - -/// A Joint Acceleration Constraint class. -class LinearJointAcceleration : public LinearConstraint { - public: - LinearJointAcceleration (const Vector& lowerAlimit, const Vector& upperAlimit) - : LinearConstraint (lowerAlimit.size() * 2, lowerAlimit.size(), true, false, false) - , m_lower (lowerAlimit) - , m_upper (upperAlimit) - { - check(); - } - - virtual std::ostream& print(std::ostream& os) const; - - private: - void check(); - - void computeParams_impl(const GeometricPath& path, - const Vector& gridpoints, - Vectors& a, Vectors& b, Vectors& c, - Matrices& F, Vectors& g, - Bounds& ubound, Bounds& xbound); - - Vector m_lower, m_upper; -}; // class LinearJointAcceleration -} // namespace constraint -} // namespace toppra - -#endif diff --git a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint/linear_joint_velocity.hpp b/dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint/linear_joint_velocity.hpp deleted file mode 100644 index a269c94b..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/constraint/linear_joint_velocity.hpp +++ /dev/null @@ -1,86 +0,0 @@ -#ifndef TOPPRA_CONSTRAINT_LINEAR_JOINT_VELOCITY_HPP -#define TOPPRA_CONSTRAINT_LINEAR_JOINT_VELOCITY_HPP - -#include - -namespace toppra { -namespace constraint { - -/** -\brief A Joint Velocity Constraint class. - -This class implements the case of constant velocity limits but can be derived to -achieve varying velocity limits. E.g. -\code -class LinearJointVelocityVarying : public LinearJointVelocity { -public: - LinearJointVelocityVarying(...) : LinearJointVelocity (nDof) {} -protected: - void computeVelocityLimits(value_type time) - { - m_lower = ...; - m_upper = ...; - } -}; -\endcode -*/ -class LinearJointVelocity : public LinearConstraint { - public: - LinearJointVelocity (const Vector& lowerVlimit, const Vector& upperVlimit) - : LinearConstraint (0, 0, true, false, true) - , m_lower (lowerVlimit) - , m_upper (upperVlimit) - , m_maxsd (1e8) - { - check(); - } - - /** Set the maximum allowed value of \f$\dot s\f$. - * \param maxsd should be strictly positive. - * */ - void maxSDot (value_type maxsd) - { - assert(maxsd > 0); - m_maxsd = maxsd; - } - - virtual std::ostream& print(std::ostream& os) const; - - protected: - LinearJointVelocity (const int nDof) - : LinearConstraint (0, 0, true, false, true) - , m_lower (nDof) - , m_upper (nDof) - , m_maxsd (1e8) - { - check(); - } - - /** - \brief Computes the velocity limit at time \c time. - - The result must be stored into attributes - LinearJointVelocity::m_lower and LinearJointVelocity::m_upper. - */ - virtual void computeVelocityLimits(value_type time) { (void)time; } - - /// The lower velocity limits - Vector m_lower; - /// The upper velocity limits - Vector m_upper; - - private: - void check(); - - void computeParams_impl(const GeometricPath& path, - const Vector& gridpoints, - Vectors& a, Vectors& b, Vectors& c, - Matrices& F, Vectors& g, - Bounds& ubound, Bounds& xbound); - - value_type m_maxsd; -}; // class LinearJointVelocity -} // namespace constraint -} // namespace toppra - -#endif diff --git a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/export.hpp b/dependency/arm/third_party/toppra/v0.6.2/include/toppra/export.hpp deleted file mode 100644 index cf498d88..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/export.hpp +++ /dev/null @@ -1,43 +0,0 @@ - -#ifndef TOPPRA_EXPORT_H -#define TOPPRA_EXPORT_H - -#ifdef TOPPRA_STATIC_DEFINE -# define TOPPRA_EXPORT -# define TOPPRA_NO_EXPORT -#else -# ifndef TOPPRA_EXPORT -# ifdef toppra_EXPORTS - /* We are building this library */ -# define TOPPRA_EXPORT __attribute__((visibility("default"))) -# else - /* We are using this library */ -# define TOPPRA_EXPORT __attribute__((visibility("default"))) -# endif -# endif - -# ifndef TOPPRA_NO_EXPORT -# define TOPPRA_NO_EXPORT __attribute__((visibility("hidden"))) -# endif -#endif - -#ifndef TOPPRA_DEPRECATED -# define TOPPRA_DEPRECATED __attribute__ ((__deprecated__)) -#endif - -#ifndef TOPPRA_DEPRECATED_EXPORT -# define TOPPRA_DEPRECATED_EXPORT TOPPRA_EXPORT TOPPRA_DEPRECATED -#endif - -#ifndef TOPPRA_DEPRECATED_NO_EXPORT -# define TOPPRA_DEPRECATED_NO_EXPORT TOPPRA_NO_EXPORT TOPPRA_DEPRECATED -#endif - -/* NOLINTNEXTLINE(readability-avoid-unconditional-preprocessor-if) */ -#if 0 /* DEFINE_NO_DEPRECATED */ -# ifndef TOPPRA_NO_DEPRECATED -# define TOPPRA_NO_DEPRECATED -# endif -#endif - -#endif /* TOPPRA_EXPORT_H */ diff --git a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/geometric_path.hpp b/dependency/arm/third_party/toppra/v0.6.2/include/toppra/geometric_path.hpp deleted file mode 100644 index cd6a49d6..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/geometric_path.hpp +++ /dev/null @@ -1,116 +0,0 @@ -#ifndef TOPPRA_GEOMETRIC_PATH_HPP -#define TOPPRA_GEOMETRIC_PATH_HPP - -#include -#include -#include -#include -#include -#include -#include - -namespace toppra { - - -/** - * \brief Abstract interface for geometric paths. - */ -class GeometricPath { -public: - - GeometricPath() = default; - - /** - * Constructor of GeometricPath on vector spaces. - */ - GeometricPath(int nDof) : m_configSize(nDof), m_dof (nDof) {} - - /** - * Constructor of GeometricPath on non-vector spaces. - */ - GeometricPath(int configSize, int nDof) : m_configSize(configSize), m_dof (nDof) {} - - /** - * \brief Evaluate the path at given position. - */ - virtual Vector eval_single(value_type, int order = 0) const = 0; - - /** - * \brief Evaluate the path at given positions (vector). - * - * Default implementation: Evaluation each point one-by-one. - */ - virtual Vectors eval(const Vector &positions, int order = 0) const; - - /** - \brief Generate gridpoints that sufficiently cover the given path. - - This function operates in multiple passes through the geometric - path from the start to the end point. In each pass, for each - segment, the maximum interpolation error is estimated using the - following equation: - - err_{est} = 0.5 * \mathrm{max}(\mathrm{abs}(p'' * d_{segment} ^ 2)) - - Here `p''` is the second derivative of the path and d_segment is - the length of the segment. If the estimated error `err_{test}` is - greater than the given threshold `max_err_threshold` then the - segment is divided in two half. - - Intuitively, at positions with higher curvature, there must be - more points in order to improve approximation - quality. Theoretically toppra performs the best when the proposed - gridpoint is optimally distributed. - - @param maxErrThreshold Maximum worstcase error thrshold allowable. - @param maxIteration Maximum number of iterations. - @param maxSegLength All segments length should be smaller than this value. - @param minNbPoints Minimum number of points. - @param initialGridpoints Initial gridpoints to start the algorithm from. If - not provided, the path interval is used. If not empty, it must start - and end with the path interval limits. - @return The proposed gridpoints. - - */ - Vector proposeGridpoints(double maxErrThreshold=1e-4, int maxIteration=100, double maxSegLength=0.05, int minNbPoints=100, Vector initialGridpoints = Vector()) const; - - /** - * \brief Dimension of the configuration space - */ - int configSize() const - { - return m_configSize; - } - - /** - * \return the number of degrees-of-freedom of the path. - */ - int dof() const - { - return m_dof; - } - - /** - * \brief Serialize path to stream. - */ - virtual void serialize(std::ostream &O) const {}; - - /** - * \brief Deserialize stream to construct path. - */ - virtual void deserialize(std::istream &I){}; - - /** - * \brief Starting and ending path positions. - */ - virtual Bound pathInterval() const = 0; - - virtual ~GeometricPath() {} - - protected: - int m_configSize, m_dof; -}; - -} // namespace toppra - -#endif diff --git a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/geometric_path/piecewise_poly_path.hpp b/dependency/arm/third_party/toppra/v0.6.2/include/toppra/geometric_path/piecewise_poly_path.hpp deleted file mode 100644 index e960eca1..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/geometric_path/piecewise_poly_path.hpp +++ /dev/null @@ -1,161 +0,0 @@ -#ifndef TOPPRA_PIECEWISE_POLY_PATH_HPP -#define TOPPRA_PIECEWISE_POLY_PATH_HPP - -#include -#include -#include -#include - -namespace toppra { - - -struct BoundaryCond { - BoundaryCond() = default; - - /** - * @brief Construct a new BoundaryCond object with a manually specified derivative. - * - * @param order Order of the specified derivative. - * @param values Vector of values. Must have the same size as the path. - */ - BoundaryCond(int order, const std::vector &values); - - BoundaryCond(int order, const Vector values); - - /** - * @brief Construct a new Boundary Cond object with well-known boundary condition. - * - * @param bc_type Possible values: not-a-knot, clamped, natural and manual. - */ - BoundaryCond(std::string bc_type); - - enum Type { NotAKnot, Clamped, Natural, Manual}; - Type bc_type = NotAKnot; - int order = 0; - Vector values; -}; - -using BoundaryCondFull = std::array; - - -/** - * \brief Piecewise polynomial geometric path. - * - * An implementation of a piecewise polynomial geometric path. - * - * The coefficient vector has shape (N, P, D), where N is the number - * segments. For each segment, the i-th row (P index) denotes the - * power, while the j-th column is the degree of freedom. In - * particular, - * - * coeff(0) * dt ^ 3 + coeff(1) * dt ^ 2 + coeff(2) * dt + coeff(3) - * - * - */ -class PiecewisePolyPath : public GeometricPath { - public: - PiecewisePolyPath() = default; - - /** - * \brief Construct new piecewise polynomial. - * - * See class docstring for details. - * - * @param coefficients Polynomial coefficients. - * @param breakpoints Vector of breakpoints. - */ - PiecewisePolyPath(const Matrices &coefficients, std::vector breakpoints); - - /** - * /brief Evaluate the path at given position. - */ - Vector eval_single(value_type, int order = 0) const override; - - /** - * /brief Evaluate the path at given positions (vector). - */ - Vectors eval(const Vector &, int order = 0) const override; - - /** - * Return the starting and ending path positions. - */ - Bound pathInterval() const override; - void serialize(std::ostream &O) const override; - void deserialize(std::istream &I) override; - - /** - * @brief Construct a piecewise Cubic Hermite polynomial. - * - * See https://en.wikipedia.org/wiki/Cubic_Hermite_spline for a good - * description of this interplation scheme. - * - * This function is implemented based on scipy.interpolate.CubicHermiteSpline. - * - * Note that path generates by this function is not guaranteed to have - * continuous acceleration, or the path second-order derivative. - * - * @param positions Robot joints corresponding to the given times. Must have - * the same size as times. - * @param velocities Robot joint velocities. - * @param times Path positions or times. This is the independent variable. - * @return PiecewisePolyPath - */ - static PiecewisePolyPath - CubicHermiteSpline(const Vectors &positions, const Vectors &velocities, - const std::vector times); - - TOPPRA_DEPRECATED static PiecewisePolyPath - constructHermite(const Vectors &positions, const Vectors &velocities, - const std::vector times); - - - /** - * @brief Construct a cubic spline. - * - * Interpolate the given joint positions with a spline that is twice - * continuously differentiable. This means the position, velocity and - * acceleration are guaranteed to be continous but not jerk. - * - * This method is modelled after scipy.interpolate.CubicSpline. - * - * @param positions Robot joints corresponding to the given times. - * @param times Path positions or times. This is the independent variable. - * @param bc_type Boundary condition. Currently on fixed boundary condition. - * @return PiecewisePolyPath - */ - static PiecewisePolyPath CubicSpline(const Vectors &positions, const Vector ×, BoundaryCondFull bc_type); - -private: - - /** - * @brief Calculate coefficients for Hermite spline. - * - * @param positions See the constructor. - * @param velocities - * @param times - */ - void initAsHermite(const Vectors &positions, const Vectors &velocities, - const std::vector times); - -protected: - static void computeCubicSplineCoefficients(const Vectors &positions, - const Vector ×, - const BoundaryCondFull &bc_type, - Matrices &coefficients); - // static void checkInputArgs(const Vectors &positions, const Vector ×, - // const BoundaryCondFull &bc_type); - - // Cubic spline - void reset(); - size_t findSegmentIndex(value_type pos) const; - void checkInputArgs(); - void computeDerivativesCoefficients(); - const Matrix &getCoefficient(size_t seg_index, int order) const; - Matrices m_coefficients, m_coefficients_1, m_coefficients_2; - std::vector m_breakpoints; - int m_degree; -}; - -} // namespace toppra - -#endif diff --git a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/parametrizer.hpp b/dependency/arm/third_party/toppra/v0.6.2/include/toppra/parametrizer.hpp deleted file mode 100644 index d5dea633..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/parametrizer.hpp +++ /dev/null @@ -1,75 +0,0 @@ -#ifndef TOPPRA_PARAMETRIZER_HPP -#define TOPPRA_PARAMETRIZER_HPP - -#include -#include - -namespace toppra { - -/** - * \brief Abstract output trajectory parametrizers. - * - * A parametrizer has the same interface as a geometric path. It - * receives as input the original geometric path and two arrays of - * gridpoints and parametrization (i.e. squared path velocities). A - * parametrizer should validate the input data. If not validated, - * evaluation results are not defined. - * - * Requirements: https://github.com/hungpham2511/toppra/issues/102 - * - * Sub-classes should override the virtual private methods *_impl. - */ -class Parametrizer : public GeometricPath { - public: - /** Construct the parametrizer. - * - * \param path Input geometric path. - * \param gridpoints Shape (N+1,). Gridpoints of the parametrization, should be - * compatible with the path domain. \param vsquared Shape (N+1,). Path velocity - * squared, should have same shape as gridpoints as vsquared[i] corresponds to the - * velocity at gridpoints[i]. - */ - Parametrizer(GeometricPathPtr path, const Vector &gridpoints, const Vector &vsquared); - - /** \brief Evaluate the path at given position. - */ - Vector eval_single(value_type, int order = 0) const override; - - /** \brief Evaluate the path at given positions (vector). - */ - Vectors eval(const Vector &, int order = 0) const override; - - /** \brief Return the starting and ending path positions. - */ - Bound pathInterval() const override; - - /** \brief Validate input data. - * - * Return false if something is wrong with the output - * trajectory. Only use the trajectory if validation successes. - */ - bool validate() const; - - virtual ~Parametrizer() {} - - /** \brief Return the waypoint times. - */ - virtual const Vector& getTimes() const = 0; - - protected: - // Input geometric path - GeometricPathPtr m_path; - // Input gridpoints - Vector m_gridpoints; - // Input path velocities (not squared) - Vector m_vs; - - private: - /// To be overwriten by derived classes - virtual Vectors eval_impl(const Vector &, int order = 0) const = 0; - virtual bool validate_impl() const = 0; - virtual Bound pathInterval_impl() const = 0; -}; -}; // namespace toppra - -#endif diff --git a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/parametrizer/const_accel.hpp b/dependency/arm/third_party/toppra/v0.6.2/include/toppra/parametrizer/const_accel.hpp deleted file mode 100644 index 7911671f..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/parametrizer/const_accel.hpp +++ /dev/null @@ -1,52 +0,0 @@ -#ifndef TOPPRA_CONST_ACCEL_HPP -#define TOPPRA_CONST_ACCEL_HPP - -#include -#include - -namespace toppra { - -namespace parametrizer { - -/** \brief A path parametrizer with constant acceleration assumption. - * - * We assume that in each segment, the path acceleration is constant. - */ -class ConstAccel : public Parametrizer { - public: - ConstAccel(GeometricPathPtr path, const Vector &gridpoints, const Vector &vsquared); - - const Vector& getTimes() const override { return m_ts; } - - private: - /** Return joint derivatives at specified times. */ - Vectors eval_impl(const Vector ×, int order = 0) const override; - bool validate_impl() const override; - Bound pathInterval_impl() const override; - - /** \brief Evaluate path variables ss, vs, and us at the input time instances. - * - * For each t, a starting gridpoint will be selected. The selected - * path position, velocity and acceleration is then used to compute - * the corresponding output quantities. - * - * \param[in] ts Time instances to be evaluated, starting from zero seconds. - * \param[out] ss Path positions at the given time instances. - * \param[out] vs Path velocities at the given time instances. - * \param[out] us Path accelerations at the given time instances. - * - */ - bool evalParams(const Vector &ts, Vector &ss, Vector &vs, Vector &us) const; - // Compute times and acclerations from given data (path, velocities) - void process_internals(); - // Vector of time instances (corresponded to gridpoints) - Vector m_ts; - // Vector of accelerations (corresponded to gridpoints). Should have size - // shorter than m_ts and m_vs by 1. - Vector m_us; -}; -} // namespace parametrizer - -} // namespace toppra - -#endif diff --git a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/parametrizer/spline.hpp b/dependency/arm/third_party/toppra/v0.6.2/include/toppra/parametrizer/spline.hpp deleted file mode 100644 index a5267255..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/parametrizer/spline.hpp +++ /dev/null @@ -1,47 +0,0 @@ -#ifndef TOPPRA_SPLINE_HPP -#define TOPPRA_SPLINE_HPP - -#include -#include - -namespace toppra { - -namespace parametrizer { - -/** \brief A path parametrizer via a spline interpolation. - * - * This class computes the time and position at each gridpoint, then - fit and return a CubicSpline (continuous first and second - derivatives). Note that the boundary conditions are: first - derivatives at the start and end of the path equal q(s)' * s'. - */ -class Spline: public Parametrizer { -public: - /** - * \brief Construct the spline parametrizer. - * - * See class docstring for details. - * - * @param path the input geometric path. - * @param gridpoints of the parametrization with shape (N+1,). - * @param vsquared the path velocity squared with shape (N+1,). - */ - Spline(GeometricPathPtr path, const Vector &gridpoints, const Vector &vsquared); - - const Vector& getTimes() const override { return m_ts; } - -private: - /** Return joint derivatives at specified times. */ - Vectors eval_impl(const Vector ×, int order = 0) const override; - bool validate_impl() const override; - Bound pathInterval_impl() const override; - - // Vector of time instances (corresponded to gridpoints) - Vector m_ts; -}; - -} // namespace parametrizer - -} // namespace toppra - -#endif diff --git a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/solver.hpp b/dependency/arm/third_party/toppra/v0.6.2/include/toppra/solver.hpp deleted file mode 100644 index 8e2e196a..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/solver.hpp +++ /dev/null @@ -1,138 +0,0 @@ -#ifndef TOPPRA_SOLVER_HPP -#define TOPPRA_SOLVER_HPP - -#include - -namespace toppra { - -/** \brief The base class for all solver wrappers. - * - * All Solver can solve Linear/Quadratic Program subject to linear constraints - * at the given stage, and possibly with additional auxiliary constraints. - * - * All Solver derived class implements - * - Solver::solveStagewiseOptim: core method needed by all Reachability - * Analysis-based algorithms - * - Solver::setupSolver, Solver::closeSolver: needed by some Solver - * implementation, such as mosek and qpOASES with warmstart. - * - * Note that some Solver only handle Linear Program while - * some handle both. - * - * Each solver wrapper should provide solver-specific constraint, - * such as ultimate bound the variable u, x. For some solvers such as - * ECOS, this is very important. - * - * */ -class Solver { - public: - /// \brief Create a solver based on the compilation option. - /// At the time of writing, the preference order is - /// - qpOASES - /// - GLPK - /// If none of these is available, this function returns a null pointer. - static SolverPtr createDefault(); - - /// \copydoc Solver::m_deltas - const Vector& deltas () const - { - return m_deltas; - } - - /// \copydoc Solver::m_N - std::size_t nbStages () const - { - return m_N; - } - - /// \copydoc Solver::m_nV - std::size_t nbVars () const - { - return m_nV; - } - - /** Solve a stage-wise quadratic (or linear) optimization problem. - * - * The quadratic optimization problem is described below: - * - * \f{eqnarray} - * \text{min } & 0.5 [u, x, v] H [u, x, v]^\top + [u, x, v] g \\ - * \text{s.t. } & [u, x] \text{ is feasible at stage } i \\ - * & x_{min} \leq x \leq x_{max} \\ - * & x_{next, min} \leq x + 2 \Delta_i u \leq x_{next, max}, - * \f} - * - * where `v` is an auxiliary variable, only exist if there are - * non-canonical constraints. The linear program is the - * quadratic problem without the quadratic term. - * - * \param i The stage index. - * \param H Either a matrix of size (d, d), where d is \ref nbVars, in - * which case a quadratic objective is defined, or a matrix - * of size (0,0), in which case a linear objective is defined. - * \param g Vector of size \ref nbVars. The linear term. - * \param[out] solution in case of success, stores the optimal solution. - * - * \return whether the resolution is successful, in which case \c solution - * contains the optimal solution. - * */ - virtual bool solveStagewiseOptim(std::size_t i, - const Matrix& H, const Vector& g, - const Bound& x, const Bound& xNext, - Vector& solution) = 0; - - /// \brief Initialize the solver - /// \note Child classes should call the parent implementation. - virtual void initialize (const LinearConstraintPtrs& constraints, const GeometricPathPtr& path, - const Vector& times); - - /** \brief Initialize the wrapped solver - */ - virtual void setupSolver () - {} - - /** \brief Free the wrapped solver - */ - virtual void closeSolver () - {} - - virtual ~Solver () {} - - protected: - Solver () {} - - void init (const LinearConstraintPtrs& constraints, const GeometricPathPtr& path, - const Vector& times); - - struct LinearConstraintParams { - int cid; - Vectors a, b, c, g; - Matrices F; - }; - struct BoxConstraintParams { - int cid; - Bounds u, x; - }; - struct ConstraintsParams { - std::vector lin; - std::vector box; - } m_constraintsParams; - - LinearConstraintPtrs m_constraints; - GeometricPathPtr m_path; - Vector m_times; - - private: - /// \brief Number of stages. - /// The number of gridpoints equals N + 1, where N is the number of stages. - std::size_t m_N; - /// Total number of variables, including u, x. - std::size_t m_nV; - /// Time increment between each stage. Size \ref nbStages - Vector m_deltas; - -}; // class Solver - -} // namespace toppra - -#endif diff --git a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/solver/glpk-wrapper.hpp b/dependency/arm/third_party/toppra/v0.6.2/include/toppra/solver/glpk-wrapper.hpp deleted file mode 100644 index d0eefabd..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/solver/glpk-wrapper.hpp +++ /dev/null @@ -1,54 +0,0 @@ -#ifndef TOPPRA_SOLVER_GLPK_WRAPPER_HPP -#define TOPPRA_SOLVER_GLPK_WRAPPER_HPP - -#include -#include - -// Forward declare glpk solver. -struct glp_prob; - -namespace toppra { -namespace solver { - -/** Wrapper around GLPK library. - * - * Internally, the problem is formulated as - * \f{eqnarray} - * min & g^T y \\ - * s.t & z = A y \\ - * & x_{min} <= x <= x_{max} \\ - * & l_1 <= z <= h_1 \\ - * \f} - * where - * \f{eqnarray} - * y =& \begin{pmatrix} u & x \end{pmatrix}^T \\ - * A =& \begin{pmatrix} - * 2\delta & 1 \\ - * F_i a_i & F_i b_i \\ - * \vdots & \vdots \\ - * \end{pmatrix}\\ - * \f} - * - * */ -class GLPKWrapper : public Solver { - public: - GLPKWrapper () = default; - - void initialize (const LinearConstraintPtrs& constraints, const GeometricPathPtr& path, - const Vector& times); - - bool solveStagewiseOptim(std::size_t i, - const Matrix& H, const Vector& g, - const Bound& x, const Bound& xNext, - Vector& solution); - - virtual ~GLPKWrapper(); - - private: - glp_prob* m_lp = NULL; -}; // class GLPKWrapper - -} // namespace solver -} // namespace toppra - -#endif diff --git a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/solver/qpOASES-wrapper.hpp b/dependency/arm/third_party/toppra/v0.6.2/include/toppra/solver/qpOASES-wrapper.hpp deleted file mode 100644 index bd490472..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/solver/qpOASES-wrapper.hpp +++ /dev/null @@ -1,66 +0,0 @@ -#ifndef TOPPRA_SOLVER_QPOASES_WRAPPER_HPP -#define TOPPRA_SOLVER_QPOASES_WRAPPER_HPP - -#include -#include - -namespace toppra { -namespace solver { - -/** Wrapper around qpOASES::SQProblem - * - * Internally, the problem is formulated as - * \f{eqnarray} - * min & 0.5 y^T H y + g^T y \\ - * s.t & lA <= Ay <= hA \\ - * & l <= y <= h \\ - * \f} - * - * \todo Add a solver that inherits from qpOASESWrapper and that uses the warm - * start capabilities of qpOASES - * - * */ -class qpOASESWrapper : public Solver { - public: - qpOASESWrapper (); - - void initialize (const LinearConstraintPtrs& constraints, const GeometricPathPtr& path, - const Vector& times); - - bool solveStagewiseOptim(std::size_t i, - const Matrix& H, const Vector& g, - const Bound& x, const Bound& xNext, - Vector& solution); - - virtual ~qpOASESWrapper(); - - value_type setBoundary () const - { - return m_boundary; - } - - void setBoundary (const value_type& v) - { - m_boundary = v; - } - - static void setDefaultBoundary (const value_type& v); - - private: - /// qpOASES uses row-major storage order. - typedef Eigen::Matrix RMatrix; - RMatrix m_H, m_A; - Vector m_lA, m_hA; - value_type m_boundary; - - static value_type m_defaultBoundary; - - struct Impl; - std::unique_ptr m_impl; -}; // class qpOASESWrapper - -} // namespace solver -} // namespace toppra - -#endif diff --git a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/solver/seidel.hpp b/dependency/arm/third_party/toppra/v0.6.2/include/toppra/solver/seidel.hpp deleted file mode 100644 index c953e0ac..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/solver/seidel.hpp +++ /dev/null @@ -1,43 +0,0 @@ -#ifndef TOPPRA_SOLVER_SEIDEL_HPP -#define TOPPRA_SOLVER_SEIDEL_HPP - -#include -#include -#include - -namespace toppra { -namespace solver { - -/** Implementation of Seidel algorithm. - * - * */ -class Seidel : public Solver { - public: - Seidel () = default; - - void initialize (const LinearConstraintPtrs& constraints, const GeometricPathPtr& path, - const Vector& times); - - bool solveStagewiseOptim(std::size_t i, - const Matrix& H, const Vector& g, - const Bound& x, const Bound& xNext, - Vector& solution); - - private: - typedef Eigen::Matrix MatrixX2; - typedef Eigen::Matrix MatrixX3; - typedef std::vector > MatricesX3; - - MatricesX3 m_A; - MatrixX2 m_low, m_high; - - MatrixX3 m_A_ordered; - MatrixX2 m_A_1d; - std::vector m_index_map; - std::array m_active_c_up, m_active_c_down; -}; // class Seidel - -} // namespace solver -} // namespace toppra - -#endif diff --git a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/toppra.hpp b/dependency/arm/third_party/toppra/v0.6.2/include/toppra/toppra.hpp deleted file mode 100644 index ce9525de..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/include/toppra/toppra.hpp +++ /dev/null @@ -1,86 +0,0 @@ -#ifndef TOPPRA_TOPPRA_HPP -#define TOPPRA_TOPPRA_HPP - -#include -#include -#include -#include - -#include -#include - -#include - - -#ifdef TOPPRA_DEBUG_ON -#define TOPPRA_LOG_DEBUG(X) std::cout << "[DEBUG]: " << X << std::endl -#else -#define TOPPRA_LOG_DEBUG(X) ((void)0) -#endif - -#if defined(TOPPRA_DEBUG_ON) || defined(TOPPRA_WARN_ON) -#define TOPPRA_LOG_WARN(X) std::cout << "[WARN]: " << X << std::endl -#else -#define TOPPRA_LOG_WARN(X) ((void)0) -#endif - -#define TOPPRA_UNUSED(x) (void)(x) - -// Use for checking if a quantity is very close to zero -#define TOPPRA_NEARLY_ZERO 1e-8 -#define TOPPRA_REL_TOL 1e-6 -#define TOPPRA_ABS_TOL 1e-8 - - -/// The TOPP-RA namespace -namespace toppra { - /// The scalar type - typedef double value_type; - - constexpr value_type infty = std::numeric_limits::infinity(); - - /// Column vector type - typedef Eigen::Matrix Vector; - /// Matrix type - typedef Eigen::Matrix Matrix; - - /// Vector of Vector - typedef std::vector > Vectors; - /// Vector of Matrix - typedef std::vector > Matrices; - - // internal data rep for Matrix - typedef std::tuple> MatrixData; - typedef std::vector MatricesData; - - /// 2D vector that stores the upper and lower bound of a variable. - typedef Eigen::Matrix Bound; - /// Vector of Bound - typedef std::vector > Bounds; - - class LinearConstraint; - /// Shared pointer to a LinearConstraint - typedef std::shared_ptr LinearConstraintPtr; - /// Vector of LinearConstraintPtr - typedef std::vector LinearConstraintPtrs; - namespace constraint { - class LinearJointVelocity; - class LinearJointAcceleration; - class JointTorque; - } // namespace constraint - - class Solver; - typedef std::shared_ptr SolverPtr; - namespace solver { - class qpOASESWrapper; - } // namespace solver - - class GeometricPath; - typedef std::shared_ptr GeometricPathPtr; - - class PathParametrizationAlgorithm; - typedef std::shared_ptr PathParametrizationAlgorithmPtr; - -} // namespace toppra - -#endif diff --git a/dependency/arm/third_party/toppra/v0.6.2/lib/cmake/toppra/toppraConfig.cmake b/dependency/arm/third_party/toppra/v0.6.2/lib/cmake/toppra/toppraConfig.cmake deleted file mode 100644 index 85f1a594..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/lib/cmake/toppra/toppraConfig.cmake +++ /dev/null @@ -1,13 +0,0 @@ -set(TOPPRA_WITH_PINOCCHIO OFF) -set(TOPPRA_WITH_qpOASES OFF) -set(TOPPRA_WITH_GLPK OFF) - -find_package(Eigen3 REQUIRED) - -if(TOPPRA_WITH_PINOCCHIO) - find_package(pinocchio REQUIRED) -endif() -# qpOASES and GLPK do not need to be found again, because -# they are not used as targets. - -include("${CMAKE_CURRENT_LIST_DIR}/toppraTargets.cmake") diff --git a/dependency/arm/third_party/toppra/v0.6.2/lib/cmake/toppra/toppraTargets-noconfig.cmake b/dependency/arm/third_party/toppra/v0.6.2/lib/cmake/toppra/toppraTargets-noconfig.cmake deleted file mode 100644 index b559b040..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/lib/cmake/toppra/toppraTargets-noconfig.cmake +++ /dev/null @@ -1,19 +0,0 @@ -#---------------------------------------------------------------- -# Generated CMake target import file. -#---------------------------------------------------------------- - -# Commands may need to know the format version. -set(CMAKE_IMPORT_FILE_VERSION 1) - -# Import target "toppra::toppra" for configuration "" -set_property(TARGET toppra::toppra APPEND PROPERTY IMPORTED_CONFIGURATIONS NOCONFIG) -set_target_properties(toppra::toppra PROPERTIES - IMPORTED_LOCATION_NOCONFIG "${_IMPORT_PREFIX}/lib/libtoppra.so" - IMPORTED_SONAME_NOCONFIG "libtoppra.so" - ) - -list(APPEND _cmake_import_check_targets toppra::toppra ) -list(APPEND _cmake_import_check_files_for_toppra::toppra "${_IMPORT_PREFIX}/lib/libtoppra.so" ) - -# Commands beyond this point should not need to know the version. -set(CMAKE_IMPORT_FILE_VERSION) diff --git a/dependency/arm/third_party/toppra/v0.6.2/lib/cmake/toppra/toppraTargets.cmake b/dependency/arm/third_party/toppra/v0.6.2/lib/cmake/toppra/toppraTargets.cmake deleted file mode 100644 index 2e6e57ae..00000000 --- a/dependency/arm/third_party/toppra/v0.6.2/lib/cmake/toppra/toppraTargets.cmake +++ /dev/null @@ -1,107 +0,0 @@ -# Generated by CMake - -if("${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}" LESS 2.8) - message(FATAL_ERROR "CMake >= 2.8.0 required") -endif() -if(CMAKE_VERSION VERSION_LESS "2.8.12") - message(FATAL_ERROR "CMake >= 2.8.12 required") -endif() -cmake_policy(PUSH) -cmake_policy(VERSION 2.8.12...3.28) -#---------------------------------------------------------------- -# Generated CMake target import file. -#---------------------------------------------------------------- - -# Commands may need to know the format version. -set(CMAKE_IMPORT_FILE_VERSION 1) - -# Protect against multiple inclusion, which would fail when already imported targets are added once more. -set(_cmake_targets_defined "") -set(_cmake_targets_not_defined "") -set(_cmake_expected_targets "") -foreach(_cmake_expected_target IN ITEMS toppra::toppra) - list(APPEND _cmake_expected_targets "${_cmake_expected_target}") - if(TARGET "${_cmake_expected_target}") - list(APPEND _cmake_targets_defined "${_cmake_expected_target}") - else() - list(APPEND _cmake_targets_not_defined "${_cmake_expected_target}") - endif() -endforeach() -unset(_cmake_expected_target) -if(_cmake_targets_defined STREQUAL _cmake_expected_targets) - unset(_cmake_targets_defined) - unset(_cmake_targets_not_defined) - unset(_cmake_expected_targets) - unset(CMAKE_IMPORT_FILE_VERSION) - cmake_policy(POP) - return() -endif() -if(NOT _cmake_targets_defined STREQUAL "") - string(REPLACE ";" ", " _cmake_targets_defined_text "${_cmake_targets_defined}") - string(REPLACE ";" ", " _cmake_targets_not_defined_text "${_cmake_targets_not_defined}") - message(FATAL_ERROR "Some (but not all) targets in this export set were already defined.\nTargets Defined: ${_cmake_targets_defined_text}\nTargets not yet defined: ${_cmake_targets_not_defined_text}\n") -endif() -unset(_cmake_targets_defined) -unset(_cmake_targets_not_defined) -unset(_cmake_expected_targets) - - -# Compute the installation prefix relative to this file. -get_filename_component(_IMPORT_PREFIX "${CMAKE_CURRENT_LIST_FILE}" PATH) -get_filename_component(_IMPORT_PREFIX "${_IMPORT_PREFIX}" PATH) -get_filename_component(_IMPORT_PREFIX "${_IMPORT_PREFIX}" PATH) -get_filename_component(_IMPORT_PREFIX "${_IMPORT_PREFIX}" PATH) -if(_IMPORT_PREFIX STREQUAL "/") - set(_IMPORT_PREFIX "") -endif() - -# Create imported target toppra::toppra -add_library(toppra::toppra SHARED IMPORTED) - -set_target_properties(toppra::toppra PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include" - INTERFACE_LINK_LIBRARIES "Eigen3::Eigen" -) - -# Load information for each installed configuration. -file(GLOB _cmake_config_files "${CMAKE_CURRENT_LIST_DIR}/toppraTargets-*.cmake") -foreach(_cmake_config_file IN LISTS _cmake_config_files) - include("${_cmake_config_file}") -endforeach() -unset(_cmake_config_file) -unset(_cmake_config_files) - -# Cleanup temporary variables. -set(_IMPORT_PREFIX) - -# Loop over all imported files and verify that they actually exist -foreach(_cmake_target IN LISTS _cmake_import_check_targets) - if(CMAKE_VERSION VERSION_LESS "3.28" - OR NOT DEFINED _cmake_import_check_xcframework_for_${_cmake_target} - OR NOT IS_DIRECTORY "${_cmake_import_check_xcframework_for_${_cmake_target}}") - foreach(_cmake_file IN LISTS "_cmake_import_check_files_for_${_cmake_target}") - if(NOT EXISTS "${_cmake_file}") - message(FATAL_ERROR "The imported target \"${_cmake_target}\" references the file - \"${_cmake_file}\" -but this file does not exist. Possible reasons include: -* The file was deleted, renamed, or moved to another location. -* An install or uninstall procedure did not complete successfully. -* The installation package was faulty and contained - \"${CMAKE_CURRENT_LIST_FILE}\" -but not all the files it references. -") - endif() - endforeach() - endif() - unset(_cmake_file) - unset("_cmake_import_check_files_for_${_cmake_target}") -endforeach() -unset(_cmake_target) -unset(_cmake_import_check_targets) - -# This file does not depend on other imported targets which have -# been exported from the same project but in a separate export set. - -# Commands beyond this point should not need to know the version. -set(CMAKE_IMPORT_FILE_VERSION) -cmake_policy(POP) diff --git a/dependency/arm/third_party/toppra/v0.6.2/lib/libtoppra.so b/dependency/arm/third_party/toppra/v0.6.2/lib/libtoppra.so deleted file mode 100644 index 374a1911ea9750e426fdca5b12c1ab82e1b62a40..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6628800 zcma(430Rb6AOC-!*USLdu;?%>0xk`UIN;Ktrf6Ch1L}xqh^T00qoS#4scD&64TuPc z2DqV_0`6voOQv>b18%rfXliCwT2{7dmS*eye_wg>`|-b@=Q)n&bKEaJ-|smW*sUYW zu=rxXjQ$2iF$x)@cuOcv3$4l7({AGbIn_k6@Z*-YqRqe8`uv|;{y&G)FF)|_VN(nF z()C}%7Z*0(z5T+*2migUsV7I@{jc!0Z~Cvf+Xnf3_8oVh&%WdC^EI_azkoEgdUq8j zTGt?7-2Zl*ysoMBYxQJ)H9J?Iv(;Yz?*H5KBk#Vzrfzz^p*)}d|L_0bSmcFS^4I(S z_4{HExO-t!H~sGDziue>Kga2jhVK!O$ z0}L|N2iIm5Op04PT6l%aXtAsP>$aNyvvJwtPA?6$ofe96=fMWs+8Fby4(dLy&7ycr zC;g4)F>!H8@g@yhTJ?TgDEHYcN!~O;Me#4qNe;Rcd7N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