Files
recovery_core/test/evade_recovery_test.cpp
duongtd 001489c8a6 feat: EvadeRecovery plugin (back up or turn to the free side)
- plugins/evade_core.h: pure geometry (polygon footprint, reverse sweep,
  rotation-arc sweep, free-side choice), tested with point lists
- plugins/evade_recovery.cpp: reads raw scans through
  RecoveryContext::sensors; holds on a short view loss, never drives on
  stale data
- RecoveryContext / behavior ABI additions for the sensor reader
2026-11-27 22:06:59 +07:00

445 lines
16 KiB
C++

/*********************************************************************
*
* Kiểm EvadeRecovery: lõi hình học (chọn lùi / xoay / không làm gì), Executor (lệnh vận tốc, ramp,
* dừng khi bị chắn giữa chừng, pose NaN), và đường nạp plugin qua library_path + ABI.
*
* Phần adapter đọc scan/TF/ô LETHAL cần `Costmap2DROBOT` thật nên không test ở đây (chưa test nào
* trong workspace dựng được nó); phần đó kiểm bằng sim.
*
* Footprint mặc định = robot KIT 1.022 x 0.392 m, base ở tâm: r_max = 0.547 m.
*
* Author: DuongTD
*********************************************************************/
#include <gtest/gtest.h>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <vector>
#include <robot/node_handle.h>
#include <recovery_core/recovery_registry.h>
#include "../plugins/evade_core.h"
#include "recovery_test_utils.h"
namespace
{
namespace evade = recovery_plugins::evade;
constexpr double kDeg = evade::kPi / 180.0;
evade::Polygon rectangle(double x_min, double x_max, double half_width)
{
return {{x_max, half_width}, {x_min, half_width}, {x_min, -half_width}, {x_max, -half_width}};
}
evade::Polygon kitFootprint()
{
return rectangle(-0.511, 0.511, 0.196);
}
/// Điểm dày đặc (bước 0.02 m) trên đoạn a-b, như một bức tường quét bằng lidar.
void addWall(std::vector<evade::Point2>& out, evade::Point2 a, evade::Point2 b)
{
const double length = std::hypot(b.x - a.x, b.y - a.y);
const int n = std::max(1, static_cast<int>(std::ceil(length / 0.02)));
for (int i = 0; i <= n; ++i)
{
const double t = static_cast<double>(i) / n;
out.push_back({a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t});
}
}
evade::Params defaultParams()
{
return evade::Params(); // 0.20 m, margin 0.05 m, min_free 0.30 m, probe 1.0 m, step 10 deg
}
// ---------------------------------------------------------------------------------------------
// Lùi
// ---------------------------------------------------------------------------------------------
TEST(EvadeDecide, BacksUpWhenTheRearIsClear)
{
std::vector<evade::Point2> obstacles;
addWall(obstacles, {0.55, -1.0}, {0.55, 1.0}); // vật sát mũi, phía sau trống
const evade::Decision d = evade::decide(kitFootprint(), {0.0, 0.0, 0.0}, defaultParams(), obstacles);
EXPECT_EQ(d.motion, evade::Motion::kBackUp);
EXPECT_LT(d.backup_blocked_at, 0.0);
}
TEST(EvadeDecide, ObstacleWithinBackUpReachSwitchesToRotation)
{
// Đuôi ở x = -0.511; tường ở -0.60 nằm trong 0.20 + 0.05 m phía sau nhưng ngoài r_max (0.547 m)
// nên không chắn cung xoay. Mũi cũng bị chắn để hướng hiện tại không thắng.
std::vector<evade::Point2> obstacles;
addWall(obstacles, {-0.60, -2.0}, {-0.60, 2.0});
addWall(obstacles, {0.60, -2.0}, {0.60, 2.0});
const evade::Decision d = evade::decide(kitFootprint(), {0.0, 0.0, 0.0}, defaultParams(), obstacles);
EXPECT_GE(d.backup_blocked_at, 0.0);
EXPECT_LE(d.backup_blocked_at, 0.25);
EXPECT_EQ(d.motion, evade::Motion::kRotate);
}
TEST(EvadeDecide, ThreeCentimetreSideGapStillBacksUp)
{
// Hai tường song song cách hông 0.03 m: CostmapCollisionChecker (253 = chắn) sẽ từ chối ngay tại
// chỗ. Ở đây footprint thật, không nở ngang, nên vẫn lùi được.
std::vector<evade::Point2> obstacles;
addWall(obstacles, {-2.0, 0.226}, {2.0, 0.226});
addWall(obstacles, {-2.0, -0.226}, {2.0, -0.226});
addWall(obstacles, {0.55, -0.226}, {0.55, 0.226});
const evade::Decision d = evade::decide(kitFootprint(), {0.0, 0.0, 0.0}, defaultParams(), obstacles);
EXPECT_EQ(d.motion, evade::Motion::kBackUp);
}
TEST(EvadeDecide, PointsInsideTheStartFootprintAreIgnored)
{
const evade::Polygon footprint = kitFootprint();
const evade::Pose2 start{0.0, 0.0, 0.0};
const std::vector<evade::Point2> raw{{0.0, 0.0}, {0.4, 0.1}, {-0.5, -0.15}, {0.6, 0.0}};
// Không lọc thì điểm phản xạ từ chính thân robot chắn ngay mẫu s = 0.
EXPECT_DOUBLE_EQ(evade::backupBlockedAt(footprint, evade::circumradius(footprint), start, 0.25, raw),
0.0);
const std::vector<evade::Point2> kept = evade::keepOutsideFootprint(footprint, start, 5.0, raw);
ASSERT_EQ(kept.size(), 1u);
EXPECT_DOUBLE_EQ(kept[0].x, 0.6);
EXPECT_EQ(evade::decide(footprint, start, defaultParams(), kept).motion, evade::Motion::kBackUp);
}
// ---------------------------------------------------------------------------------------------
// Xoay
// ---------------------------------------------------------------------------------------------
TEST(EvadeDecide, RotatesTowardTheWiderSide)
{
// Trước/sau chắn sát. Bên trái (+y) tường cách mũi ~0.4 m, bên phải (-y) trống > 1 m. Phía rộng
// cố ý đặt bên -y: khi hoà, thứ tự quét đi +y trước, nên đáp án âm chứng tỏ d thật sự được so.
std::vector<evade::Point2> obstacles;
addWall(obstacles, {-0.60, -2.0}, {-0.60, 2.0});
addWall(obstacles, {0.60, -2.0}, {0.60, 2.0});
addWall(obstacles, {-2.0, 0.911}, {2.0, 0.911});
const evade::Decision d = evade::decide(kitFootprint(), {0.0, 0.0, 0.0}, defaultParams(), obstacles);
ASSERT_EQ(d.motion, evade::Motion::kRotate);
EXPECT_LT(d.rotation, -60.0 * kDeg) << "must turn toward -y (the 1 m side)";
EXPECT_GT(d.rotation, -100.0 * kDeg);
EXPECT_GE(d.free_distance, 0.95);
}
TEST(EvadeDecide, TiedHeadingsPickTheSmallestRotation)
{
// Đối xứng: 80, 90, 100 deg (và đối xứng âm) đều có d = 1.0 m (trần). 70 deg chỉ ~0.7 m.
std::vector<evade::Point2> obstacles;
addWall(obstacles, {-0.60, -2.0}, {-0.60, 2.0});
addWall(obstacles, {0.60, -2.0}, {0.60, 2.0});
const evade::Decision d = evade::decide(kitFootprint(), {0.0, 0.0, 0.0}, defaultParams(), obstacles);
ASSERT_EQ(d.motion, evade::Motion::kRotate);
EXPECT_NEAR(std::abs(d.rotation), 80.0 * kDeg, 1e-6);
EXPECT_DOUBLE_EQ(d.free_distance, 1.0);
}
TEST(EvadeDecide, BlockedShortArcFallsBackToTheLongWay)
{
// Footprint lệch tâm (base ở mũi, đuôi dài 0.8 m) — với thân đối xứng, cung dài (>= pi) luôn phủ
// cung ngắn nên ca này không tồn tại. Vật B ở hướng 225 deg, r = 0.7 m: đuôi quét qua nó khi xoay
// CCW 0 -> 90 deg, nhưng không khi xoay CW 0 -> -270 deg.
const evade::Polygon footprint = rectangle(-0.8, 0.2, 0.2);
evade::Params params = defaultParams();
params.heading_step = 90.0 * kDeg;
params.min_free_distance = 0.8;
const std::vector<evade::Point2> obstacles{
{0.91, 0.0}, // mũi: d(0) = 0.70 < 0.8, ngoài r_max (0.825)
{-0.90, 0.0}, // sau đuôi: chắn lùi, ngoài r_max; d(180) = 0.70
{0.0, -0.92}, // phía -y: d(-90) = 0.70, ngoài r_max
{-0.495, -0.495}, // B
};
const evade::Decision d = evade::decide(footprint, {0.0, 0.0, 0.0}, params, obstacles);
ASSERT_EQ(d.motion, evade::Motion::kRotate);
EXPECT_NEAR(d.rotation, -270.0 * kDeg, 1e-6);
EXPECT_NEAR(d.heading, 90.0 * kDeg, 1e-6);
}
TEST(EvadeDecide, AlreadyFacingTheFreeSideNeedsNoMotion)
{
std::vector<evade::Point2> obstacles;
addWall(obstacles, {-0.60, -2.0}, {-0.60, 2.0}); // chỉ phía sau bị chắn
const evade::Decision d = evade::decide(kitFootprint(), {0.0, 0.0, 0.0}, defaultParams(), obstacles);
ASSERT_EQ(d.motion, evade::Motion::kAlreadyFacing);
evade::Executor executor;
executor.start(kitFootprint(), {0.0, 0.0, 0.0}, d, defaultParams(), evade::MotionLimits());
const evade::Tick tick = executor.tick({0.0, 0.0, 0.0}, obstacles, 0.05);
EXPECT_EQ(tick.status, evade::TickStatus::kSucceeded);
EXPECT_DOUBLE_EQ(tick.vx, 0.0);
EXPECT_DOUBLE_EQ(tick.wz, 0.0);
}
// ---------------------------------------------------------------------------------------------
// Thất bại
// ---------------------------------------------------------------------------------------------
TEST(EvadeDecide, NothingFeasibleIsReported)
{
// Hộp kín, mọi tường cách tâm 0.60 m: xoay được (r_max 0.547) nhưng không hướng nào đạt 0.30 m.
std::vector<evade::Point2> obstacles;
addWall(obstacles, {-0.60, -0.60}, {-0.60, 0.60});
addWall(obstacles, {0.60, -0.60}, {0.60, 0.60});
addWall(obstacles, {-0.60, 0.60}, {0.60, 0.60});
addWall(obstacles, {-0.60, -0.60}, {0.60, -0.60});
const evade::Decision d = evade::decide(kitFootprint(), {0.0, 0.0, 0.0}, defaultParams(), obstacles);
EXPECT_EQ(d.motion, evade::Motion::kNone);
EXPECT_EQ(d.feasible_headings, 0);
EXPECT_GE(d.backup_blocked_at, 0.0);
}
// ---------------------------------------------------------------------------------------------
// Executor: lệnh vận tốc
// ---------------------------------------------------------------------------------------------
struct Sim
{
evade::Pose2 pose{1.0, 2.0, 0.3}; // không ở gốc, có yaw: bắt lỗi quên đổi frame
void apply(const evade::Tick& tick, double dt)
{
pose.x += tick.vx * std::cos(pose.yaw) * dt;
pose.y += tick.vx * std::sin(pose.yaw) * dt;
pose.yaw += tick.wz * dt;
}
};
TEST(EvadeExecutor, BackUpCommandsStayWithinLimitsAndStopAtTheDistance)
{
Sim sim;
const evade::Pose2 start = sim.pose;
evade::Decision decision;
decision.motion = evade::Motion::kBackUp;
const evade::MotionLimits limits; // 0.15 m/s, 0.3 m/s^2
evade::Executor executor;
executor.start(kitFootprint(), start, decision, defaultParams(), limits);
const double dt = 0.05;
double previous_vx = 0.0;
evade::Tick tick;
int ticks = 0;
for (; ticks < 200; ++ticks)
{
tick = executor.tick(sim.pose, {}, dt);
if (tick.status != evade::TickStatus::kRunning)
{
break;
}
EXPECT_LE(tick.vx, 0.0);
EXPECT_DOUBLE_EQ(tick.wz, 0.0);
EXPECT_LE(std::abs(tick.vx), limits.backup_speed + 1e-9);
EXPECT_LE(std::abs(tick.vx - previous_vx), limits.acc_lim_x * dt + 1e-9);
previous_vx = tick.vx;
sim.apply(tick, dt);
}
ASSERT_EQ(tick.status, evade::TickStatus::kSucceeded);
const double traveled = -((sim.pose.x - start.x) * std::cos(start.yaw) +
(sim.pose.y - start.y) * std::sin(start.yaw));
EXPECT_NEAR(traveled, 0.20, evade::kBackupTolerance + 1e-6);
EXPECT_DOUBLE_EQ(tick.vx, 0.0);
}
TEST(EvadeExecutor, RotationCommandsHaveNoLinearPartAndStopAtTheAngle)
{
Sim sim;
evade::Decision decision;
decision.motion = evade::Motion::kRotate;
decision.rotation = -100.0 * kDeg; // CW: dấu lệnh phải âm
const evade::MotionLimits limits; // 0.5 rad/s, 0.8 rad/s^2
evade::Executor executor;
executor.start(kitFootprint(), sim.pose, decision, defaultParams(), limits);
const double start_yaw = sim.pose.yaw;
const double dt = 0.05;
double previous_wz = 0.0;
evade::Tick tick;
for (int i = 0; i < 400; ++i)
{
tick = executor.tick(sim.pose, {}, dt);
if (tick.status != evade::TickStatus::kRunning)
{
break;
}
EXPECT_DOUBLE_EQ(tick.vx, 0.0);
EXPECT_LE(tick.wz, 0.0);
EXPECT_LE(std::abs(tick.wz), limits.rotate_speed + 1e-9);
EXPECT_LE(std::abs(tick.wz - previous_wz), limits.acc_lim_theta * dt + 1e-9);
previous_wz = tick.wz;
sim.apply(tick, dt);
}
ASSERT_EQ(tick.status, evade::TickStatus::kSucceeded);
EXPECT_NEAR(sim.pose.yaw - start_yaw, -100.0 * kDeg, evade::kRotateTolerance + 1e-6);
}
TEST(EvadeExecutor, FirstTickAtTheStartStampDoesNotJumpToFullSpeed)
{
evade::Decision decision;
decision.motion = evade::Motion::kBackUp;
evade::Executor executor;
executor.start(kitFootprint(), {0.0, 0.0, 0.0}, decision, defaultParams(), evade::MotionLimits());
const evade::Tick tick = executor.tick({0.0, 0.0, 0.0}, {}, 0.0);
EXPECT_EQ(tick.status, evade::TickStatus::kRunning);
EXPECT_DOUBLE_EQ(tick.vx, 0.0);
}
TEST(EvadeExecutor, HoldRestartsTheRampFromZero)
{
// Sim 27/11: the plugin publishes 0 while the view is lost; resuming must ramp again, not jump to the old speed.
Sim sim;
sim.pose = {0.0, 0.0, 0.0};
evade::Decision decision;
decision.motion = evade::Motion::kBackUp;
const evade::MotionLimits limits;
evade::Executor executor;
executor.start(kitFootprint(), sim.pose, decision, defaultParams(), limits);
for (int i = 0; i < 10; ++i)
{
const evade::Tick tick = executor.tick(sim.pose, {}, 0.05);
ASSERT_EQ(tick.status, evade::TickStatus::kRunning);
sim.apply(tick, 0.05);
}
executor.hold();
const evade::Tick resumed = executor.tick(sim.pose, {}, 0.05);
EXPECT_EQ(resumed.status, evade::TickStatus::kRunning);
EXPECT_LE(std::abs(resumed.vx), limits.acc_lim_x * 0.05 + 1e-9);
}
TEST(EvadeViewGuard, HoldsUntilTheTimeoutThenExpires)
{
evade::ViewGuard guard;
EXPECT_EQ(guard.update(true, 10.0, 1.0), evade::ViewGuard::State::kSeeing);
EXPECT_EQ(guard.update(false, 10.1, 1.0), evade::ViewGuard::State::kHolding);
EXPECT_EQ(guard.update(false, 10.9, 1.0), evade::ViewGuard::State::kHolding);
EXPECT_EQ(guard.update(true, 11.0, 1.0), evade::ViewGuard::State::kSeeing) << "a fresh view ends the loss";
EXPECT_EQ(guard.update(false, 11.5, 1.0), evade::ViewGuard::State::kHolding) << "a new loss starts a new clock";
EXPECT_EQ(guard.update(false, 12.5, 1.0), evade::ViewGuard::State::kExpired);
}
TEST(EvadeViewGuard, ZeroTimeoutFailsOnTheFirstLoss)
{
evade::ViewGuard guard;
EXPECT_EQ(guard.update(false, 10.0, 0.0), evade::ViewGuard::State::kExpired);
}
TEST(EvadeExecutor, ObstacleAppearingMidRunStopsWithZeroCommand)
{
Sim sim;
sim.pose = {0.0, 0.0, 0.0};
evade::Decision decision;
decision.motion = evade::Motion::kBackUp;
evade::Executor executor;
executor.start(kitFootprint(), sim.pose, decision, defaultParams(), evade::MotionLimits());
for (int i = 0; i < 5; ++i)
{
const evade::Tick tick = executor.tick(sim.pose, {}, 0.05);
ASSERT_EQ(tick.status, evade::TickStatus::kRunning);
sim.apply(tick, 0.05);
}
// Có người bước vào ngay sau đuôi (trong phần lùi còn lại).
std::vector<evade::Point2> obstacles;
addWall(obstacles, {sim.pose.x - 0.60, -0.3}, {sim.pose.x - 0.60, 0.3});
const evade::Tick blocked = executor.tick(sim.pose, obstacles, 0.05);
EXPECT_EQ(blocked.status, evade::TickStatus::kFailed);
EXPECT_DOUBLE_EQ(blocked.vx, 0.0);
EXPECT_DOUBLE_EQ(blocked.wz, 0.0);
}
TEST(EvadeExecutor, NanPoseStopsWithZeroCommand)
{
evade::Decision decision;
decision.motion = evade::Motion::kRotate;
decision.rotation = 90.0 * kDeg;
evade::Executor executor;
executor.start(kitFootprint(), {0.0, 0.0, 0.0}, decision, defaultParams(), evade::MotionLimits());
const evade::Tick tick = executor.tick({0.0, std::nan(""), 0.0}, {}, 0.05);
EXPECT_EQ(tick.status, evade::TickStatus::kFailed);
EXPECT_DOUBLE_EQ(tick.vx, 0.0);
EXPECT_DOUBLE_EQ(tick.wz, 0.0);
}
// ---------------------------------------------------------------------------------------------
// Plugin qua registry (library_path + ABI)
// ---------------------------------------------------------------------------------------------
TEST(EvadePlugin, LoadsThroughLibraryPathWithTheCurrentAbi)
{
recovery_test::VelocityRig rig;
robot::NodeHandle nh;
recovery_core::RecoveryRegistry registry;
EXPECT_TRUE(registry.loadFromConfig(nh, "recovery_evade", rig.ctx));
EXPECT_NE(recovery_test::findBehavior(registry, "evade"), nullptr);
}
TEST(EvadePlugin, RefusesToStartWithoutCostmapSensorsOrTf)
{
recovery_test::VelocityRig rig; // có pose + collision, KHÔNG có local_costmap/sensors/tf
rig.pose.setPose(0.0, 0.0, 0.0);
robot::NodeHandle nh;
recovery_core::RecoveryRegistry registry;
ASSERT_TRUE(registry.loadFromConfig(nh, "recovery_evade", rig.ctx));
recovery_core::RecoveryBehavior* evade_behavior = recovery_test::findBehavior(registry, "evade");
ASSERT_NE(evade_behavior, nullptr);
EXPECT_FALSE(evade_behavior->start(recovery_core::RecoveryGoal(), robot::Time(1000.0)));
const auto result = evade_behavior->update(robot::Time(1000.1));
EXPECT_EQ(result.status, recovery_core::RecoveryStatus::kFailed);
ASSERT_NE(result.velocity(), nullptr);
EXPECT_DOUBLE_EQ(result.velocity()->linear.x, 0.0);
EXPECT_DOUBLE_EQ(result.velocity()->angular.z, 0.0);
}
TEST(EvadePlugin, RejectsInvalidParameters)
{
recovery_test::VelocityRig rig;
robot::NodeHandle nh;
recovery_core::RecoveryRegistry registry;
EXPECT_FALSE(registry.loadFromConfig(nh, "recovery_evade_bad", rig.ctx));
EXPECT_EQ(recovery_test::findBehavior(registry, "evade"), nullptr);
}
} // namespace
int main(int argc, char** argv)
{
#ifdef RECOVERY_CORE_TEST_CONFIG_DIR
setenv("PNKX_NAV_CORE_CONFIG_DIR", RECOVERY_CORE_TEST_CONFIG_DIR, 0);
#endif
#ifdef RECOVERY_CORE_TEST_LIBRARY_DIR
setenv("PNKX_NAV_CORE_LIBRARY_PATH", RECOVERY_CORE_TEST_LIBRARY_DIR, 0);
#endif
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}