Files
recovery_core/plugins/evade_core.h
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

565 lines
19 KiB
C++

/*********************************************************************
*
* Software License Agreement (BSD License)
*
* recovery_core — hình học thuần của EvadeRecovery: footprint đa giác, quét lùi, quét cung xoay,
* chọn hướng trống. Không phụ thuộc costmap, TF hay sensor store, nên test thẳng bằng danh sách
* điểm (test/evade_recovery_test.cpp).
*
* Author: DuongTD
*********************************************************************/
#ifndef RECOVERY_CORE_PLUGINS_EVADE_CORE_H_
#define RECOVERY_CORE_PLUGINS_EVADE_CORE_H_
#include <algorithm>
#include <cmath>
#include <cstddef>
#include <vector>
namespace recovery_plugins
{
namespace evade
{
constexpr double kPi = 3.14159265358979323846;
/// [m] bước lấy mẫu dọc quãng lùi (mục 6.2 bước 5 của plan).
constexpr double kLinearSampleStep = 0.02;
/// [m] bước đẩy footprint tới trước khi đo quãng trống d(ψ).
constexpr double kProbeStep = 0.05;
/// [m] cung tối đa mà góc thân xa nhất đi được giữa hai mẫu góc khi quét xoay.
constexpr double kArcSampleAtCorner = 0.02;
/// [m] hai hướng có d chênh nhau không quá mức này thì coi là hoà, chọn hướng xoay ít hơn.
constexpr double kTieDistance = 0.05;
/// [rad] hướng thắng lệch hướng đang quay mặt ít hơn mức này thì coi là đã quay ra phía trống (4a).
constexpr double kFacingTolerance = 10.0 * kPi / 180.0;
struct Point2
{
double x = 0.0; ///< [m]
double y = 0.0; ///< [m]
};
struct Pose2
{
double x = 0.0; ///< [m]
double y = 0.0; ///< [m]
double yaw = 0.0; ///< [rad]
};
/// Footprint trong frame thân robot (base), không padding. Thứ tự đỉnh tuỳ ý (CW hay CCW đều được).
using Polygon = std::vector<Point2>;
/// Tham số quyết định, đã validate ở onConfigure().
struct Params
{
double backup_distance = 0.20; ///< [m] quãng lùi
double motion_margin = 0.05; ///< [m] biên chỉ cộng theo chiều chuyển động
double min_free_distance = 0.30; ///< [m] d(ψ) tối thiểu để một hướng được coi là trống
double max_probe_distance = 1.0; ///< [m] trần khi đo d(ψ)
double heading_step = 10.0 * kPi / 180.0; ///< [rad] bước lấy mẫu hướng ứng viên
};
enum class Motion
{
kNone, ///< Không động tác nào khả thi.
kBackUp, ///< Lùi thẳng backup_distance.
kRotate, ///< Xoay tại chỗ một góc có dấu.
kAlreadyFacing ///< Hướng thắng chính là hướng đang quay mặt: không cần chuyển động (4a).
};
struct Decision
{
Motion motion = Motion::kNone;
double rotation = 0.0; ///< [rad] có dấu, + = ngược chiều kim đồng hồ. Chỉ cho kRotate.
double heading = 0.0; ///< [rad] hướng thắng ψ trong frame của pose
double free_distance = 0.0; ///< [m] d(ψ) của hướng thắng
double backup_blocked_at = -1.0; ///< [m] s đầu tiên bị chắn khi lùi; < 0 = lùi trống
int feasible_headings = 0; ///< số hướng khả thi (cung trống và d >= min_free_distance)
};
inline double normalizeAngle(double angle)
{
return std::atan2(std::sin(angle), std::cos(angle));
}
/// Ray casting chẵn-lẻ. Điểm đúng trên cạnh rơi vào bên nào cũng được: motion_margin phủ phần đó.
inline bool insidePolygon(const Polygon& polygon, double x, double y)
{
if (polygon.size() < 3)
{
return false;
}
bool inside = false;
for (std::size_t i = 0, j = polygon.size() - 1; i < polygon.size(); j = i++)
{
const Point2& a = polygon[i];
const Point2& b = polygon[j];
if ((a.y > y) != (b.y > y) && x < (b.x - a.x) * (y - a.y) / (b.y - a.y) + a.x)
{
inside = !inside;
}
}
return inside;
}
/// [m] khoảng cách từ tâm thân tới đỉnh xa nhất (bán kính đường tròn ngoại tiếp quanh base).
inline double circumradius(const Polygon& polygon)
{
double r2 = 0.0;
for (const Point2& p : polygon)
{
r2 = std::max(r2, p.x * p.x + p.y * p.y);
}
return std::sqrt(r2);
}
/// @return true nếu có điểm nào của @p obstacles (cùng frame với @p pose) nằm trong footprint đặt tại @p pose.
inline bool footprintHits(const Polygon& footprint, double r_max, const Pose2& pose,
const std::vector<Point2>& obstacles)
{
const double c = std::cos(pose.yaw);
const double s = std::sin(pose.yaw);
const double r2 = r_max * r_max;
for (const Point2& p : obstacles)
{
const double dx = p.x - pose.x;
const double dy = p.y - pose.y;
if (dx * dx + dy * dy > r2)
{
continue; // ngoài đường tròn ngoại tiếp thì không thể nằm trong đa giác
}
if (insidePolygon(footprint, c * dx + s * dy, -s * dx + c * dy))
{
return true;
}
}
return false;
}
/**
* @brief Giữ các điểm cách tâm @p pose không quá @p radius và nằm NGOÀI footprint tại @p pose.
*
* Điểm trong footprint tại pose hiện tại là nhiễu hoặc phản xạ từ chính thân robot: robot đang đứng
* đó nên không thể có vật thật ở đó. Giữ chúng lại thì mọi động tác đều bị coi là chắn ngay mẫu đầu.
*/
inline std::vector<Point2> keepOutsideFootprint(const Polygon& footprint, const Pose2& pose,
double radius, const std::vector<Point2>& points)
{
std::vector<Point2> kept;
kept.reserve(points.size());
const double c = std::cos(pose.yaw);
const double s = std::sin(pose.yaw);
const double r2 = radius * radius;
for (const Point2& p : points)
{
const double dx = p.x - pose.x;
const double dy = p.y - pose.y;
if (dx * dx + dy * dy > r2)
{
continue;
}
if (!insidePolygon(footprint, c * dx + s * dy, -s * dx + c * dy))
{
kept.push_back(p);
}
}
return kept;
}
/**
* @brief Quét lùi thẳng (ngược hướng @p from.yaw) quãng @p distance, bước <= kLinearSampleStep.
* @return s [m] của mẫu đầu tiên bị chắn, hoặc -1 nếu cả quãng trống.
*/
inline double backupBlockedAt(const Polygon& footprint, double r_max, const Pose2& from,
double distance, const std::vector<Point2>& obstacles)
{
const int samples = std::max(1, static_cast<int>(std::ceil(distance / kLinearSampleStep)));
const double c = std::cos(from.yaw);
const double s = std::sin(from.yaw);
for (int i = 0; i <= samples; ++i)
{
const double travel = distance * static_cast<double>(i) / samples;
const Pose2 pose{from.x - c * travel, from.y - s * travel, from.yaw};
if (footprintHits(footprint, r_max, pose, obstacles))
{
return travel;
}
}
return -1.0;
}
/**
* @brief Quét cung xoay tại chỗ từ @p from theo góc có dấu @p angle, cộng thêm @p overshoot [rad].
* @return true nếu footprint ở mọi mẫu góc đều không chứa vật cản.
*/
inline bool arcClear(const Polygon& footprint, double r_max, const Pose2& from, double angle,
double overshoot, const std::vector<Point2>& obstacles)
{
const double sweep = std::abs(angle) + overshoot;
const double direction = angle >= 0.0 ? 1.0 : -1.0;
const double step = kArcSampleAtCorner / std::max(r_max, 1e-3);
const int samples = std::max(1, static_cast<int>(std::ceil(sweep / step)));
for (int i = 0; i <= samples; ++i)
{
const Pose2 pose{from.x, from.y, from.yaw + direction * sweep * static_cast<double>(i) / samples};
if (footprintHits(footprint, r_max, pose, obstacles))
{
return false;
}
}
return true;
}
/**
* @brief Quãng trống d(ψ): đẩy footprint thẳng tới trước theo @p heading từng bước kProbeStep.
* @return [m] quãng xa nhất còn trống, tối đa @p max_probe.
*/
inline double freeDistance(const Polygon& footprint, double r_max, const Pose2& from,
double heading, double max_probe, const std::vector<Point2>& obstacles)
{
const int steps = static_cast<int>(std::floor(max_probe / kProbeStep + 1e-9));
const double c = std::cos(heading);
const double s = std::sin(heading);
for (int i = 1; i <= steps; ++i)
{
const double travel = kProbeStep * i;
const Pose2 pose{from.x + c * travel, from.y + s * travel, heading};
if (footprintHits(footprint, r_max, pose, obstacles))
{
return kProbeStep * (i - 1);
}
}
return max_probe;
}
/**
* @brief Chọn động tác né từ pose @p start, với tập vật cản @p obstacles đã bỏ điểm trong footprint.
*
* Bước 1: lùi thẳng nếu cả quãng `backup_distance + motion_margin` trống. Bước 2: xét các hướng
* ψ_k = yaw + k·heading_step; hướng khả thi khi cung xoay tới đó (thử chiều ngắn trước, chiều dài
* sau, vượt đích motion_margin / r_max) trống và d(ψ) >= min_free_distance. Thắng = d lớn nhất; các
* hướng có d trong kTieDistance của d lớn nhất thì chọn hướng xoay ít nhất.
*/
inline Decision decide(const Polygon& footprint, const Pose2& start, const Params& params,
const std::vector<Point2>& obstacles)
{
Decision decision;
const double r_max = circumradius(footprint);
decision.backup_blocked_at = backupBlockedAt(footprint, r_max, start,
params.backup_distance + params.motion_margin,
obstacles);
if (decision.backup_blocked_at < 0.0)
{
decision.motion = Motion::kBackUp;
decision.heading = start.yaw;
return decision;
}
const double overshoot = params.motion_margin / std::max(r_max, 1e-3);
const int count = std::max(1, static_cast<int>(std::floor(2.0 * kPi / params.heading_step + 1e-9)));
struct Candidate
{
double rotation;
double heading;
double free_distance;
};
std::vector<Candidate> feasible;
feasible.reserve(static_cast<std::size_t>(count));
for (int k = 0; k < count; ++k)
{
const double short_turn = normalizeAngle(k * params.heading_step);
const double heading = start.yaw + short_turn;
const double d = freeDistance(footprint, r_max, start, heading, params.max_probe_distance,
obstacles);
if (d < params.min_free_distance)
{
continue;
}
double rotation = 0.0;
bool reachable = (k == 0); // hướng hiện tại: không xoay, không cần cung
if (!reachable)
{
if (arcClear(footprint, r_max, start, short_turn, overshoot, obstacles))
{
rotation = short_turn;
reachable = true;
}
else
{
const double long_turn = short_turn - std::copysign(2.0 * kPi, short_turn);
if (arcClear(footprint, r_max, start, long_turn, overshoot, obstacles))
{
rotation = long_turn;
reachable = true;
}
}
}
if (reachable)
{
feasible.push_back({rotation, heading, d});
}
}
decision.feasible_headings = static_cast<int>(feasible.size());
if (feasible.empty())
{
return decision;
}
double best_distance = 0.0;
for (const Candidate& c : feasible)
{
best_distance = std::max(best_distance, c.free_distance);
}
const Candidate* winner = nullptr;
for (const Candidate& c : feasible)
{
if (c.free_distance + kTieDistance + 1e-9 < best_distance)
{
continue;
}
if (winner == nullptr || std::abs(c.rotation) < std::abs(winner->rotation))
{
winner = &c;
}
}
decision.rotation = winner->rotation;
decision.heading = normalizeAngle(winner->heading);
decision.free_distance = winner->free_distance;
decision.motion = std::abs(winner->rotation) < kFacingTolerance ? Motion::kAlreadyFacing
: Motion::kRotate;
return decision;
}
/// Giới hạn chuyển động của một lượt né (độ lớn, đã validate > 0).
struct MotionLimits
{
double backup_speed = 0.15; ///< [m/s]
double rotate_speed = 0.5; ///< [rad/s]
double acc_lim_x = 0.3; ///< [m/s^2]
double acc_lim_theta = 0.8; ///< [rad/s^2]
};
/// [m] dung sai đích khi lùi.
constexpr double kBackupTolerance = 0.01;
/// [rad] dung sai đích khi xoay.
constexpr double kRotateTolerance = 0.035;
enum class TickStatus
{
kRunning,
kSucceeded,
kFailed ///< phải phát lệnh 0: pose hỏng hoặc phần chuyển động còn lại bị chắn
};
struct Tick
{
TickStatus status = TickStatus::kFailed;
double vx = 0.0; ///< [m/s] âm = lùi
double wz = 0.0; ///< [rad/s] + = ngược chiều kim đồng hồ
double progress = 0.0; ///< [0, 1]
double remaining = 0.0; ///< [m] hoặc [rad]
const char* message = "";
};
/**
* @class Executor
* @brief Chạy động tác đã chọn, mỗi tick: đo tiến độ bằng pose thật, kiểm lại phần CÒN LẠI với tập
* vật cản mới nhất, rồi sinh lệnh có ramp. Thuần, không I/O.
*
* Lùi: quãng đo dọc trục thân lúc bắt đầu; lệnh chỉ có vx < 0. Xoay: góc cộng dồn có dấu theo chiều
* xoay (unwrap); lệnh chỉ có wz. Vận tốc không vượt độ lớn cấu hình, không tăng quá acc_lim·dt mỗi
* tick, và không vượt phần còn lại / dt (giảm tốc khi gần đích, như BackUpRecovery/RotateRecovery).
*/
class Executor
{
public:
void start(const Polygon& footprint, const Pose2& start, const Decision& decision,
const Params& params, const MotionLimits& limits)
{
footprint_ = footprint;
r_max_ = circumradius(footprint);
start_ = start;
decision_ = decision;
params_ = params;
limits_ = limits;
last_yaw_ = start.yaw;
rotated_ = 0.0;
current_speed_ = 0.0;
}
/// @param obstacles Vật cản cùng frame với @p current, ĐÃ bỏ điểm trong footprint tại @p current.
Tick tick(const Pose2& current, const std::vector<Point2>& obstacles, double dt)
{
if (decision_.motion == Motion::kAlreadyFacing)
{
return finish(TickStatus::kSucceeded, "evade: already facing the free side");
}
if (decision_.motion == Motion::kNone)
{
return finish(TickStatus::kFailed, "evade: no feasible motion");
}
if (!std::isfinite(current.x) || !std::isfinite(current.y) || !std::isfinite(current.yaw))
{
return finish(TickStatus::kFailed, "robot pose is NaN/Inf — stopping the evade");
}
if (!std::isfinite(dt) || dt < 0.0)
{
dt = 0.0;
}
return decision_.motion == Motion::kBackUp ? tickBackUp(current, obstacles, dt)
: tickRotate(current, obstacles, dt);
}
/// The caller published 0 this tick (obstacle view lost): restart the ramp from 0 when motion resumes.
void hold()
{
current_speed_ = 0.0;
}
private:
Tick finish(TickStatus status, const char* message)
{
current_speed_ = 0.0;
Tick t;
t.status = status;
t.progress = status == TickStatus::kSucceeded ? 1.0 : 0.0;
t.message = message;
return t;
}
double nextSpeed(double target, double acc_lim, double remaining, double dt) const
{
if (dt <= 0.0)
{
return current_speed_; // tick cùng mốc với start: chưa có thời gian để tăng tốc
}
const double step = acc_lim * dt;
double speed = target > current_speed_ ? std::min(target, current_speed_ + step)
: std::max(target, current_speed_ - step);
speed = std::min(speed, remaining / dt);
return std::max(speed, 0.0);
}
Tick tickBackUp(const Pose2& current, const std::vector<Point2>& obstacles, double dt)
{
const double traveled = -((current.x - start_.x) * std::cos(start_.yaw) +
(current.y - start_.y) * std::sin(start_.yaw));
const double remaining = params_.backup_distance - traveled;
if (remaining <= kBackupTolerance)
{
return finish(TickStatus::kSucceeded, "evade back-up complete");
}
if (backupBlockedAt(footprint_, r_max_, current, remaining + params_.motion_margin,
obstacles) >= 0.0)
{
return finish(TickStatus::kFailed, "obstacle entered the back-up path — stopping the evade");
}
current_speed_ = nextSpeed(limits_.backup_speed, limits_.acc_lim_x, remaining, dt);
Tick t;
t.status = TickStatus::kRunning;
t.vx = -current_speed_;
t.progress = traveled / params_.backup_distance;
t.remaining = remaining;
t.message = "evade: backing up";
return t;
}
Tick tickRotate(const Pose2& current, const std::vector<Point2>& obstacles, double dt)
{
const double direction = decision_.rotation >= 0.0 ? 1.0 : -1.0;
// Có dấu: quay ngược chiều (trượt) không bị tính là tiến; cộng dồn từng bước nên vượt π vẫn đúng.
rotated_ += direction * normalizeAngle(current.yaw - last_yaw_);
last_yaw_ = current.yaw;
const double target = std::abs(decision_.rotation);
const double remaining = target - rotated_;
if (remaining <= kRotateTolerance)
{
return finish(TickStatus::kSucceeded, "evade rotation complete");
}
const double overshoot = params_.motion_margin / std::max(r_max_, 1e-3);
if (!arcClear(footprint_, r_max_, current, direction * remaining, overshoot, obstacles))
{
return finish(TickStatus::kFailed, "obstacle entered the rotation arc — stopping the evade");
}
current_speed_ = nextSpeed(limits_.rotate_speed, limits_.acc_lim_theta, remaining, dt);
Tick t;
t.status = TickStatus::kRunning;
t.wz = direction * current_speed_;
t.progress = rotated_ / target;
t.remaining = remaining;
t.message = "evade: rotating";
return t;
}
Polygon footprint_;
double r_max_ = 0.0; ///< [m]
Pose2 start_;
Decision decision_;
Params params_;
MotionLimits limits_;
double last_yaw_ = 0.0; ///< [rad]
double rotated_ = 0.0; ///< [rad] tiến độ có dấu theo chiều xoay
double current_speed_ = 0.0; ///< [m/s] hoặc [rad/s] đang phát, để ramp
};
/**
* @class ViewGuard
* @brief Tolerates a short loss of the obstacle view (stale scan, TF a little late): hold still while it lasts,
* give up once it has lasted `timeout` [s]. Never lets the robot move on old data — it only decides
* between "wait" and "fail". Sim 27/11: single late scans (0.53 s) or TF gaps (0.13 s) killed a back-up.
*/
class ViewGuard
{
public:
enum class State
{
kSeeing, ///< fresh view this tick
kHolding, ///< lost, still within the timeout: publish 0 and wait
kExpired ///< lost for >= timeout: fail
};
void reset()
{
lost_ = false;
since_ = 0.0;
}
/// @param now [s] same clock on every call. @param timeout [s] 0 = fail on the first loss.
State update(bool seeing, double now, double timeout)
{
if (seeing)
{
lost_ = false;
return State::kSeeing;
}
if (!lost_)
{
lost_ = true;
since_ = now;
}
return now - since_ >= timeout ? State::kExpired : State::kHolding;
}
bool lost() const
{
return lost_;
}
private:
bool lost_ = false;
double since_ = 0.0; ///< [s] when the current loss began
};
} // namespace evade
} // namespace recovery_plugins
#endif // RECOVERY_CORE_PLUGINS_EVADE_CORE_H_