/********************************************************************* * * Software License Agreement (BSD License) * * sbpl_recovery — recovery họ path: lập đường vòng quanh vật cản rồi NỐI LẠI global plan hiện hành. * * Port từ `navigation_experimental/sbpl_recovery` (Eitan Marder-Eppstein, BSD) sang khuôn * `recovery_core`. Hai khác biệt có chủ đích so với bản gốc: * * 1. Bản gốc TỰ LÁI: chạy pose_follower bên trong và publish thẳng cmd_vel — hai nguồn vận tốc * song song với move_base. Ở đây behavior thuộc họ `kPath`: nó chỉ TRẢ VỀ đường vòng; runtime * áp path đó và local planner đang active bám theo (một nguồn vận tốc duy nhất, đúng D8). * 2. Bản gốc nhận plan qua topic; ở đây plan đến từ `RecoveryContext::plan` — chính plan mà * control loop đang bám, không lệch phiên bản. * * Đường vòng được NỐI với phần còn lại của plan cũ (splice): contract 2026-08-04b không replan sau * recovery, nên path trả về phải đi tới đích của CHẶNG, không phải chỉ tới điểm nối — nếu không * robot sẽ báo "tới đích" ngay tại điểm nối giữa tuyến. * * Author: DuongTD *********************************************************************/ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace sbpl_recovery { namespace { constexpr double kDefaultPlanningDistance = 2.0; // [m] constexpr double kDefaultSampleStep = 0.5; // [m] constexpr double kDefaultRejoinClearance = 0.5; // [m] constexpr double kDefaultMaxRejoinDistance = 0.0; // [m] 0 = quét tới cuối plan / rìa lưới constexpr int kDefaultAttemptsPerRun = 3; constexpr double kSpacingEpsilon = 1e-6; // [m] constexpr double kReferencePlanLogThrottle = 10.0; // [s] double sqDistance(const robot_geometry_msgs::PoseStamped& a, const robot_geometry_msgs::PoseStamped& b) { const double dx = a.pose.position.x - b.pose.position.x; const double dy = a.pose.position.y - b.pose.position.y; return dx * dx + dy * dy; } /// [m] Khoảng cách từ điểm tới đoạn thẳng. double pointToSegment(double px, double py, double ax, double ay, double bx, double by) { const double dx = bx - ax; const double dy = by - ay; const double len_sq = dx * dx + dy * dy; if (len_sq <= 1e-12) { return std::hypot(px - ax, py - ay); } double t = ((px - ax) * dx + (py - ay) * dy) / len_sq; t = std::max(0.0, std::min(1.0, t)); return std::hypot(px - (ax + t * dx), py - (ay + t * dy)); } /** * @brief [m] Độ lệch lớn nhất của @p detour so với đoạn plan gốc `plan[0..rejoin]`. * * Đây là guard cho ràng buộc lệch tuyến của fleet: order chỉ định tuyến, robot chỉ được rời khỏi nó * trong một hành lang cho phép. Đo so với **plan gốc** chứ không so với đường thẳng nối hai đầu — * plan gốc mới là thứ fleet đã duyệt. */ double maxDeviation(const std::vector& plan, std::size_t rejoin, const std::vector& detour) { if (plan.size() < 2 || detour.empty()) { return 0.0; } const std::size_t last = std::min(rejoin, plan.size() - 1); double worst = 0.0; for (const robot_geometry_msgs::PoseStamped& pose : detour) { double best = std::numeric_limits::max(); for (std::size_t i = 0; i < last; ++i) { best = std::min(best, pointToSegment(pose.pose.position.x, pose.pose.position.y, plan[i].pose.position.x, plan[i].pose.position.y, plan[i + 1].pose.position.x, plan[i + 1].pose.position.y)); } worst = std::max(worst, best); } return worst; } } // namespace /** * @class DetourPathRecovery * @brief Lập đường vòng bằng một global planner plugin (mặc định SBPL) và nối lại plan hiện hành. * * Thuật toán (giữ nguyên khung của bản gốc): * 1. `onStart`: chụp plan hiện hành; đi dọc plan tới đoạn GẦN robot (tránh chọn điểm nối sau lưng * trên tuyến vòng), rồi chọn tối đa `attempts_per_run` ứng viên điểm nối cách robot ít nhất * `planning_distance` và cách nhau `sample_step` dọc plan. * 2. Mỗi `update()` thử ĐÚNG MỘT ứng viên: makePlan(pose hiện tại → ứng viên) trên costmap đã * chọn. Thành công → trả path = đường vòng + phần plan cũ sau điểm nối, `kSucceeded`. * Hết ứng viên → `kFailed`, state machine chuyển behavior kế tiếp của route. * * ## Ba chế độ costmap (`costmap_source`) * * - `combined` (khuyến nghị, xem `DETOUR_MERGED_GRID_PLAN.md`): LƯỚI GỘP — snapshot global làm * nền (tường/kệ tĩnh, phủ toàn bản đồ) rồi đè cửa sổ local lên (vật cản sensor tươi). Mutex hai * costmap chỉ bị giữ trong lúc copy (~vài ms); SBPL search trên bản chụp KHÔNG giữ mutex nào — * map update không bao giờ bị planner bỏ đói. Một frame (map), một nguồn sự thật: quét ứng viên, * SBPL và splice cùng nhìn một lưới. Cần planner export capability `ExternalGrid` * (sbpl_lattice_planner có sẵn). Điểm nối được quét tới CUỐI plan. * - `local`: chỉ cửa sổ lăn — cho hệ không có global costmap; điểm nối kẹt trong cửa sổ. * - `global`: chỉ lưới tĩnh — cho hệ mà global có nạp obstacle. Đã đo trên sim 2026-08-05: global * KHÔNG nạp sensor thì goal nào SBPL cũng vẽ xuyên đúng chỗ vật cản tươi — đừng dùng khi đó. * * ## Timing * * `onUpdate` chạy trên control thread. Một lượt makePlan trên cửa sổ local là lời gọi "nặng" so * với khuyến cáo của hook, nhưng CHỦ ĐÍCH chấp nhận: trong RECOVERING họ path robot đứng yên * (velocity source = kNone), một cycle giãn ra không làm sai lệnh nào — cùng ngân sách thời gian * mà recovery blocking của move_base gen-1 vẫn dùng. Mỗi tick chỉ thử một ứng viên để chặn trên * từng cycle là một lượt planner duy nhất. * * Param (namespace của instance): * - `planner_name` [string, "SBPLLatticePlanner"] tên instance planner: vừa là namespace đọc * param, vừa là tên truyền vào `initialize()`. Đổi nó = có một instance tuning * riêng (vd `allocated_time` ngắn cho detour) mà không đụng bản dùng chung. * - `planner_symbol` [string, = planner_name] alias Boost.DLL **có thật** trong `.so`, và cũng là * khoá tra `/library_path`. Chỉ cần khai khi `planner_name` * không phải một alias có thật — đúng trường hợp `SBPLLatticePlanner`, vốn chỉ * export một symbol duy nhất (khác bộ local planner, nơi mỗi biến thể là một * class riêng có alias riêng). * - `use_global_costmap` [bool, false] legacy; `costmap_source` khai thì thắng. * - `planning_distance` [m, 2.0] điểm nối cách robot tối thiểu chừng này. * - `sample_step` [m, 0.5] khoảng cách dọc plan giữa hai ứng viên liên tiếp. * - `rejoin_clearance` [m, 0.5] điểm nối phải cách pose bẩn gần nhất (CẢ HAI PHÍA dọc * plan) ít nhất chừng này. Sát mép vật cản thì đường vòng * gần như luôn đâm vào vùng đệm của chính nó. * - `max_rejoin_distance` [m, 0 = không giới hạn] TRẦN quét dọc plan, thuần tuỳ chọn: quét luôn * tự dừng ở rìa lưới (`kOutside`) hoặc cuối plan. Đừng đặt * nhỏ: sim 2026-08-05 hai lần liền cap cắt quét ngay sau * pose bẩn cuối và báo "không có chỗ sạch" dù chưa nhìn tiếp. * - `attempts_per_run` [int, 3] số ứng viên tối đa một lượt. * - `rejoin_on` [string, "reference"] tuyến để nối lại: `reference` = tuyến GỐC của chặng (plan * do planner sinh — detour tự kéo robot về tuyến order, và * `max_deviation` đo đúng hành lang fleet đã duyệt); * `current` = plan đang bám (hành vi cũ, tuyến trôi dần qua * từng lượt detour). Runtime không cấp tuyến tham chiếu thì * tự quay về `current` kèm cảnh báo. * - `timeout` [s] trần lượt, base cưỡng chế (0 = không giới hạn). * - `lock_costmap` [bool, true] giữ mutex costmap quanh makePlan (giao thức với * map-update thread). CHỈ unit test với costmap placeholder được tắt. * - `costmap_frame_override` [string, ""] frame của costmap khi không dereference được costmap. * CHỈ dành cho unit test với costmap placeholder. */ class DetourPathRecovery final : public recovery_core::RecoveryBehavior { public: DetourPathRecovery() = default; static recovery_core::RecoveryBehavior::RecoveryBehaviorPtr create() { return std::make_shared(); } recovery_core::RecoveryOutputType outputKind() const override { return recovery_core::RecoveryOutputType::kPath; } protected: bool onConfigure(robot::NodeHandle& nh) override { nh.param("planner_name", planner_name_, std::string("SBPLLatticePlanner")); // Symbol Boost.DLL mặc định TRÙNG tên instance. Tách ra vì hai thứ này chỉ trùng nhau khi mỗi // biến thể planner là một class riêng có alias riêng (như bộ local planner). `SBPLLatticePlanner` // chỉ export ĐÚNG MỘT symbol, nên muốn một instance SBPL riêng cho detour (allocated_time ngắn // để không treo control thread) thì phải nạp cùng symbol đó nhưng đọc param từ namespace khác. nh.param("planner_symbol", planner_symbol_, planner_name_); // "local" | "global" | "combined". Khai thì thắng `use_global_costmap` (giữ để tương thích). nh.param("costmap_source", costmap_source_, std::string()); nh.param("use_global_costmap", use_global_costmap_, false); nh.param("planning_distance", planning_distance_, kDefaultPlanningDistance); nh.param("sample_step", sample_step_, kDefaultSampleStep); nh.param("rejoin_clearance", rejoin_clearance_, kDefaultRejoinClearance); nh.param("max_rejoin_distance", max_rejoin_distance_, kDefaultMaxRejoinDistance); nh.param("attempts_per_run", attempts_per_run_, kDefaultAttemptsPerRun); nh.param("max_deviation", max_deviation_, 0.0); // "reference" | "current". Xem @ref rejoin_on_ và RecoveryContext::reference_plan. nh.param("rejoin_on", rejoin_on_, std::string("reference")); nh.param("lock_costmap", lock_costmap_, true); nh.param("costmap_frame_override", costmap_frame_override_, std::string()); if (rejoin_on_ != "reference" && rejoin_on_ != "current") { robot::log_error("[sbpl_recovery] '%s': rejoin_on='%s' must be reference | current.", name().c_str(), rejoin_on_.c_str()); return false; } if (planner_name_.empty() || planner_symbol_.empty()) { robot::log_error("[sbpl_recovery] '%s': planner_name/planner_symbol must not be empty.", name().c_str()); return false; } if (costmap_source_.empty()) { costmap_source_ = use_global_costmap_ ? "global" : "local"; } if (costmap_source_ != "local" && costmap_source_ != "global" && costmap_source_ != "combined") { robot::log_error("[sbpl_recovery] '%s': costmap_source='%s' must be local | global | " "combined.", name().c_str(), costmap_source_.c_str()); return false; } // combined = LƯỚI GỘP (2026-08-05, vòng 3): global nền + local đè, SBPL initialize trên GLOBAL // (env theo kích thước lưới gộp) và nhận bản chụp gộp qua capability ExternalGrid mỗi attempt. // Nguyên lý không đổi: người LẬP đường phải nhìn thấy vật cản tươi — giờ nhìn qua lưới gộp. use_global_costmap_ = costmap_source_ != "local"; if (!std::isfinite(planning_distance_) || planning_distance_ <= 0.0) { robot::log_error("[sbpl_recovery] '%s': planning_distance=%.3f m must be > 0.", name().c_str(), planning_distance_); return false; } if (!std::isfinite(sample_step_) || sample_step_ <= 0.0) { robot::log_error("[sbpl_recovery] '%s': sample_step=%.3f m must be > 0.", name().c_str(), sample_step_); return false; } if (!std::isfinite(rejoin_clearance_) || rejoin_clearance_ < 0.0) { robot::log_error("[sbpl_recovery] '%s': rejoin_clearance=%.3f m must be >= 0.", name().c_str(), rejoin_clearance_); return false; } if (!std::isfinite(max_rejoin_distance_) || max_rejoin_distance_ < 0.0) { robot::log_error("[sbpl_recovery] '%s': max_rejoin_distance=%.3f m must be >= 0 " "(0 = scan to the end of the plan).", name().c_str(), max_rejoin_distance_); return false; } if (max_rejoin_distance_ > 0.0 && max_rejoin_distance_ < planning_distance_) { // Tầm quét ngắn hơn khoảng cách tối thiểu tới điểm nối thì không ứng viên nào lọt qua được cả // hai điều kiện — lượt detour nào cũng từ chối, im lặng. robot::log_error("[sbpl_recovery] '%s': max_rejoin_distance=%.3f m < planning_distance=%.3f " "m — no candidate could ever satisfy both.", name().c_str(), max_rejoin_distance_, planning_distance_); return false; } if (attempts_per_run_ < 1) { robot::log_error("[sbpl_recovery] '%s': attempts_per_run=%d must be >= 1.", name().c_str(), attempts_per_run_); return false; } if (!std::isfinite(max_deviation_) || max_deviation_ < 0.0) { robot::log_error("[sbpl_recovery] '%s': max_deviation=%.3f m must be >= 0 (0 = no limit).", name().c_str(), max_deviation_); return false; } // Họ path không bị base bắt buộc có pose, nhưng behavior NÀY cần: điểm nối chọn theo khoảng // cách tới robot. Chặn ở boot thay vì lượt chạy đầu tiên. if (ctx().pose == nullptr) { robot::log_error("[sbpl_recovery] '%s': needs a PoseProvider to pick a rejoin point.", name().c_str()); return false; } robot_costmap_2d::Costmap2DROBOT* costmap = chosenCostmap(); if (costmap == nullptr) { robot::log_error("[sbpl_recovery] '%s': the %s costmap is missing from the context.", name().c_str(), use_global_costmap_ ? "global" : "local"); return false; } if (costmap_source_ == "combined" && costmap_frame_override_.empty() && ctx().local_costmap == nullptr) { // Lưới gộp cần CẢ HAI nguồn — thiếu mắt tươi thì đây chỉ còn là mode "global", và mode đó // đã được đo là mù vật cản sensor. Bắt lỗi cấu hình ở boot thay vì chạy sai âm thầm. robot::log_error("[sbpl_recovery] '%s': costmap_source=combined needs BOTH costmaps but the " "local costmap is missing from the context.", name().c_str()); return false; } return loadPlanner(costmap); } bool onStart(const recovery_core::RecoveryGoal& /*goal*/) override { robot_costmap_2d::Costmap2DROBOT* costmap = chosenCostmap(); if (costmap == nullptr) { robot::log_error("[sbpl_recovery] '%s': costmap disappeared from the context.", name().c_str()); return false; } // Con trỏ costmap là non-owning và CÓ THỂ bị thay giữa hai lượt (contract của RecoveryContext). // Planner đã initialize() với con trỏ cũ thì phải dựng lại — dùng tiếp là đọc một costmap chết. if (costmap != initialized_costmap_ && !loadPlanner(costmap)) { return false; } // Costmap quá hạn = lưới đang mô tả một thế giới của quá khứ. Lập đường vòng trên nó là sinh // ra một plan trông hợp lệ nhưng vô nghĩa (sim 2026-08-05: detour 22-31 pose trên map cũ ngay // sau khi chính attempt SBPL trước đó bỏ đói map update). Từ chối kèm lý do; gate qua test seam // vì costmap placeholder của unit test không dereference được. if (costmap_frame_override_.empty()) { const bool chosen_current = costmap->isCurrent(); const bool local_current = costmap_source_ != "combined" || ctx().local_costmap == nullptr || ctx().local_costmap->isCurrent(); if (!chosen_current || !local_current) { robot::log_warning("[sbpl_recovery] '%s': refusing to start — the %s costmap is stale " "(planning on a past world produces junk detours).", name().c_str(), !chosen_current ? (use_global_costmap_ ? "global" : "local") : "local"); return false; } } // Tuyến để NỐI LẠI. Mặc định là tuyến THAM CHIẾU của chặng (plan do planner sinh), không phải // plan đang bám (2026-08-05e): nối vào plan đang bám nghĩa là mỗi lượt detour lấy kết quả của // lượt trước làm mốc — sim đo được tuyến bị ăn mòn dần (rejoin 106/305 -> 130/289 -> 132/273), // robot không bao giờ quay về tuyến order, và `max_deviation` đo với một mốc đã trôi nên hành // lang fleet mất ý nghĩa. Nối vào tuyến tham chiếu thì chính SBPL kéo robot trở lại tuyến đã // duyệt, và đuôi splice cũng là đuôi tuyến gốc nên chặng luôn kết thúc đúng chỗ. plan_.clear(); const bool want_reference = rejoin_on_ == "reference" && ctx().reference_plan != nullptr; bool have_plan = want_reference && ctx().reference_plan->getGlobalPlan(plan_) && !plan_.empty(); if (!have_plan) { // Runtime không cấp tuyến tham chiếu (hoặc chưa có plan nào của planner): quay về plan đang // bám. Mất khả năng tự về tuyến, nhưng vẫn vòng được — im lặng thì tệ hơn. if (want_reference) { robot::log_warning_throttle( kReferencePlanLogThrottle, "[sbpl_recovery] '%s': no reference route available — rejoining the CURRENT plan " "instead; detours will not pull the robot back to the order route.", name().c_str()); } plan_.clear(); have_plan = ctx().plan != nullptr && ctx().plan->getGlobalPlan(plan_) && !plan_.empty(); } if (!have_plan) { robot::log_warning("[sbpl_recovery] '%s': no plan to rejoin — refusing to start.", name().c_str()); return false; } plan_frame_ = plan_.front().header.frame_id; costmap_frame_ = costmapFrame(costmap); if (plan_frame_ != costmap_frame_ && ctx().tf == nullptr) { // Local costmap (odom) + plan (map) là ca mặc định — thiếu TF thì không quy đổi được. robot::log_error("[sbpl_recovery] '%s': plan frame '%s' != costmap frame '%s' and the " "context has no TF buffer.", name().c_str(), plan_frame_.c_str(), costmap_frame_.c_str()); return false; } robot_geometry_msgs::PoseStamped robot_in_plan; if (!robotPoseIn(plan_frame_, robot_in_plan)) { robot::log_warning("[sbpl_recovery] '%s': robot pose unavailable — cannot pick a rejoin " "point.", name().c_str()); return false; } // Lưới gộp cho lượt quét ứng viên; mỗi attempt trong onUpdate sẽ chụp lại bản tươi hơn. if (merged_active_ && !buildMergedGrid()) { robot::log_warning("[sbpl_recovery] '%s': could not build the merged grid — refusing to " "start.", name().c_str()); return false; } buildCandidates(robot_in_plan); if (candidates_.empty()) { // Không có điểm nối nào đặt được robot vào: từ chối NGAY thay vì chạy `attempts_per_run` lượt // SBPL chắc chắn hỏng — mỗi lượt hỏng vẫn giữ mutex costmap trọn `allocated_time` và làm đói // thread cập nhật costmap. // // Log kèm SỐ LIỆU của lượt quét: "không có ứng viên" có ít nhất ba nguyên nhân khác hẳn nhau // (tầm quét quá ngắn, vật cản trải dài qua rìa tầm, hoặc ngưỡng khoảng cách quá chặt) và // không phân biệt được chúng nếu chỉ báo kết quả. robot::log_warning("[sbpl_recovery] '%s': no placeable rejoin point — refusing to start. " "plan=%zu pose(s), scanned=%zu, scan ended at %.2f m (cap %.2f m, 0 = " "none), blocked=%zu, first blocked at %.2f m, last blocked at %.2f m, " "last blocked IN VIEW at %.2f m (that is the one the rejoin point must " "clear), first joinable spot at %.2f m (need >= %.2f m from any block " "and >= %.2f m from the robot).", name().c_str(), plan_.size(), scan_.scanned, scan_.reach_distance, max_rejoin_distance_, scan_.blocked, scan_.first_blocked_distance, scan_.last_blocked_distance, scan_.last_blocked_in_view_distance, scan_.first_clear_distance, rejoin_clearance_, planning_distance_); return false; } attempt_ = 0; return true; } recovery_core::RecoveryResult onUpdate(const robot::Time& now, double /*dt*/) override { if (attempt_ >= candidates_.size()) { return recovery_core::RecoveryResult::Failed() .withProgress(1.0, 0.0) .withMessage("no reachable rejoin point on the plan after " + std::to_string(candidates_.size()) + " attempt(s)"); } const std::size_t rejoin_index = candidates_[attempt_]; // Pose lấy TƯƠI mỗi lượt thử: behavior trước đó trong route (rotate/back_up) có thể đã dời // robot; và mất pose giữa chừng phải kết thúc lượt, không dùng pose cũ. robot_geometry_msgs::PoseStamped start; if (!robotPoseIn(costmap_frame_, start)) { return recovery_core::RecoveryResult::Failed().withMessage("robot pose became unavailable"); } robot_geometry_msgs::PoseStamped rejoin_goal; std::vector detour; bool planned = false; try { rejoin_goal = toFrame(plan_[rejoin_index], costmap_frame_); if (merged_active_) { // Lưới gộp: chụp lại bản TƯƠI trước từng attempt (mutex chỉ bị giữ trong lúc copy), rồi // SBPL search trên bản chụp — KHÔNG giữ mutex costmap nào, map update không bị bỏ đói dù // attempt thua đốt trọn allocated_time. if (!buildMergedGrid()) { return recovery_core::RecoveryResult::Failed() .withMessage("could not rebuild the merged grid (TF/costmap unavailable)"); } set_external_grid_(planner_.get(), &merged_grid_); planned = planner_->makePlan(start, rejoin_goal, detour); } // Cùng giao thức khoá với PlannerRunner/gen-1: map-update thread ghi lưới dưới mutex này, // planner đọc lưới sống thì phải giữ nó. Chỉ unit test với costmap placeholder được tắt. else if (lock_costmap_) { robot_costmap_2d::Costmap2DROBOT* costmap = chosenCostmap(); boost::unique_lock lock( *(costmap->getCostmap()->getMutex())); planned = planner_->makePlan(start, rejoin_goal, detour); } else { planned = planner_->makePlan(start, rejoin_goal, detour); } } catch (const std::exception& ex) { robot::log_warning("[sbpl_recovery] '%s': attempt %zu/%zu threw: %s", name().c_str(), attempt_ + 1, candidates_.size(), ex.what()); planned = false; } if (planned && !detour.empty() && max_deviation_ > 0.0) { // Guard lệch tuyến: đường vòng phải nằm trong hành lang fleet cho phép quanh tuyến gốc. // `plan_` ở frame plan còn `detour` vừa được planner sinh ra ở frame costmap, nên phải quy // về cùng frame trước khi đo. TF đứt giữa chừng thì bỏ qua guard — nhánh splice bên dưới sẽ // gặp lại đúng lỗi đó và xử lý một lần. std::vector detour_in_plan_frame; detour_in_plan_frame.reserve(detour.size()); bool converted = true; try { for (const robot_geometry_msgs::PoseStamped& pose : detour) { detour_in_plan_frame.push_back(toFrame(pose, plan_frame_)); } } catch (const std::exception&) { converted = false; } if (converted) { const double deviation = maxDeviation(plan_, rejoin_index, detour_in_plan_frame); // [m] if (deviation > max_deviation_) { robot::log_warning("[sbpl_recovery] '%s': attempt %zu/%zu strays %.2f m from the route " "(limit %.2f m) — rejected.", name().c_str(), attempt_ + 1, candidates_.size(), deviation, max_deviation_); ++attempt_; return recovery_core::RecoveryResult::Running() .withProgress(progressNow(), remainingNow()) .withMessage("detour rejected: deviates too far from the route"); } } } if (planned && !detour.empty()) { robot_nav_msgs::Path out; out.header.frame_id = plan_frame_; out.header.stamp = now; out.poses.reserve(detour.size() + (plan_.size() - rejoin_index)); try { for (const robot_geometry_msgs::PoseStamped& pose : detour) { out.poses.push_back(toFrame(pose, plan_frame_)); } } catch (const std::exception& ex) { // TF đứt đúng giữa lúc quy đổi kết quả: đường vòng không dùng được, coi như lượt thử hỏng. robot::log_warning("[sbpl_recovery] '%s': could not express the detour in '%s': %s", name().c_str(), plan_frame_.c_str(), ex.what()); ++attempt_; return recovery_core::RecoveryResult::Running() .withProgress(progressNow(), remainingNow()) .withMessage("detour found but its frame conversion failed"); } // Nối phần còn lại của plan cũ SAU điểm nối: contract 2026-08-04b không replan sau recovery, // path này phải tự đi tới đích của chặng. Bỏ chính pose điểm nối — detour đã kết thúc ở đó. for (std::size_t i = rejoin_index + 1; i < plan_.size(); ++i) { out.poses.push_back(plan_[i]); } robot::log_info("[sbpl_recovery] '%s': detour with %zu pose(s) rejoins the plan at index " "%zu/%zu (attempt %zu/%zu).", name().c_str(), detour.size(), rejoin_index, plan_.size(), attempt_ + 1, candidates_.size()); return recovery_core::RecoveryResult::PathOut(out, recovery_core::RecoveryStatus::kSucceeded) .withProgress(1.0, 0.0) .withMessage("detour rejoins the current plan"); } ++attempt_; return recovery_core::RecoveryResult::Running() .withProgress(progressNow(), remainingNow()) .withMessage("detour attempt " + std::to_string(attempt_) + "/" + std::to_string(candidates_.size()) + " failed"); } private: robot_costmap_2d::Costmap2DROBOT* chosenCostmap() const { return use_global_costmap_ ? ctx().global_costmap : ctx().local_costmap; } /// Frame của costmap đã chọn. Override chỉ dành cho unit test với costmap placeholder — /// production để rỗng và đọc thẳng từ costmap. std::string costmapFrame(robot_costmap_2d::Costmap2DROBOT* costmap) const { return costmap_frame_override_.empty() ? costmap->getGlobalFrameID() : costmap_frame_override_; } bool loadPlanner(robot_costmap_2d::Costmap2DROBOT* costmap) { // Tra library_path và đọc param của planner từ ROOT config (không phải namespace của instance // recovery) — cùng chỗ với mọi planner khác, nên `SBPLLatticePlanner` dùng chung tuning với // backup planner nếu trùng tên. robot::NodeHandle root_nh; robot::PluginLoaderHelper loader(root_nh); const std::string library_path = loader.findLibraryPath(planner_symbol_); if (library_path.empty()) { robot::log_error("[sbpl_recovery] '%s': no library found for planner symbol '%s' — check the " "key '%s/library_path' in the YAML.", name().c_str(), planner_symbol_.c_str(), planner_symbol_.c_str()); return false; } try { // factory_ giữ .so còn nạp — phải sống lâu hơn planner_ (factory_ khai TRƯỚC planner_ nên bị // huỷ SAU). planner_factory_ = boost::dll::import_alias( library_path, planner_symbol_, boost::dll::load_mode::append_decorations); planner_ = planner_factory_(); } catch (const boost::system::system_error& ex) { robot::log_error("[sbpl_recovery] '%s': could not load symbol '%s' from '%s': %s. Lưu ý: " "`planner_symbol` phải là alias Boost.DLL CÓ THẬT trong .so; muốn một " "instance tuning riêng thì đổi `planner_name` (namespace param), không phải " "symbol.", name().c_str(), planner_symbol_.c_str(), library_path.c_str(), ex.what()); return false; } catch (const std::exception& ex) { robot::log_error("[sbpl_recovery] '%s': error while loading planner '%s': %s", name().c_str(), planner_symbol_.c_str(), ex.what()); return false; } if (!planner_) { robot::log_error("[sbpl_recovery] '%s': factory of '%s' returned null.", name().c_str(), planner_symbol_.c_str()); return false; } try { // Boot-time là chỗ đúng cho initialize: SBPL dựng environment theo kích thước costmap và // CHẶN tới khi costmap khác 0 — không được làm điều đó trong control loop. if (!planner_->initialize(planner_name_, costmap)) { robot::log_error("[sbpl_recovery] '%s': planner '%s' reported an initialize() failure.", name().c_str(), planner_name_.c_str()); planner_.reset(); return false; } } catch (const std::exception& ex) { robot::log_error("[sbpl_recovery] '%s': initialize() of '%s' threw: %s", name().c_str(), planner_name_.c_str(), ex.what()); planner_.reset(); return false; } initialized_costmap_ = costmap; // `costmap_frame_override` là test seam với costmap placeholder — lúc đó không được dựng // checker thật (nó sẽ dereference placeholder) và cũng không nạp capability lưới ngoài. merged_active_ = false; if (costmap_frame_override_.empty()) { if (costmap_source_ == "global") { // Checker phải nhìn cùng lưới với planner (ctx().collision của runtime trỏ local). own_checker_ = std::make_unique(costmap); } else if (costmap_source_ == "combined") { // Lưới gộp cần planner nhận lưới NGOÀI (bản chụp global+local). Capability nằm ngoài // interface BaseGlobalPlanner nên tra qua một alias Boost.DLL thứ hai trong CÙNG .so: // "ExternalGrid". Thiếu nó = planner này không chạy được mode combined — // báo lỗi cấu hình ở boot, không âm thầm rơi về hành vi khác. try { // std::function giữ luôn tham chiếu .so bên trong callable của boost::dll — cùng cơ chế // giữ-sống với planner_factory_. set_external_grid_ = boost::dll::import_alias( library_path, planner_symbol_ + "ExternalGrid", boost::dll::load_mode::append_decorations); } catch (const std::exception& ex) { robot::log_error("[sbpl_recovery] '%s': costmap_source=combined but '%s' does not " "export the '%sExternalGrid' capability: %s. Use a planner that " "supports external grids, or switch costmap_source to local/global.", name().c_str(), library_path.c_str(), planner_symbol_.c_str(), ex.what()); planner_.reset(); return false; } merged_active_ = true; } } robot::log_info("[sbpl_recovery] '%s': detour planner '%s' ready on the %s costmap.", name().c_str(), planner_name_.c_str(), costmap_source_ == "combined" ? "merged (global+local)" : (use_global_costmap_ ? "global" : "local")); return true; } /** * @brief Chụp lưới gộp: global làm nền, cửa sổ local đè lên (xem merge_grids.h). * * Mutex mỗi costmap chỉ bị giữ trong lúc copy nguyên khối lưới của nó; phần overlay chạy trên * hai BẢN CHỤP nên không đụng costmap sống. TF local->map tra MỘT lần cho cả lượt. */ bool buildMergedGrid() { robot_costmap_2d::Costmap2DROBOT* global = ctx().global_costmap; robot_costmap_2d::Costmap2DROBOT* local = ctx().local_costmap; if (global == nullptr || local == nullptr) { return false; } PlanarTransform2D local_to_map; // Ghi lại làm member: pha quét ứng viên cần chiều ngược. const std::string local_frame = local->getGlobalFrameID(); const std::string map_frame = global->getGlobalFrameID(); if (local_frame != map_frame) { if (ctx().tf == nullptr) { robot::log_warning("[sbpl_recovery] '%s': merged grid needs TF '%s' -> '%s' but the " "context has no TF buffer.", name().c_str(), local_frame.c_str(), map_frame.c_str()); return false; } try { const tf3::TransformStampedMsg transform = ctx().tf->lookupTransform(map_frame, local_frame, tf3::Time()); local_to_map.x = transform.transform.translation.x; local_to_map.y = transform.transform.translation.y; // Quaternion phẳng (robot 2D): yaw = 2*atan2(z, w) — cùng phép rút gọn với port SBPL. const double yaw = 2.0 * std::atan2(transform.transform.rotation.z, transform.transform.rotation.w); local_to_map.cos_yaw = std::cos(yaw); local_to_map.sin_yaw = std::sin(yaw); } catch (const std::exception& ex) { robot::log_warning("[sbpl_recovery] '%s': TF '%s' -> '%s' unavailable for the merged " "grid: %s", name().c_str(), local_frame.c_str(), map_frame.c_str(), ex.what()); return false; } } { boost::unique_lock lock( *(global->getCostmap()->getMutex())); merged_grid_ = *global->getCostmap(); } { boost::unique_lock lock( *(local->getCostmap()->getMutex())); local_snapshot_ = *local->getCostmap(); } overlayLocalGrid(local_snapshot_, local_to_map, merged_grid_); local_to_map_ = local_to_map; return true; } /// Pose robot trong @p frame. Trả false khi mất pose hoặc TF không quy đổi được. bool robotPoseIn(const std::string& frame, robot_geometry_msgs::PoseStamped& out) const { robot_geometry_msgs::PoseStamped raw; if (!ctx().pose->getRobotPose(raw)) { return false; } try { out = toFrame(raw, frame); } catch (const std::exception& ex) { robot::log_warning("[sbpl_recovery] '%s': cannot express the robot pose in '%s': %s", name().c_str(), frame.c_str(), ex.what()); return false; } return true; } /// Quy @p in về @p target qua TF của context. Ném tf3 exception khi không quy đổi được. robot_geometry_msgs::PoseStamped toFrame(const robot_geometry_msgs::PoseStamped& in, const std::string& target) const { if (in.header.frame_id == target || in.header.frame_id.empty()) { return in; } if (ctx().tf == nullptr) { throw std::runtime_error("frame '" + in.header.frame_id + "' != '" + target + "' and no TF buffer is available"); } const tf3::TransformStampedMsg transform = ctx().tf->lookupTransform(target, in.header.frame_id, tf3::Time()); robot_geometry_msgs::PoseStamped out; tf3::doTransform(in, out, transform); out.header.frame_id = target; return out; } /** * @brief Đặt được robot tại pose này không (footprint thật, trên costmap đang dùng). * * Không có collision checker, hoặc không quy đổi được frame → coi là **đặt được**. "Không biết" * không được biến thành "loại": loại nhầm hết ứng viên thì detour mất sạch đường ra, trong khi * planner mới là bên phán quyết cuối cùng. */ /** * @brief Collision checker khớp với costmap mà DETOUR đang lập plan trên đó. * * `ctx().collision` của runtime trỏ vào costmap LOCAL. Khi `use_global_costmap: true`, kiểm ứng * viên bằng checker local là tự mâu thuẫn: pose ngoài cửa sổ lăn 8x8 m bị đọc thành "chắn" trong * khi SBPL trên global costmap tới đó bình thường — đúng lỗi sim 2026-08-05 (footprint của pose ở * ~3.5 m vươn quá rìa 4.0 m, `kOutsideMap`, cả đuôi tầm quét thành "vật cản"). Người quyết định * và người kiểm phải nhìn cùng một lưới. */ const recovery_core::CollisionChecker* checker() const { if (use_global_costmap_ && own_checker_ != nullptr) { return own_checker_.get(); } return ctx().collision; } /** * @brief Phân loại một vị trí ứng viên trên costmap đã chọn. * * Kiểm **một điểm** (tâm robot), KHÔNG quét footprint — hai lý do, cả hai đo được trên sim * 2026-08-05: * 1. Footprint dài ~1 m làm dải "chắn" quanh vật cản phình thêm cả mét mỗi phía; cộng với việc * footprint của pose ở ~3.5 m ló khỏi rìa cửa sổ lăn 4.0 m (bị đọc thành chắn), cả đuôi tầm * quét thành "vật cản" và không bao giờ còn điểm nối. * 2. SBPL — người phán quyết cuối — đằng nào cũng tự kiểm footprint khi lập đường; ở đây chỉ cần * lọc thô. Cùng phép đo với `move_base2::checkPlan` (thứ khai hoả lượt detour này), nên hai * bên nhìn thấy cùng một dải bẩn. * * `kUnknown` được coi là ĐẶT ĐƯỢC — khớp cả ba bên trong cùng đường chạy: `checkPlan` bỏ qua ô * NO_INFORMATION, SBPL chạy `allow_unknown: true`. Lệch một bên là monitor báo chắn còn detour * thấy sạch (hoặc ngược lại) — vòng lặp vô nghĩa. * * `kOutside` phải được bên gọi xử lý là **hết tầm quét**, không phải vật cản. */ /// @brief Phân loại một điểm bằng @p collision trong @p frame. Lỗi TF -> kFree (không loại mù). recovery_core::CollisionChecker::Placement classifyOn( const recovery_core::CollisionChecker* collision, const std::string& frame, const robot_geometry_msgs::PoseStamped& pose_in_plan) const { using Placement = recovery_core::CollisionChecker::Placement; if (collision == nullptr) { return Placement::kOutside; } robot_geometry_msgs::PoseStamped in_grid; try { in_grid = toFrame(pose_in_plan, frame); } catch (const std::exception&) { return Placement::kFree; } return collision->classifyPoint(in_grid.pose.position.x, in_grid.pose.position.y); } /// @brief Phân loại một CELL trên lưới gộp (đã ở frame của lưới — map). recovery_core::CollisionChecker::Placement classifyMergedPoint(double wx, double wy) const { using Placement = recovery_core::CollisionChecker::Placement; unsigned int mx = 0; unsigned int my = 0; if (!merged_grid_.worldToMap(wx, wy, mx, my)) { return Placement::kOutside; } const unsigned char cost = merged_grid_.getCost(mx, my); if (cost == robot_costmap_2d::NO_INFORMATION) { // Cùng quy ước với checkPlan và SBPL allow_unknown: chưa biết KHÔNG phải vật cản. return Placement::kUnknown; } if (cost == robot_costmap_2d::LETHAL_OBSTACLE || cost == robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE) { return Placement::kBlocked; } return Placement::kFree; } /** * @brief Pose này có nằm trong TẦM NHÌN LOCAL (cửa sổ costmap lăn) không? * * Chỉ dùng để chọn `last_blocked_in_view` — pose bẩn ngoài tầm là dữ liệu cũ (đuôi plan không bao * giờ được replan, và lưới gộp ngoài cửa sổ chỉ còn dữ liệu tĩnh của global) nên không được quyền * quyết định điểm nối phải nằm đâu. **Không** dùng làm bộ lọc ứng viên: điểm nối ngoài cửa sổ vẫn * hợp lệ, vì planner chạy trên lưới gộp cỡ global. * * Dùng thẳng membership của lưới local thay vì một tham số "tầm nhìn" riêng: đúng hình học thật * của cửa sổ lăn, và tự đúng khi ai đó đổi kích thước costmap. * * Mode `local`/`global` không có bản chụp local → trả true cho mọi pose, tức luật suy biến về * "sau pose bẩn cuối cùng trong tầm quét", đúng hành vi của hai mode đó. */ bool inLocalView(const robot_geometry_msgs::PoseStamped& pose_in_plan) const { if (!merged_active_ || local_snapshot_.getSizeInCellsX() == 0) { return true; } robot_geometry_msgs::PoseStamped in_map; try { in_map = toFrame(pose_in_plan, costmap_frame_); } catch (const std::exception&) { return true; // Không quy đổi được thì không loại — luật suy biến về tầm quét, an toàn hơn. } double lx = 0.0; double ly = 0.0; local_to_map_.applyInverse(in_map.pose.position.x, in_map.pose.position.y, lx, ly); unsigned int mx = 0; unsigned int my = 0; return local_snapshot_.worldToMap(lx, ly, mx, my); } recovery_core::CollisionChecker::Placement classifyPose( const robot_geometry_msgs::PoseStamped& pose_in_plan) const { using Placement = recovery_core::CollisionChecker::Placement; // Mode "combined": MỘT lưới gộp (global nền + local đè) là nguồn sự thật duy nhất — cùng lưới // mà SBPL sẽ lập đường trên đó, nên người quét và người lập nhìn thấy cùng một thế giới. if (merged_active_) { robot_geometry_msgs::PoseStamped in_grid; try { in_grid = toFrame(pose_in_plan, costmap_frame_); } catch (const std::exception&) { return Placement::kFree; // Lỗi TF -> không loại mù; planner là người phán quyết cuối. } return classifyMergedPoint(in_grid.pose.position.x, in_grid.pose.position.y); } const recovery_core::CollisionChecker* collision = checker(); if (collision == nullptr) { return Placement::kFree; // Không biết thì không loại — planner là người phán quyết cuối. } return classifyOn(collision, costmap_frame_, pose_in_plan); } /** * @brief Chọn ứng viên điểm nối trên plan. * * Ba pha: * 1. Tiến dọc plan tới đoạn **gần robot** — không có pha này, một tuyến vòng lại gần chỗ robot sẽ * cho điểm nối phía sau lưng và robot quay đầu chạy ngược tuyến. * 2. Tìm **pose bẩn cuối cùng trong tầm với**: đó là chỗ chắn phải vòng qua. * 3. Nhận ứng viên **đặt được robot vào**, nằm **sau** chỗ chắn ít nhất `rejoin_clearance`, cách * robot ít nhất `planning_distance`, cách nhau `sample_step`. * * Pha 2 và điều kiện "sạch" ở pha 3 là thứ bản gốc (và bản đầu của gói này) **không có**: chọn * điểm nối thuần theo khoảng cách nghĩa là các ứng viên nằm ngay trên vật cản đang chắn tuyến — * planner không bao giờ tới được, và mỗi lượt thử hỏng vẫn tốn trọn `allocated_time` trong lúc * đang giữ mutex costmap. Đây đúng là lỗi đã quan sát trên sim 2026-08-05: ba ứng viên ở 2.03, * 2.55, 3.06 m đều nằm trên tuyến bị chắn và cả ba đều "Solution not found". */ void buildCandidates(const robot_geometry_msgs::PoseStamped& robot_in_plan) { candidates_.clear(); const double sq_planning_distance = planning_distance_ * planning_distance_; // --- Pha 1 --------------------------------------------------------------------------------- std::size_t near_index = 0; while (near_index < plan_.size() && sqDistance(robot_in_plan, plan_[near_index]) >= sq_planning_distance) { ++near_index; } if (near_index == plan_.size()) { near_index = 0; // Plan không bao giờ lại gần robot — xét từ đầu thay vì bỏ cuộc. } // --- Pha 2: quét & phân loại MỘT lượt ------------------------------------------------------- // // Ranh giới quét: rìa lưới costmap (`kOutside` — phần plan ngoài lưới không đánh giá được, // không phải "chắn"), cuối plan, hoặc trần tuỳ chọn `max_rejoin_distance` (> 0). Với lưới gộp // phủ toàn bản đồ, quét đi tới CUỐI plan. using Placement = recovery_core::CollisionChecker::Placement; struct ScannedPose { std::size_t index; double travelled; // [m] dọc plan, tính từ đoạn gần robot. Placement placement; }; std::vector scanned; // Cấp phát mỗi lượt recovery — sự kiện hiếm, ngoài control path. scanned.reserve(plan_.size() - near_index); scan_ = ScanStats(); std::size_t last_blocked_in_view = plan_.size(); { double travelled = 0.0; // [m] for (std::size_t i = near_index; i < plan_.size(); ++i) { if (i > near_index) { travelled += std::sqrt(sqDistance(plan_[i - 1], plan_[i])); } scan_.reach_distance = travelled; // [m] chỗ quét thật sự dừng, dù dừng vì lý do nào. if (max_rejoin_distance_ > 0.0 && travelled > max_rejoin_distance_) { break; } const Placement placement = classifyPose(plan_[i]); if (placement == Placement::kOutside) { break; } ++scan_.scanned; scanned.push_back({i, travelled, placement}); if (placement == Placement::kBlocked) { ++scan_.blocked; scan_.last_blocked_distance = travelled; // [m] if (scan_.first_blocked_distance < 0.0) { scan_.first_blocked_distance = travelled; // [m] } // Chỉ chỗ chắn NHÌN THẤY ĐƯỢC mới quyết định điểm nối phải nằm ở đâu — xem chú thích // của pha 4. if (inLocalView(plan_[i])) { last_blocked_in_view = i; scan_.last_blocked_in_view_distance = travelled; // [m] } } } } const bool have_block = last_blocked_in_view < plan_.size(); // --- Pha 3: khoảng cách tới pose bẩn gần nhất, HAI PHÍA dọc plan ---------------------------- // // Hành lang này tính với MỌI pose bẩn, kể cả ngoài tầm nhìn: nó là kiểm hình học tại chỗ (đừng // đặt goal sát một bức tường mà global đã biết), rẻ, và không thể giết ứng viên ở xa nó. const double kInfinity = std::numeric_limits::infinity(); std::vector to_prev_block(scanned.size(), kInfinity); std::vector to_next_block(scanned.size(), kInfinity); { double prev_block_at = -kInfinity; // [m] travelled của pose bẩn gần nhất phía trước. for (std::size_t k = 0; k < scanned.size(); ++k) { if (scanned[k].placement == Placement::kBlocked) { to_prev_block[k] = 0.0; prev_block_at = scanned[k].travelled; } else if (prev_block_at > -kInfinity) { to_prev_block[k] = scanned[k].travelled - prev_block_at; } } double next_block_at = kInfinity; // [m] travelled của pose bẩn gần nhất phía sau. for (std::size_t k = scanned.size(); k-- > 0;) { if (scanned[k].placement == Placement::kBlocked) { to_next_block[k] = 0.0; next_block_at = scanned[k].travelled; } else if (next_block_at < kInfinity) { to_next_block[k] = next_block_at - scanned[k].travelled; } } } // --- Pha 4: ứng viên ------------------------------------------------------------------------ // // Luật "sau pose bẩn CUỐI CÙNG TRONG TẦM NHÌN LOCAL" (2026-08-05f). Hai luật trước đều sai, và // sai ở PHẠM VI chứ không sai ở ý: // - "sau pose bẩn cuối toàn tầm quét": đuôi plan không bao giờ được replan nên nó cắt qua vật // cản ở xa; một vết bẩn ở 7.96 m thành "chỗ chắn cuối" và giết sạch ứng viên hợp lệ ngay sau // vật cản ĐANG chắn ở 2.5 m -> refuse -> ABORT (log sim 11:00); // - "sau CỤM CHẮN ĐẦU TIÊN": chữa được ca trên nhưng nối vào khe giữa hai vật cản CÙNG NHÌN // THẤY, robot chạy ~0.5 m rồi bị chắn lại -> detour lặp quanh đúng vật cản thứ nhất. // Đúng: chỗ chắn nào robot ĐANG NHÌN THẤY (nằm trong cửa sổ costmap local) thì phải vòng qua // hết; chỗ chắn ngoài tầm là dữ liệu cũ, không được quyền phủ quyết. // // Điểm nối ĐƯỢC PHÉP nằm ngoài cửa sổ local: từ 2026-08-05e planner chạy trên lưới GỘP cỡ // global, nên biên thật của nó là bản đồ global chứ không phải cửa sổ lăn. Vật cản kéo dài quá // tầm nhìn thì đường vòng tới một chỗ ta chưa thấy — monitor sẽ bắn lại và detour lượt nữa; // đoán một lần rồi sửa rẻ hơn nhích từng đoạn để lấy đúng thông tin đó. // // Đường lùi cho plan ngắn hơn `planning_distance`. CHỈ dùng khi không có chỗ chắn nào: nếu có, // một điểm nối "gần nhất có thể" gần như luôn nằm trước vật cản, tức vô nghĩa. std::size_t fallback = plan_.size(); double last_accepted_at = -kInfinity; // [m] travelled của ứng viên vừa nhận (giãn sample_step). for (std::size_t k = 0; k < scanned.size(); ++k) { const std::size_t i = scanned[k].index; if (scanned[k].placement == Placement::kBlocked) { continue; } if (have_block) { if (i <= last_blocked_in_view) { continue; // Phải qua HẾT phần chắn NHÌN THẤY ĐƯỢC, không chỉ cụm đầu tiên. } if (to_prev_block[k] + kSpacingEpsilon < rejoin_clearance_ || to_next_block[k] + kSpacingEpsilon < rejoin_clearance_) { continue; // Sát mép vật cản (phía nào cũng vậy) thì đường vòng đâm vào vùng đệm của nó. } if (scan_.first_clear_distance < 0.0) { scan_.first_clear_distance = scanned[k].travelled; // [m] chỗ nối được sớm nhất (chẩn đoán). } } else if (i > near_index) { fallback = i; } if (sqDistance(robot_in_plan, plan_[i]) < sq_planning_distance) { continue; } if (scanned[k].travelled - last_accepted_at + kSpacingEpsilon < sample_step_) { continue; } candidates_.push_back(i); last_accepted_at = scanned[k].travelled; if (candidates_.size() >= static_cast(attempts_per_run_)) { break; } } if (candidates_.empty() && fallback < plan_.size()) { candidates_.push_back(fallback); } } double progressNow() const { return candidates_.empty() ? 1.0 : static_cast(attempt_) / static_cast(candidates_.size()); } double remainingNow() const { return static_cast(candidates_.size() - std::min(attempt_, candidates_.size())); } // --- Param --------------------------------------------------------------- std::string planner_name_ = "SBPLLatticePlanner"; ///< Namespace param + tên truyền vào initialize(). std::string planner_symbol_ = "SBPLLatticePlanner"; ///< Alias Boost.DLL thật trong .so. bool use_global_costmap_ = false; double planning_distance_ = kDefaultPlanningDistance; ///< [m] double sample_step_ = kDefaultSampleStep; ///< [m] double rejoin_clearance_ = kDefaultRejoinClearance; ///< [m] cách chỗ chắn tối thiểu. double max_rejoin_distance_ = kDefaultMaxRejoinDistance; ///< [m] tầm quét, <= nửa cửa sổ costmap. int attempts_per_run_ = kDefaultAttemptsPerRun; double max_deviation_ = 0.0; ///< [m] 0 = không giới hạn. /// "reference" = nối vào tuyến gốc của chặng (mặc định, tự về tuyến order); "current" = nối vào /// plan đang bám (hành vi trước 2026-08-05e). std::string rejoin_on_ = "reference"; bool lock_costmap_ = true; std::string costmap_frame_override_; ///< Test seam — production để rỗng. // --- Planner plugin (factory_ khai trước planner_: .so phải sống lâu hơn instance) ----------- std::function planner_factory_; robot_nav_core::BaseGlobalPlanner::Ptr planner_; robot_costmap_2d::Costmap2DROBOT* initialized_costmap_ = nullptr; ///< non-owning. /// Checker trên costmap ĐÃ CHỌN, chỉ dựng cho mode "global" (ctx().collision là local). std::unique_ptr own_checker_; std::string costmap_source_; ///< "local" | "global" | "combined". // --- Lưới gộp (mode combined) --------------------------------------------------------------- /// Capability lưới ngoài của planner (alias "ExternalGrid"); std::function giữ .so sống. std::function set_external_grid_; robot_costmap_2d::Costmap2D merged_grid_; ///< Bản chụp gộp; buffer tái dùng giữa các lượt. robot_costmap_2d::Costmap2D local_snapshot_; ///< Bản chụp cửa sổ local; tái dùng như trên. /// Frame local -> frame lưới gộp, chụp cùng lúc với hai lưới. Chiều ngược dùng cho @ref inLocalView. PlanarTransform2D local_to_map_; bool merged_active_ = false; ///< combined + đủ hai costmap + planner có capability. // --- Trạng thái một lượt -------------------------------------------------- std::vector plan_; ///< Bản chụp plan, frame plan_frame_. std::string plan_frame_; std::string costmap_frame_; std::vector candidates_; ///< Index điểm nối trong plan_, thử tuần tự. std::size_t attempt_ = 0; /// Số liệu lượt quét gần nhất — chỉ để log khi từ chối, không tham gia quyết định nào. struct ScanStats { std::size_t scanned = 0; std::size_t blocked = 0; double first_blocked_distance = -1.0; ///< [m] pose bẩn ĐẦU TIÊN; -1 = không có chỗ chắn nào. /// [m] pose bẩn cuối cùng còn NHÌN THẤY ĐƯỢC — mốc quyết định điểm nối. -1 = không có. double last_blocked_in_view_distance = -1.0; double last_blocked_distance = -1.0; ///< [m] pose bẩn cuối cùng trong tầm quét. double first_clear_distance = -1.0; ///< [m] chỗ nối được sớm nhất (đủ clearance); -1 = không. double reach_distance = 0.0; ///< [m] chỗ quét kết thúc thật: rìa lưới, cap, hoặc hết plan. }; ScanStats scan_; }; } // namespace sbpl_recovery BOOST_DLL_ALIAS(sbpl_recovery::DetourPathRecovery::create, DetourPathRecovery)