/********************************************************************* * * Software License Agreement (BSD License) * * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Willow Garage nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Author: Mike Phillips *********************************************************************/ #include #include #include #include #include #include #include #include #include #include #include using namespace std; namespace robot_geometry_msgs { bool operator== (const Point &p1, const Point &p2) { return p1.x == p2.x && p1.y == p2.y && p1.z == p2.z; } } namespace sbpl_lattice_planner{ class LatticeSCQ : public StateChangeQuery{ public: LatticeSCQ(EnvironmentNAVXYTHETALAT* env, std::vector const & changedcellsV) : env_(env), changedcellsV_(changedcellsV) { } // lazy init, because we do not always end up calling this method virtual std::vector const * getPredecessors() const{ if(predsOfChangedCells_.empty() && !changedcellsV_.empty()) env_->GetPredsofChangedEdges(&changedcellsV_, &predsOfChangedCells_); return &predsOfChangedCells_; } // lazy init, because we do not always end up calling this method virtual std::vector const * getSuccessors() const{ if(succsOfChangedCells_.empty() && !changedcellsV_.empty()) env_->GetSuccsofChangedEdges(&changedcellsV_, &succsOfChangedCells_); return &succsOfChangedCells_; } EnvironmentNAVXYTHETALAT * env_; std::vector const & changedcellsV_; mutable std::vector predsOfChangedCells_; mutable std::vector succsOfChangedCells_; }; SBPLLatticePlanner::SBPLLatticePlanner() : initialized_(false), costmap_robot_(NULL), external_grid_(NULL){ } SBPLLatticePlanner::SBPLLatticePlanner(std::string name, robot_costmap_2d::Costmap2DROBOT* costmap_robot) : initialized_(false), costmap_robot_(NULL), external_grid_(NULL) { initialize(name, costmap_robot); } void SBPLLatticePlanner::setExternalGrid(const robot_costmap_2d::Costmap2D* grid){ external_grid_ = grid; } const robot_costmap_2d::Costmap2D* SBPLLatticePlanner::activeGrid() const{ return external_grid_ != NULL ? external_grid_ : costmap_robot_->getCostmap(); } const char* SBPLLatticePlanner::costClassName(unsigned char cost){ // Semantics của costmap trong port này, không phải của SBPL: 254 lethal, 253 = trong bán kính // inscribed của một ô lethal, 255 = chưa biết. FREE_SPACE ở đây là 60 chứ không phải 0 // (cost_values.h): dưới 60 là lane ưu tiên (PreferredLayer hạ cost), trên 60 là inflation hoặc // vùng unpreferred. if (cost == robot_costmap_2d::LETHAL_OBSTACLE) return "LETHAL"; if (cost == robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE) return "INSCRIBED"; if (cost == robot_costmap_2d::NO_INFORMATION) return "UNKNOWN"; if (cost == robot_costmap_2d::FREE_SPACE) return "FREE"; if (cost < robot_costmap_2d::FREE_SPACE) return "PREFERRED"; return "INFLATED/UNPREFERRED"; } SBPLLatticePlanner::PoseAudit SBPLLatticePlanner::auditPose( const robot_costmap_2d::Costmap2D* grid, double wx, double wy, double theta) const{ PoseAudit a; a.in_map = grid->worldToMap(wx, wy, a.mx, a.my); if (!a.in_map) { return a; } a.cost = grid->getCost(a.mx, a.my); // Cùng phép kiểm SBPL dùng bên trong khi mở rộng: mọi ô footprint phải trong lưới và < obsthresh. // SetGoal() của SBPL chỉ CẢNH BÁO khi phép này false, và cảnh báo đó bị compile bỏ (SBPL_PRINTF // rỗng) — nên goal như vậy lọt qua, rồi search quét hết map mới báo không có đường. Chỉ số ô // của worldToMap trùng với CONTXY2DISC(x - origin) mà SetStart/SetGoal dùng cho điểm trong lưới. a.footprint_ok = env_ != NULL && env_->IsValidConfiguration(static_cast(a.mx), static_cast(a.my), env_->ContTheta2DiscNew(theta)); return a; } void SBPLLatticePlanner::logGridWindow(const robot_costmap_2d::Costmap2D* grid, int radius, unsigned int cx, unsigned int cy, unsigned int sx, unsigned int sy, unsigned int gx, unsigned int gy, const char* label) const{ // Một dòng mỗi hàng, hàng y lớn in trước để nhìn như bản đồ (y hướng lên). Ký hiệu: // . FREE (60) - PREFERRED (<60) : INFLATED/UNPREFERRED (61-252) // i INSCRIBED (253) # LETHAL (254) ? UNKNOWN (255) S start G goal const int W = static_cast(grid->getSizeInCellsX()); const int H = static_cast(grid->getSizeInCellsY()); robot::log_info("[sbpl_lattice_planner] grid window around %s: center cell (%u,%u), %d x %d cells " "@ %.3f m | . free - preferred : inflated/unpreferred i inscribed # lethal " "? unknown S start G goal", label, cx, cy, 2 * radius + 1, 2 * radius + 1, grid->getResolution()); std::string row; row.reserve(static_cast(2 * radius + 1)); for (int dy = radius; dy >= -radius; --dy) { row.clear(); const int y = static_cast(cy) + dy; for (int dx = -radius; dx <= radius; ++dx) { const int x = static_cast(cx) + dx; char c; if (x < 0 || y < 0 || x >= W || y >= H) { c = ' '; // ngoài lưới } else if (x == static_cast(sx) && y == static_cast(sy)) { c = 'S'; } else if (x == static_cast(gx) && y == static_cast(gy)) { c = 'G'; } else { const unsigned char cost = grid->getCost(static_cast(x), static_cast(y)); c = (cost == robot_costmap_2d::LETHAL_OBSTACLE) ? '#' : (cost == robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE) ? 'i' : (cost == robot_costmap_2d::NO_INFORMATION) ? '?' : (cost == robot_costmap_2d::FREE_SPACE) ? '.' : (cost < robot_costmap_2d::FREE_SPACE) ? '-' : ':'; } row.push_back(c); } robot::log_info("[sbpl_lattice_planner] %5d |%s|", y, row.c_str()); } } bool SBPLLatticePlanner::initialize(std::string name, robot_costmap_2d::Costmap2DROBOT* costmap_robot){ if(!initialized_){ robot::NodeHandle nh; robot::NodeHandle private_nh = robot::NodeHandle(nh, name); robot::log_info("Name is %s", name.c_str()); private_nh.param("planner_type", planner_type_, string("ARAPlanner")); private_nh.param("allocated_time", allocated_time_, 10.0); private_nh.param("initial_epsilon",initial_epsilon_,3.0); private_nh.param("environment_type", environment_type_, string("XYThetaLattice")); private_nh.param("forward_search", forward_search_, bool(false)); private_nh.param("primitive_filename",primitive_filename_,string("")); private_nh.param("force_scratch_limit",force_scratch_limit_,500); // Đường dẫn TƯƠNG ĐỐI của file mprim được giải theo cây config đang chạy (2026-09-11), cùng thứ // tự NodeHandle dùng: PNKX_NAV_CORE_CONFIG_DIR rồi PNKX_NAV_CORE_DIR/config. Trước đây YAML phải // ghi đường dẫn tuyệt đối — máy dev chép sang robot là gãy (`/home/duongtd/rl_ws/...`). if (!primitive_filename_.empty() && primitive_filename_[0] != '/' && access(primitive_filename_.c_str(), R_OK) != 0) { std::vector candidates; if (const char* cfg = std::getenv("PNKX_NAV_CORE_CONFIG_DIR")) candidates.push_back(std::string(cfg) + "/" + primitive_filename_); if (const char* root = std::getenv("PNKX_NAV_CORE_DIR")) candidates.push_back(std::string(root) + "/config/" + primitive_filename_); bool resolved = false; for (const std::string& c : candidates) { if (access(c.c_str(), R_OK) == 0) { robot::log_info("[sbpl_lattice_planner] primitive_filename '%s' resolved to '%s'", primitive_filename_.c_str(), c.c_str()); primitive_filename_ = c; resolved = true; break; } } if (!resolved) { robot::log_error("[sbpl_lattice_planner] primitive_filename '%s' is relative and was not " "found under PNKX_NAV_CORE_CONFIG_DIR or PNKX_NAV_CORE_DIR/config", primitive_filename_.c_str()); } } double nominalvel_mpersecs, timetoturn45degsinplace_secs; private_nh.param("nominalvel_mpersecs", nominalvel_mpersecs, 0.4); private_nh.param("timetoturn45degsinplace_secs", timetoturn45degsinplace_secs, 0.6); robot::log_error("nominalvel_mpersecs: %f, timetoturn45degsinplace_secs: %f, primitive_filename_: %s",nominalvel_mpersecs,timetoturn45degsinplace_secs,primitive_filename_.c_str()); int lethal_obstacle; private_nh.param("lethal_obstacle",lethal_obstacle,20); lethal_obstacle_ = (unsigned char) lethal_obstacle; inscribed_inflated_obstacle_ = lethal_obstacle_-1; sbpl_cost_multiplier_ = (unsigned char) (robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE/inscribed_inflated_obstacle_ + 1); robot::log_debug("SBPL: lethal: %uz, inscribed inflated: %uz, multiplier: %uz",lethal_obstacle,inscribed_inflated_obstacle_,sbpl_cost_multiplier_); private_nh.param("publish_footprint_path", publish_footprint_path_, bool(true)); private_nh.param("visualizer_skip_poses", visualizer_skip_poses_, 5); private_nh.param("allow_unknown", allow_unknown_, bool(true)); if (!private_nh.hasParam("allow_unknown")) { // Khoá này quyết định robot có được lập plan xuyên vùng chưa scan hay không, và quyết định // goal ngoài vùng đã map fail tức thì (false) hay quét cả map 6-7 s rồi mới fail (true, đo // 2026-09-17). Default C++ âm thầm là true — nói ra để người vận hành biết mình đang dựa vào nó. robot::log_warning("[sbpl_lattice_planner] '%s/allow_unknown' not set in YAML — defaulting to " "true (unknown cells are traversable). Set it explicitly.", name.c_str()); } // chỉ bật khi local planner có bước quay tại chỗ đầu path (turn_around_priority) private_nh.param("free_start_heading", free_start_heading_, bool(false)); // Nhóm log chẩn đoán lập plan. Mặc định BẬT: tắt là lựa chọn có ý thức của người đang không cần // debug, không phải thứ đổi sau lưng người đang dựa vào log. Dòng LỖI không đi qua khoá này. private_nh.param("debug_plan", debug_plan_, bool(true)); private_nh.param("debug_grid_window", debug_grid_window_, 0); if (debug_grid_window_ < 0) { robot::log_warning("[sbpl_lattice_planner] debug_grid_window=%d < 0, using 0 (off)", debug_grid_window_); debug_grid_window_ = 0; } constexpr int kMaxGridWindow = 60; // 121x121 ô = 6 m @5 cm; hơn nữa là spam log, không đọc nổi if (debug_grid_window_ > kMaxGridWindow) { robot::log_warning("[sbpl_lattice_planner] debug_grid_window=%d > %d, clamping", debug_grid_window_, kMaxGridWindow); debug_grid_window_ = kMaxGridWindow; } robot::log_info("[sbpl_lattice_planner] '%s' config: allocated_time=%.1fs initial_epsilon=%.2f " "allow_unknown=%s free_start_heading=%s forward_search=%s | debug_plan=%s " "debug_grid_window=%d", name.c_str(), allocated_time_, initial_epsilon_, allow_unknown_ ? "true" : "false", free_start_heading_ ? "true" : "false", forward_search_ ? "true" : "false", debug_plan_ ? "on" : "off", debug_grid_window_); name_ = name; costmap_robot_ = costmap_robot; robot::Time start_time = robot::Time::now(); robot::Rate rate(1.0); while(costmap_robot_->getCostmap()->getSizeInCellsX() == 0 || costmap_robot_->getCostmap()->getSizeInCellsY() == 0){ robot::log_warning("Waiting for costmap to be initialized..."); rate.sleep(); if((robot::Time::now() - start_time).toSec() > 2.0){ robot::log_error("Costmap not initialized after 10 seconds, exiting..."); exit(1); } } footprint_ = costmap_robot_->getRobotFootprint(); footprint_prev_ = footprint_; if ("XYThetaLattice" == environment_type_){ robot::log_debug("Using a 3D costmap for theta lattice\n"); env_ = new DirectionalEnvironmentNAVXYTHETALAT(); } else{ robot::log_error("XYThetaLattice is currently the only supported environment!\n"); exit(1); } circumscribed_cost_ = computeCircumscribedCost(); if (circumscribed_cost_ == 0) { // Unfortunately, the inflation_radius is not taken into account by // inflation_layer->computeCost(). If inflation_radius is smaller than // the circumscribed radius, SBPL will ignore some obstacles, but we // cannot detect this problem. If the cost_scaling_factor is too large, // SBPL won't run into obstacles, but will always perform an expensive // footprint check, no matter how far the nearest obstacle is. robot::log_warning("The costmap value at the robot's circumscribed radius (%f m) is 0.", costmap_robot_->getLayeredCostmap()->getCircumscribedRadius()); robot::log_warning("SBPL performance will suffer."); robot::log_warning("Please decrease the costmap's cost_scaling_factor."); } if(!env_->SetEnvParameter("cost_inscribed_thresh",costMapCostToSBPLCost(robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE))){ robot::log_error("Failed to set cost_inscribed_thresh parameter"); exit(1); } if(!env_->SetEnvParameter("cost_possibly_circumscribed_thresh", circumscribed_cost_)){ robot::log_error("Failed to set cost_possibly_circumscribed_thresh parameter"); exit(1); } int obst_cost_thresh = costMapCostToSBPLCost(robot_costmap_2d::LETHAL_OBSTACLE); vector perimeterptsV; perimeterptsV.reserve(footprint_.size()); for (size_t ii(0); ii < footprint_.size(); ++ii) { sbpl_2Dpt_t pt; pt.x = footprint_[ii].x; pt.y = footprint_[ii].y; perimeterptsV.push_back(pt); } // Kích thước env và cost ban đầu lấy từ lưới ĐANG CÓ HIỆU LỰC (activeGrid), không phải luôn là // lưới sống. Lần initialize() đầu tiên chạy trên control thread khi external_grid_ còn NULL nên // vẫn là lưới sống như trước. Nhưng re-init từ makePlan() (đổi kích thước map, đổi footprint) // chạy trên thread planner — và khi PlannerRunner đã đưa bản chụp (snapshot_for_readers) thì // thread đó KHÔNG còn giữ mutex costmap. Đọc cell sống ở đây lúc đó là đọc đua với map-update // thread, và resizeMap realloc mảng dưới chân vòng lặp. Bản chụp cùng kích thước/origin với // master tại thời điểm chụp nên env dựng theo nó là nhất quán với phần cost đổ vào sau. const robot_costmap_2d::Costmap2D* init_grid = activeGrid(); robot::log_info("footprint size = %zu", perimeterptsV.size()); robot::log_info("width=%d", init_grid->getSizeInCellsX()); robot::log_info("height=%d", init_grid->getSizeInCellsY()); robot::log_info("resolution=%f", init_grid->getResolution()); bool ret; try{ // robot::log_warning("DEBUG 2000"); ret = env_->InitializeEnv(init_grid->getSizeInCellsX(), // width init_grid->getSizeInCellsY(), // height 0, // mapdata 0, 0, 0, // start (x, y, theta, t) 0, 0, 0, // goal (x, y, theta) 0, 0, 0, //goal tolerance perimeterptsV, init_grid->getResolution(), nominalvel_mpersecs, timetoturn45degsinplace_secs, obst_cost_thresh, primitive_filename_.c_str()); if (ret) ret = env_->buildDirectionTable(); current_env_resolution_ = init_grid->getResolution(); current_env_width_ = init_grid->getSizeInCellsX(); current_env_height_ = init_grid->getSizeInCellsY(); // robot::log_warning("DEBUG 3000"); } catch(SBPL_Exception *e){ robot::log_error("SBPL encountered a fatal exception: %s", e->what()); ret = false; } if(!ret){ robot::log_error("SBPL initialization or direction table construction failed!"); delete env_; env_ = NULL; return false; } for (ssize_t ix(0); ix < init_grid->getSizeInCellsX(); ++ix) for (ssize_t iy(0); iy < init_grid->getSizeInCellsY(); ++iy) env_->UpdateCost(ix, iy, costMapCostToSBPLCost(init_grid->getCost(ix,iy))); if ("ARAPlanner" == planner_type_){ robot::log_info("Planning with ARA*"); planner_ = new ARAPlanner(env_, forward_search_); } else if ("ADPlanner" == planner_type_){ robot::log_info("Planning with AD*"); planner_ = new ADPlanner(env_, forward_search_); } else{ robot::log_error("ARAPlanner and ADPlanner are currently the only supported planners!\n"); exit(1); } // Preempt (2026-09-11) cần libsbpl có abort flag. Header nói có (SBPL_HAS_ABORT_FLAG) chưa đủ: // .so nạp lúc chạy có thể là bản cũ (ros-noetic-sbpl 2020 ở /opt/ros) — layout SBPLPlanner khác, // chạm vào set_abort_flag() là ghi đè member đầu của ARAPlanner. Probe symbol trước, không có thì // TUYỆT ĐỐI không đụng cờ và nói to: cancel sẽ không cắt được lượt đang chạy. sbpl_abort_supported_ = false; #ifdef SBPL_HAS_ABORT_FLAG { using ProbeFn = int (*)(); // boost::dll nạp plugin với RTLD_LOCAL, nên librobot_sbpl (dependency của .so này) không nằm // trong global scope và RTLD_DEFAULT không thấy nó dù đúng bản. RTLD_NEXT tra tiếp các // dependency của chính .so này. void* sym = dlsym(RTLD_DEFAULT, "sbpl_abort_flag_abi_version"); if (sym == nullptr) sym = dlsym(RTLD_NEXT, "sbpl_abort_flag_abi_version"); if (sym != nullptr && reinterpret_cast(sym)() == SBPL_ABORT_FLAG_ABI_VERSION) { sbpl_abort_supported_ = true; planner_->set_abort_flag(&preempt_); robot::log_info("[sbpl_lattice_planner] libsbpl abort flag: supported — cancel/pause can " "interrupt a running search"); } else { robot::log_error("[sbpl_lattice_planner] compiled against an sbpl header with abort flag " "but the loaded libsbpl.so has no sbpl_abort_flag_abi_version (old library " "on the load path?) — preempt DISABLED, a cancelled search runs to " "allocated_time. Fix the install so one libsbpl is used."); } } #else robot::log_warning("[sbpl_lattice_planner] built against an sbpl without abort flag — " "cancel/pause cannot interrupt a running search (runs to allocated_time)"); #endif robot::log_info("[sbpl_lattice_planner] Initialized successfully"); // plan_pub_ = private_nh.advertise("plan", 1); // stats_publisher_ = private_nh.advertise("sbpl_lattice_planner_stats", 1); // sbpl_plan_footprint_pub_ = private_nh.advertise("footprint_markers", 1); initialized_ = true; } return initialized_; } //Taken from Sachin's sbpl_cart_planner //This rescales the costmap according to a robotparam which sets the obstacle cost unsigned char SBPLLatticePlanner::costMapCostToSBPLCost(unsigned char newcost){ if(newcost == robot_costmap_2d::LETHAL_OBSTACLE || (!allow_unknown_ && newcost == robot_costmap_2d::NO_INFORMATION)) return lethal_obstacle_; else if(newcost == robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE) return inscribed_inflated_obstacle_; else if(newcost == 0 || newcost == robot_costmap_2d::NO_INFORMATION) return 0; else { unsigned char sbpl_cost = newcost / sbpl_cost_multiplier_; if (sbpl_cost == 0) sbpl_cost = 1; return sbpl_cost; } } unsigned char SBPLLatticePlanner::computeCircumscribedCost() { unsigned char result = 0; if (!costmap_robot_) { robot::log_error("Costmap is not initialized"); return 0; } // // check if the costmap has an inflation layer for (const auto &layer : *costmap_robot_->getLayeredCostmap()->getPlugins()) { // Kiểm tra layer có đúng type if (layer->getType() == robot_costmap_2d::LayerType::INFLATION_LAYER) { result = costMapCostToSBPLCost(layer->computeCost( costmap_robot_->getLayeredCostmap()->getCircumscribedRadius() / costmap_robot_->getCostmap()->getResolution())); } } return result; } bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start, const robot_geometry_msgs::PoseStamped& goal, std::vector& plan){ if(!initialized_){ robot::log_error("Global planner is not initialized"); return false; } // Mỗi lượt bắt đầu với cờ preempt SẠCH: một preempt nhắm vào lượt trước không được giết lượt này // (contract robot_nav_core::Preemptable). Cờ đã gắn vào planner_ ở initialize() nếu libsbpl hỗ trợ. preempt_.store(false, std::memory_order_relaxed); // Lưới cell đang có hiệu lực: bản chụp ngoài (detour trên lưới gộp) hoặc lưới sống. Footprint, // inflation và frame vẫn thuộc costmap sống — lưới ngoài bắt buộc cùng kích thước với nó. const robot_costmap_2d::Costmap2D* grid = activeGrid(); const auto direction_snapshot = costmap_robot_->getLayeredCostmap()->getDirectionFieldSnapshot(); const robot_costmap_2d::DirectionGeometry initial_geometry{grid->getSizeInCellsX(), grid->getSizeInCellsY(), grid->getResolution(), grid->getOriginX(), grid->getOriginY(), costmap_robot_->getGlobalFrameID()}; const auto initial_decision = decideDirection(direction_snapshot, have_previous_direction_, previous_direction_state_, previous_direction_generation_, initial_geometry); if (initial_decision.result == DirectionDecision::Result::kPending) { const auto now = std::chrono::steady_clock::now(); if (direction_pending_since_ == std::chrono::steady_clock::time_point{}) direction_pending_since_ = now; if (last_direction_pending_log_ == std::chrono::steady_clock::time_point{} || now - last_direction_pending_log_ >= std::chrono::seconds(5)) { const double waited = std::chrono::duration(now - direction_pending_since_).count(); robot::log_error("[sbpl_lattice_planner] direction field is not ready (%.1f s); refusing to plan", waited); last_direction_pending_log_ = now; } direction_scratch_pending_ = direction_scratch_pending_ || initial_decision.force_scratch; have_previous_direction_ = true; previous_direction_state_ = direction_snapshot.state; previous_direction_generation_ = direction_snapshot.generation; if (debug_plan_) robot::log_info("[sbpl_lattice_planner] direction state=PENDING generation=%llu rejected=0", static_cast(direction_snapshot.generation)); return false; } direction_pending_since_ = {}; last_direction_pending_log_ = {}; bool do_init = false; if (current_env_resolution_ != grid->getResolution()) { robot::log_info("Costmap resolution has changed, reinitializing sbpl_lattice_planner."); do_init = true; } else if (current_env_width_ != grid->getSizeInCellsX() || current_env_height_ != grid->getSizeInCellsY()) { robot::log_info("Costmap dimensions have changed from (%d x %d) to (%d x %d), reinitializing sbpl_lattice_planner.", current_env_width_, current_env_height_, grid->getSizeInCellsX(), grid->getSizeInCellsY()); do_init = true; } else if (footprint_ != costmap_robot_->getRobotFootprint()) { robot::log_info("Robot footprint has changed, reinitializing sbpl_lattice_planner."); do_init = true; } else if (circumscribed_cost_ != computeCircumscribedCost()) { robot::log_info("Cost at circumscribed radius has changed, reinitializing sbpl_lattice_planner."); do_init = true; } if (do_init) { initialized_ = false; delete planner_; planner_ = NULL; delete env_; env_ = NULL; // Footprint, inflation và frame vẫn lấy từ costmap SỐNG — lưới ngoài lệch kích thước với nó sẽ // churn re-init mỗi lượt. Contract của setExternalGrid cấm lệch, nhưng phát hiện được thì nói // thẳng. So với lưới sống thật (getCostmap()), KHÔNG so với `grid`: `grid` chính là // external_grid_ khi có lưới ngoài, nên phép so cũ luôn bằng nhau và không bao giờ bắn. // Chỉ đọc hai số kích thước, không chạm cell, nên không cần mutex. const robot_costmap_2d::Costmap2D* live = costmap_robot_->getCostmap(); if (external_grid_ != NULL && (external_grid_->getSizeInCellsX() != live->getSizeInCellsX() || external_grid_->getSizeInCellsY() != live->getSizeInCellsY())) { robot::log_error("[sbpl_lattice_planner] external grid (%d x %d) does not match the live " "costmap (%d x %d); dropping the external grid.", external_grid_->getSizeInCellsX(), external_grid_->getSizeInCellsY(), live->getSizeInCellsX(), live->getSizeInCellsY()); external_grid_ = NULL; grid = activeGrid(); } // Re-init đọc cell từ activeGrid(): bản chụp nếu có, lưới sống nếu không (xem initialize()). if (!initialize(name_, costmap_robot_)) return false; } // The snapshot owns the field through search, conversion and the optional realignment retry. struct DirectionGuard { DirectionalEnvironmentNAVXYTHETALAT* env; const robot_costmap_2d::DirectionFieldSnapshot& snapshot; bool debug; ~DirectionGuard() { if (debug) { const char* state = snapshot.state == robot_costmap_2d::DirectionFieldState::kReady ? "READY" : snapshot.state == robot_costmap_2d::DirectionFieldState::kPending ? "PENDING" : "DISABLED"; robot::log_info("[sbpl_lattice_planner] direction state=%s generation=%llu rejected=%llu", state, static_cast(snapshot.generation), static_cast(env->directionRejections())); } env->setDirectionField(nullptr); } } guard{env_, direction_snapshot, debug_plan_}; env_->resetDirectionRejections(); const robot_costmap_2d::DirectionGeometry geometry{grid->getSizeInCellsX(), grid->getSizeInCellsY(), grid->getResolution(), grid->getOriginX(), grid->getOriginY(), costmap_robot_->getGlobalFrameID()}; const auto decision = decideDirection(direction_snapshot, have_previous_direction_, previous_direction_state_, previous_direction_generation_, geometry); using DirectionResult = DirectionDecision::Result; direction_scratch_pending_ = direction_scratch_pending_ || decision.force_scratch; have_previous_direction_ = true; previous_direction_state_ = direction_snapshot.state; previous_direction_generation_ = direction_snapshot.generation; if (decision.result == DirectionResult::kGeometryMismatch) { const auto now = std::chrono::steady_clock::now(); if (last_direction_geometry_log_ == std::chrono::steady_clock::time_point{} || now - last_direction_geometry_log_ >= std::chrono::seconds(5)) { robot::log_error("[sbpl_lattice_planner] direction field geometry does not match the active grid"); last_direction_geometry_log_ = now; } return false; } last_direction_geometry_log_ = {}; env_->setDirectionField(decision.result == DirectionResult::kReady ? direction_snapshot.field.get() : nullptr); if (direction_scratch_pending_) { planner_->force_planning_from_scratch(); direction_scratch_pending_ = false; } plan.clear(); robot::log_info("[sbpl_lattice_planner] getting start point (%g,%g) goal point (%g,%g)", start.pose.position.x, start.pose.position.y,goal.pose.position.x, goal.pose.position.y); double theta_start = 2 * atan2(start.pose.orientation.z, start.pose.orientation.w); double theta_goal = 2 * atan2(goal.pose.orientation.z, goal.pose.orientation.w); // Heading thật của robot — giữ lại để retry nếu heading giả định không ra nghiệm. const double theta_start_actual = theta_start; bool start_heading_overridden = false; if (free_start_heading_) { // Local planner tự quay tại chỗ về hướng path trước khi bám (turn_around_priority), // nên heading xuất phát không phải ràng buộc thật. Giữ nguyên nó thì khi goal nằm // phía sau, SBPL sẽ vẽ cung quay đầu (U-turn) ở đầu path — chuỗi prim quay tại chỗ // đắt hơn cung tiến nhiều lần theo costmult nên không bao giờ được chọn. Gán heading // giả định hướng thẳng tới goal để path bắt đầu thẳng, phần xoay đầu do local planner lo. const double dx = goal.pose.position.x - start.pose.position.x; const double dy = goal.pose.position.y - start.pose.position.y; // Goal quá gần (< ~2 cell): hướng tới goal hết ý nghĩa, dùng luôn heading của goal. theta_start = (std::hypot(dx, dy) > 2.0 * grid->getResolution()) ? atan2(dy, dx) : theta_goal; start_heading_overridden = true; } int start_state_id = -1; int goal_state_id = -1; try{ int ret = env_->SetStart(start.pose.position.x - grid->getOriginX(), start.pose.position.y - grid->getOriginY(), theta_start); if(ret < 0 || planner_->set_start(ret) == 0){ robot::log_error("ERROR: failed to set start state\n"); return false; } start_state_id = ret; } catch(SBPL_Exception *e){ robot::log_error("SBPL encountered a fatal exception while setting the start state"); return false; } try{ int ret = env_->SetGoal(goal.pose.position.x - grid->getOriginX(), goal.pose.position.y - grid->getOriginY(), theta_goal); if(ret < 0 || planner_->set_goal(ret) == 0){ // Nhánh duy nhất SBPL tự từ chối: Ô goal ngoài lưới. Goal trong lưới nhưng footprint đè // tường thì SBPL im lặng nhận — phần audit bên dưới bắt ca đó. robot::log_error("ERROR: failed to set goal state — goal (%.3f, %.3f) is outside the " "%u x %u grid (origin %.2f, %.2f, %.3f m/cell)\n", goal.pose.position.x, goal.pose.position.y, grid->getSizeInCellsX(), grid->getSizeInCellsY(), grid->getOriginX(), grid->getOriginY(), grid->getResolution()); return false; } goal_state_id = ret; } catch(SBPL_Exception *e){ robot::log_error("SBPL encountered a fatal exception while setting the goal state"); return false; } int offOnCount = 0; int onOffCount = 0; int allCount = 0; vector changedcellsV; for(unsigned int ix = 0; ix < grid->getSizeInCellsX(); ix++) { for(unsigned int iy = 0; iy < grid->getSizeInCellsY(); iy++) { unsigned char oldCost = env_->GetMapCost(ix,iy); unsigned char newCost = costMapCostToSBPLCost(grid->getCost(ix,iy)); if(oldCost == newCost) continue; allCount++; //first case - off cell goes on if((oldCost != costMapCostToSBPLCost(robot_costmap_2d::LETHAL_OBSTACLE) && oldCost != costMapCostToSBPLCost(robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE)) && (newCost == costMapCostToSBPLCost(robot_costmap_2d::LETHAL_OBSTACLE) || newCost == costMapCostToSBPLCost(robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE))) { offOnCount++; } if((oldCost == costMapCostToSBPLCost(robot_costmap_2d::LETHAL_OBSTACLE) || oldCost == costMapCostToSBPLCost(robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE)) && (newCost != costMapCostToSBPLCost(robot_costmap_2d::LETHAL_OBSTACLE) && newCost != costMapCostToSBPLCost(robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE))) { onOffCount++; } env_->UpdateCost(ix, iy, costMapCostToSBPLCost(grid->getCost(ix,iy))); nav2dcell_t nav2dcell; nav2dcell.x = ix; nav2dcell.y = iy; changedcellsV.push_back(nav2dcell); } } try{ if(!changedcellsV.empty()){ StateChangeQuery* scq = new LatticeSCQ(env_, changedcellsV); planner_->costs_changed(*scq); delete scq; } if(allCount > force_scratch_limit_) planner_->force_planning_from_scratch(); } catch(SBPL_Exception *e){ robot::log_error("SBPL failed to update the costmap"); return false; } // ================================================================================================ // Chẩn đoán TRƯỚC khi search (2026-09-18). Env đã nhận cost mới ở vòng trên, nên soi ở đây mới // đúng lưới mà ARA* sắp dùng. Ba câu hỏi, trả lời xong mới chạy search: // 1. Goal đứng trên ô gì, footprint tại goal có hợp lệ không? -> không thì từ chối ngay. // 2. Start đứng trên ô gì? -> chỉ báo, không từ chối. // 3. Có đường 2D (điểm) từ start tới goal qua ô < inscribed? -> không thì từ chối ngay. // Từ chối sớm không đổi kết quả (ARA* cũng sẽ trả false) nhưng bỏ 6-14 s quét map + retry // heading, và log nói thẳng nguyên nhân thay vì "Solution not found". // ================================================================================================ const PoseAudit goal_audit = auditPose(grid, goal.pose.position.x, goal.pose.position.y, theta_goal); const PoseAudit start_audit = auditPose(grid, start.pose.position.x, start.pose.position.y, theta_start); const auto dump_windows = [&](const char* why) { if (debug_grid_window_ <= 0 || !goal_audit.in_map || !start_audit.in_map) { return; } robot::log_info("[sbpl_lattice_planner] grid dump (%s)", why); logGridWindow(grid, debug_grid_window_, goal_audit.mx, goal_audit.my, start_audit.mx, start_audit.my, goal_audit.mx, goal_audit.my, "GOAL"); logGridWindow(grid, debug_grid_window_, start_audit.mx, start_audit.my, start_audit.mx, start_audit.my, goal_audit.mx, goal_audit.my, "START"); }; // (1) Goal. Một action không bao giờ được KẾT THÚC trên ô >= cost_inscribed_thresh (253), và // footprint tại goal phải trong lưới + không đè lethal — hai điều kiện SBPL kiểm khi mở rộng // nhưng KHÔNG kiểm khi SetGoal. Goal vi phạm = không có successor nào trùng goal = chắc chắn fail // sau khi quét hết vùng nối với robot. const bool goal_cell_blocked = goal_audit.cost >= robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE && !(allow_unknown_ && goal_audit.cost == robot_costmap_2d::NO_INFORMATION); if (!goal_audit.in_map || goal_cell_blocked || !goal_audit.footprint_ok) { robot::log_error("[sbpl_lattice_planner] goal REJECTED at (%.3f, %.3f, yaw %.2f): cell (%u,%u) " "cost=%u %s, footprint %s — SBPL never ends an action on a cell >= 253 or with " "the footprint on lethal/map edge; the search would sweep the whole reachable " "map and fail anyway. Move the goal >= inscribed radius (%.2f m) away from " "walls/keepout, or check the map/zone layers.\n", goal.pose.position.x, goal.pose.position.y, theta_goal, goal_audit.mx, goal_audit.my, goal_audit.cost, costClassName(goal_audit.cost), goal_audit.footprint_ok ? "valid" : "INVALID", costmap_robot_->getLayeredCostmap()->getInscribedRadius()); dump_windows("goal rejected"); return false; } // (2) Start. Robot đang đứng trong tường là chuyện của recovery (clear costmap), planner chỉ nói. if (start_audit.cost >= robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE || !start_audit.footprint_ok) { robot::log_error("[sbpl_lattice_planner] start audit at (%.3f, %.3f, yaw %.2f%s): cell (%u,%u) " "cost=%u %s, footprint %s — robot is inside/next to lethal; expect few or no " "valid first actions.\n", start.pose.position.x, start.pose.position.y, theta_start, start_heading_overridden ? " (free heading)" : "", start_audit.mx, start_audit.my, start_audit.cost, costClassName(start_audit.cost), start_audit.footprint_ok ? "valid" : "INVALID"); } else if (debug_plan_) { robot::log_info("[sbpl_lattice_planner] audit: start cell (%u,%u) cost=%u %s | goal cell (%u,%u) " "cost=%u %s footprint valid | grid %u x %u @ %.3f m origin (%.2f, %.2f) | " "allow_unknown=%s", start_audit.mx, start_audit.my, start_audit.cost, costClassName(start_audit.cost), goal_audit.mx, goal_audit.my, goal_audit.cost, costClassName(goal_audit.cost), grid->getSizeInCellsX(), grid->getSizeInCellsY(), grid->getResolution(), grid->getOriginX(), grid->getOriginY(), allow_unknown_ ? "true" : "false"); } // (3) Nối 2D. Heuristic của SBPL là Dijkstra 2D từ goal trên ô < cost_inscribed_thresh — đúng tập // ô mà tâm robot được phép đi qua trong search 3D. Vậy h(start) = INF nghĩa là KHÔNG tồn tại // đường 3D; ARA* sẽ dừng sau 0 expansion, nhưng vẫn tốn khởi tạo + retry heading, và log chỉ // nói "Solution not found". Gọi trước để nói rõ, rồi từ chối. GetGoalHeuristic chia cho // nominalvel nên INF (1e9) có thể tràn int thành số ÂM — bắt cả hai dạng. int h_2d = 0; try{ env_->EnsureHeuristicsUpdated(forward_search_); h_2d = forward_search_ ? env_->GetGoalHeuristic(start_state_id) : env_->GetStartHeuristic(goal_state_id); } catch(SBPL_Exception *e){ robot::log_error("SBPL encountered a fatal exception while computing the 2D heuristic"); return false; } const bool h_2d_infinite = (h_2d < 0 || h_2d >= INFINITECOST); if (h_2d_infinite) { robot::log_error("[sbpl_lattice_planner] 2D reachability start->goal: h=INF — no point path " "through cells < 253 (allow_unknown=%s). Goal region is sealed off from the " "robot by lethal/inscribed cells%s. REJECTED without running the lattice search.\n", allow_unknown_ ? "true" : "false", allow_unknown_ ? "" : " or by unknown space (allow_unknown=false)"); dump_windows("2D unreachable"); return false; } if (debug_plan_) { // h tính bằng đơn vị cost SBPL (mm / nominalvel): chỉ dùng để so tương đối giữa các lượt. robot::log_info("[sbpl_lattice_planner] 2D reachability start->goal: h=%d (finite) — point path " "exists, running lattice search", h_2d); } //setting planner parameters robot::log_debug("allocated:%f, init eps:%f\n",allocated_time_,initial_epsilon_); planner_->set_initialsolution_eps(initial_epsilon_); planner_->set_search_mode(false); robot::log_debug("[sbpl_lattice_planner] run planner"); const robot::Time plan_started = robot::Time::now(); // NGÂN SÁCH CHUNG (2026-09-11): `allocated_time` là trần của CẢ lượt makePlan, không phải của // từng lượt replan nội bộ. Trước đây ba lượt (free heading → heading thật → căn lại heading) mỗi // lượt được cấp lại nguyên allocated_time, trần thật là 3x — 30 s với config 10 s, và khi // PlannerRunner còn giữ costmap mutex (global_costmap.snapshot_for_readers = false) thì map-update // thread đứng suốt chừng ấy. Lượt sau chỉ chạy khi còn >= kMinReplanBudget. constexpr double kMinReplanBudget = 0.5; // [s] dưới mức này một lượt ARA* không kịp ra gì const auto budget_left = [&]() { return allocated_time_ - (robot::Time::now() - plan_started).toSec(); }; vector solution_stateIDs; int solution_cost; // Khám nghiệm khi fail cần biết pha cuối chạy với ngân sách nào và bắt đầu lúc nào — "hết giờ" // hay "cạn" chỉ phân biệt được bằng elapsed/budget của ĐÚNG pha đó. const char* phase_name = start_heading_overridden ? "free_heading" : "actual_heading"; double phase_budget = allocated_time_; robot::Time phase_started = plan_started; try{ int ret = planner_->replan(allocated_time_, &solution_stateIDs, &solution_cost); if(preempt_.load(std::memory_order_relaxed)){ robot::log_info("[sbpl_lattice_planner] preempted after %.0f ms (first search)", (robot::Time::now() - plan_started).toSec() * 1000.0); return false; } if(!ret && start_heading_overridden && budget_left() >= kMinReplanBudget){ // Heading giả định có thể không khả thi (vd hướng tới goal đâm thẳng vào tường // ngay tại cell xuất phát) — thử lại MỘT lần với heading thật trước khi bỏ cuộc. robot::log_warning("[sbpl_lattice_planner] no solution with free start heading after %d " "expansions in %.0f ms, retrying with actual robot heading (%.2f s left)", planner_->get_n_expands(), (robot::Time::now() - plan_started).toSec() * 1000.0, budget_left()); int sid = env_->SetStart(start.pose.position.x - grid->getOriginX(), start.pose.position.y - grid->getOriginY(), theta_start_actual); if(sid >= 0 && planner_->set_start(sid) != 0){ phase_name = "actual_heading_retry"; phase_budget = budget_left(); phase_started = robot::Time::now(); ret = planner_->replan(phase_budget, &solution_stateIDs, &solution_cost); } if(preempt_.load(std::memory_order_relaxed)){ robot::log_info("[sbpl_lattice_planner] preempted after %.0f ms (heading retry)", (robot::Time::now() - plan_started).toSec() * 1000.0); return false; } } if(ret) { // eps THẬT đạt được, không phải eps đặt trong config. Cần thiết vì toàn bộ log nội bộ của // SBPL bị compile bỏ (`Test/sbpl/.../config.h:53 DEBUG 0` làm `SBPL_PRINTF` rỗng), nên đây // là đường DUY NHẤT biết ARA* dừng ở nấc nào. Không có nó thì mọi kết luận về // `allocated_time` chỉ là suy đoán từ thời gian đo được. // // Đọc thế nào: eps == initial_epsilon nghĩa là hết giờ ngay ở nấc đầu — nới `allocated_time` // hoặc hạ `initial_epsilon`. eps == 1.0 nghĩa là đã tới nghiệm tối ưu. expands= là số state // ARA* đã mở: so giữa hai lượt cùng goal để thấy map/cost đổi hay không. if (debug_plan_) { robot::log_info("[sbpl_lattice_planner] solved: eps=%.3f (init %.2f), cost=%d, %zu state(s), " "%.0f ms of %.2f s allowed, expands=%d, h_2d=%d, phase=%s", planner_->get_final_epsilon(), initial_epsilon_, solution_cost, solution_stateIDs.size(), (robot::Time::now() - plan_started).toSec() * 1000.0, allocated_time_, planner_->get_n_expands(), h_2d, phase_name); } } else{ // Dòng LỖI, không tắt được. Ba nguyên nhân phân biệt bằng elapsed của pha cuối: // EXHAUSTED: dừng trước khi hết ngân sách -> OPEN list cạn -> KHÔNG có đường 3D dù 2D có // (footprint/primitive không lọt khe, hoặc goal ở ô hợp lệ nhưng không có action // nào kết thúc đúng (x,y,theta) đó). Kèm h_2d hữu hạn ở trên = đúng ca này. // TIMEOUT: chạy sát ngân sách -> map lớn/eps=1.0/goal xa, nới allocated_time hoặc tăng // initial_epsilon. // (preempt đã return sớm ở trên, không tới đây.) const double phase_elapsed = (robot::Time::now() - phase_started).toSec(); const double total_elapsed = (robot::Time::now() - plan_started).toSec(); constexpr double kTimeoutFraction = 0.95; // sát trần ngần này coi là hết giờ const bool timed_out = phase_budget > 0.0 && phase_elapsed >= kTimeoutFraction * phase_budget; robot::log_error("[sbpl_lattice_planner] NO SOLUTION start=(%.3f,%.3f) goal=(%.3f,%.3f) " "dist=%.1f m | phase=%s reason=%s expands=%d phase_elapsed=%.0f ms of %.0f ms " "total=%.0f ms of %.0f ms eps=%.2f h_2d=%d allow_unknown=%s\n", start.pose.position.x, start.pose.position.y, goal.pose.position.x, goal.pose.position.y, std::hypot(goal.pose.position.x - start.pose.position.x, goal.pose.position.y - start.pose.position.y), phase_name, timed_out ? "TIMEOUT" : "EXHAUSTED", planner_->get_n_expands(), phase_elapsed * 1000.0, phase_budget * 1000.0, total_elapsed * 1000.0, allocated_time_ * 1000.0, planner_->get_final_epsilon(), h_2d, allow_unknown_ ? "true" : "false"); dump_windows("no solution"); return false; } } catch(SBPL_Exception *e){ robot::log_error("SBPL encountered a fatal exception while planning"); return false; } robot::log_debug("size of solution=%d", (int)solution_stateIDs.size()); vector sbpl_path; try{ env_->ConvertStateIDPathintoXYThetaPath(&solution_stateIDs, &sbpl_path); } catch(SBPL_Exception *e){ robot::log_error("SBPL encountered a fatal exception while reconstructing the path"); return false; } if (start_heading_overridden && sbpl_path.size() > 1) { // free_start_heading nhắm heading giả định thẳng tới goal; nếu hướng đó bị chặn, // path vẫn mở đầu bằng cung rẽ từ heading giả định sang hướng đi thật. Yêu cầu vận // hành là đoạn đầu path phải THẲNG (robot quay tại chỗ xong là bám thẳng), nên nếu // phát hiện đoạn đầu cong thì căn lại heading xuất phát theo hướng đi thật của path // rồi plan lại đúng MỘT lần (không lặp — lần hai đã xuất phát đúng hướng đi thật // nên primitive thẳng là lựa chọn rẻ nhất). constexpr double kStraightLeadCheckM = 0.5; // [m] cửa sổ kiểm tra độ thẳng đoạn đầu constexpr double kMaxLeadHeadingDevRad = 0.2; // [rad] ~ nửa bước góc lưới 16 hướng double lead_len = 0.0; double max_dev = 0.0; size_t iend = 1; for (; iend < sbpl_path.size() && lead_len < kStraightLeadCheckM; ++iend) { lead_len += std::hypot(sbpl_path[iend].x - sbpl_path[iend - 1].x, sbpl_path[iend].y - sbpl_path[iend - 1].y); max_dev = std::max(max_dev, std::fabs(std::remainder( sbpl_path[iend].theta - sbpl_path[0].theta, 2.0 * M_PI))); } if (max_dev > kMaxLeadHeadingDevRad) { // Tìm HƯỚNG ĐI THẬT của route: đoạn thẳng đầu tiên trên path (heading giữ nguyên // liên tục >= kStraightRunM). Với U-turn dài hơn cửa sổ 0.5m, mốc cố định sẽ rơi // vào giữa cung — phải quét qua hết phần cong. Đoạn thẳng mở đầu đi theo hướng // route tìm được, KHÔNG ép theo hướng tới goal (goal chỉ là seed cho lần plan đầu). constexpr double kStraightRunM = 0.3; // [m] độ dài tối thiểu để tính là đoạn thẳng constexpr double kScanLimitM = 3.0; // [m] giới hạn quét phần cong mở đầu double theta_realign = sbpl_path[iend - 1].theta; // fallback: heading sau cửa sổ đầu double scanned = 0.0; for (size_t i = 0; i + 1 < sbpl_path.size() && scanned < kScanLimitM; ++i) { double run = 0.0; bool straight = true; for (size_t j = i + 1; j < sbpl_path.size() && run < kStraightRunM; ++j) { run += std::hypot(sbpl_path[j].x - sbpl_path[j - 1].x, sbpl_path[j].y - sbpl_path[j - 1].y); if (std::fabs(std::remainder(sbpl_path[j].theta - sbpl_path[i].theta, 2.0 * M_PI)) > 1e-3) { straight = false; break; } } if (straight && run >= kStraightRunM) { theta_realign = sbpl_path[i].theta; break; } scanned += std::hypot(sbpl_path[i + 1].x - sbpl_path[i].x, sbpl_path[i + 1].y - sbpl_path[i].y); } if(preempt_.load(std::memory_order_relaxed)){ robot::log_info("[sbpl_lattice_planner] preempted after %.0f ms (before realign)", (robot::Time::now() - plan_started).toSec() * 1000.0); return false; } if(budget_left() < kMinReplanBudget){ robot::log_debug("[sbpl_lattice_planner] initial segment curved (dev %.2f rad) but only " "%.2f s of the budget left — keeping the first path", max_dev, budget_left()); } else{ robot::log_debug("[sbpl_lattice_planner] initial segment curved (dev %.2f rad), " "replanning with start heading realigned to %.2f (%.2f s left)", max_dev, theta_realign, budget_left()); try{ int sid = env_->SetStart(start.pose.position.x - grid->getOriginX(), start.pose.position.y - grid->getOriginY(), theta_realign); vector realigned_ids; int realigned_cost; if(sid >= 0 && planner_->set_start(sid) != 0 && planner_->replan(budget_left(), &realigned_ids, &realigned_cost)){ vector realigned_path; env_->ConvertStateIDPathintoXYThetaPath(&realigned_ids, &realigned_path); if(!realigned_path.empty()){ sbpl_path = realigned_path; } } if(preempt_.load(std::memory_order_relaxed)){ robot::log_info("[sbpl_lattice_planner] preempted after %.0f ms (realign)", (robot::Time::now() - plan_started).toSec() * 1000.0); return false; } } catch(SBPL_Exception *e){ // giữ path đầu tiên — cong nhưng vẫn hợp lệ, không được trả thất bại ở đây robot::log_warning("[sbpl_lattice_planner] realigned replan failed, keeping first path"); } } // budget_left() >= kMinReplanBudget } } // if the plan has zero points, add a single point to make move_base happy if( sbpl_path.size() == 0 ) { EnvNAVXYTHETALAT3Dpt_t s( start.pose.position.x - grid->getOriginX(), start.pose.position.y - grid->getOriginY(), theta_start); // sbpl_path.push_back(s); } robot::log_debug("Plan has %d points.\n", (int)sbpl_path.size()); robot::Time plan_time = robot::Time::now(); // if (publish_footprint_path_) // { // robot_visualization_msgs::Marker sbpl_plan_footprint; // getFootprintList(sbpl_path, costmap_robot_->getGlobalFrameID(), sbpl_plan_footprint); // sbpl_plan_footprint_pub_.publish(sbpl_plan_footprint); // } //create a message for the plan // nav_msgs::Path gui_path; // gui_path.poses.resize(sbpl_path.size()); // gui_path.header.frame_id = costmap_robot_->getGlobalFrameID(); // gui_path.header.stamp = plan_time; for(unsigned int i=0; igetGlobalFrameID(); pose.pose.position.x = sbpl_path[i].x + grid->getOriginX(); pose.pose.position.y = sbpl_path[i].y + grid->getOriginY(); pose.pose.position.z = start.pose.position.z; // tf2::Quaternion temp; // temp.setRPY(0,0,sbpl_path[i].theta); // pose.pose.orientation.x = temp.getX(); // pose.pose.orientation.y = temp.getY(); // pose.pose.orientation.z = temp.getZ(); // pose.pose.orientation.w = temp.getW(); pose.pose.orientation = data_convert::getQuaternion(sbpl_path[i].theta); plan.push_back(pose); // gui_path.poses[i] = plan[i]; } // plan_pub_.publish(gui_path); // publishStats(solution_cost, sbpl_path.size(), start, goal); // The search and realignment use one immutable snapshot. Refuse to hand off a path // for an older map or field when the provider changed while planning. const auto handoff_snapshot = costmap_robot_->getLayeredCostmap()->getDirectionFieldSnapshot(); const bool both_disabled = direction_snapshot.state == robot_costmap_2d::DirectionFieldState::kDisabled && handoff_snapshot.state == robot_costmap_2d::DirectionFieldState::kDisabled; if (!both_disabled && (direction_snapshot.state != handoff_snapshot.state || direction_snapshot.generation != handoff_snapshot.generation)) { plan.clear(); robot::log_warning("[sbpl_lattice_planner] direction field changed during planning " "(generation %llu -> %llu); discarding path", static_cast(direction_snapshot.generation), static_cast(handoff_snapshot.generation)); return false; } return true; } void SBPLLatticePlanner::getFootprintList(const std::vector& sbpl_path, const std::string& path_frame_id, robot_visualization_msgs::Marker& ma) { ma.header.frame_id = path_frame_id; ma.header.stamp = robot::Time(); ma.ns = "sbpl_robot_footprint"; ma.id = 0; ma.type = robot_visualization_msgs::Marker::LINE_LIST; ma.action = robot_visualization_msgs::Marker::ADD; ma.scale.x = 0.05; ma.color.a = 1.0; ma.color.r = 0.0; ma.color.g = 0.0; ma.color.b = 1.0; ma.pose.orientation.w = 1.0; for (unsigned int i = 0; i < sbpl_path.size(); i = i + visualizer_skip_poses_) { std::vector transformed_rfp; robot_geometry_msgs::Pose robot_pose; robot_pose.position.x = sbpl_path[i].x + costmap_robot_->getCostmap()->getOriginX(); robot_pose.position.y = sbpl_path[i].y + costmap_robot_->getCostmap()->getOriginY(); robot_pose.position.z = 0.0; robot_pose.orientation = data_convert::getQuaternion(sbpl_path[i].theta); transformFootprintToEdges(robot_pose, footprint_, transformed_rfp); for (auto & point : transformed_rfp) ma.points.push_back(point); } } void SBPLLatticePlanner::transformFootprintToEdges(const robot_geometry_msgs::Pose& robot_pose, const std::vector& footprint, std::vector& out_footprint) { out_footprint.resize(2 * footprint.size()); double yaw = data_convert::getYaw(robot_pose.orientation); for (unsigned int i = 0; i < footprint.size(); i++) { out_footprint[2 * i].x = robot_pose.position.x + cos(yaw) * footprint[i].x - sin(yaw) * footprint[i].y; out_footprint[2 * i].y = robot_pose.position.y + sin(yaw) * footprint[i].x + cos(yaw) * footprint[i].y; if (i == 0) { out_footprint.back().x = out_footprint[i].x; out_footprint.back().y = out_footprint[i].y; } else { out_footprint[2 * i - 1].x = out_footprint[2 * i].x; out_footprint[2 * i - 1].y = out_footprint[2 * i].y; } } } // Export factory function robot_nav_core::BaseGlobalPlanner::Ptr SBPLLatticePlanner::create() { return std::make_shared(); } // Cầu capability cho bên NGOÀI .so: caller chỉ giữ BaseGlobalPlanner* (nạp qua alias factory), // còn dynamic_cast xuống lớp cụ thể chạy Ở TRONG .so này — typeinfo nhất quán, không phụ thuộc // RTLD_LOCAL/GLOBAL của boost::dll. Planner không phải instance của lớp này thì bỏ qua kèm log. void setExternalGridOn(robot_nav_core::BaseGlobalPlanner* planner, const robot_costmap_2d::Costmap2D* grid) { SBPLLatticePlanner* self = dynamic_cast(planner); if (self != NULL) { self->setExternalGrid(grid); } else { robot::log_error("[sbpl_lattice_planner] setExternalGridOn: planner is not an " "SBPLLatticePlanner instance; external grid ignored."); } } void SBPLLatticePlanner::preempt() { // Từ thread khác: một store, không lock. ARA* đọc cờ này qua set_abort_flag (nếu libsbpl hỗ trợ); // makePlan đọc nó giữa các lượt replan nội bộ. Không log ở đây — chạy trên control thread. preempt_.store(true, std::memory_order_relaxed); } }; // Alias cho Boost.DLL (nếu muốn dùng boost::dll::import_alias) BOOST_DLL_ALIAS(sbpl_lattice_planner::SBPLLatticePlanner::create, SBPLLatticePlanner) // Capability lưới ngoài: tra theo tên "ExternalGrid" (xem sbpl_recovery). BOOST_DLL_ALIAS(sbpl_lattice_planner::setExternalGridOn, SBPLLatticePlannerExternalGrid)