/********************************************************************* * * Software License Agreement (BSD License) * * move_base2 — cài đặt grid_analysis (xem header). * * Author: DuongTD *********************************************************************/ #include #include #include #include #include #include namespace move_base2 { namespace { constexpr float kInf = std::numeric_limits::infinity(); /// Giá trị "vô cùng" hữu hạn cho EDT 1-D: bình phương khoảng cách theo ô tối đa là 160^2 = 25 600, /// 1e6 vẫn biểu diễn chính xác trong float và không sinh NaN khi trừ nhau như +inf. constexpr float kFarSq = 1.0e6f; /// [m] Bỏ quãng đầu quỹ đạo khi kéo footprint — cùng lý do với plan_inspector::kSkipOwnFootprintDist. constexpr double kSkipOwnFootprintDist = 0.05; /// Lượng tử hoá khoảng cách trong khoá heap: 0.1 mm, đủ cho 20 m trong 32 bit. constexpr double kHeapQuant = 10000.0; double yawOf(const robot_geometry_msgs::PoseStamped& pose) { const auto& q = pose.pose.orientation; return std::atan2(2.0 * (q.w * q.z + q.x * q.y), 1.0 - 2.0 * (q.y * q.y + q.z * q.z)); } /** * @brief Biến đổi khoảng cách bình phương 1-D (Felzenszwalb & Huttenlocher 2004) — parabola lower envelope. * @param f n giá trị vào (0 tại vật cản, kFarSq nơi khác; hoặc kết quả lượt trước). * @param d n giá trị ra. * @param v,z bộ đệm >= n và >= n+1. */ void distanceTransform1D(const float* f, int n, float* d, int* v, float* z) { int k = 0; v[0] = 0; z[0] = -kInf; z[1] = kInf; for (int q = 1; q < n; ++q) { float s = ((f[q] + static_cast(q) * q) - (f[v[k]] + static_cast(v[k]) * v[k])) / (2.0f * q - 2.0f * v[k]); while (s <= z[k]) { --k; s = ((f[q] + static_cast(q) * q) - (f[v[k]] + static_cast(v[k]) * v[k])) / (2.0f * q - 2.0f * v[k]); } ++k; v[k] = q; z[k] = s; z[k + 1] = kInf; } k = 0; for (int q = 0; q < n; ++q) { while (z[k + 1] < static_cast(q)) { ++k; } const float dq = static_cast(q - v[k]); d[q] = dq * dq + f[v[k]]; } } std::uint64_t heapKey(double dist, std::uint32_t idx) { const std::uint64_t q = static_cast(std::llround(dist * kHeapQuant)); return (q << 32) | idx; } /// Dựng chu vi hình chữ nhật thân (frame thân) với bước @p spacing; mỗi điểm mang id cạnh. void buildPerimeter(double front, double rear, double side, double spacing, std::vector& out) { out.clear(); const double x0[4] = { -rear, front, front, -rear }; const double y0[4] = { -side, -side, side, side }; const double x1[4] = { front, front, -rear, -rear }; const double y1[4] = { -side, side, side, -side }; for (int e = 0; e < 4; ++e) { const double len = std::hypot(x1[e] - x0[e], y1[e] - y0[e]); const int n = std::max(1, static_cast(std::ceil(len / spacing))); for (int i = 0; i <= n; ++i) { const double t = static_cast(i) / n; out.push_back(x0[e] + (x1[e] - x0[e]) * t); out.push_back(y0[e] + (y1[e] - y0[e]) * t); out.push_back(static_cast(e)); } } } } // namespace // ------------------------------------------------------------------------------------------ scratch bool GridScratch::ensure(const robot_costmap_2d::Costmap2D& grid) { const unsigned int w = grid.getSizeInCellsX(); const unsigned int h = grid.getSizeInCellsY(); resolution = grid.getResolution(); origin_x = grid.getOriginX(); origin_y = grid.getOriginY(); if (w == 0 || h == 0 || !(resolution > 0.0)) { return false; } if (w != width || h != height) { width = w; height = h; const std::size_t n = static_cast(w) * h; edt.assign(n, kInf); free.assign(n, 0); geo.assign(n, kInf); tmp_.assign(n, kFarSq); const std::size_t m = std::max(w, h) + 2; f_.assign(m, 0.0f); d_.assign(m, 0.0f); v_.assign(m, 0); z_.assign(m + 1, 0.0f); heap_.clear(); heap_.reserve(n * 2); baseline.reserve(1024); perim_.reserve(3 * 512); } return true; } bool GridScratch::toCell(double x, double y, unsigned int& mx, unsigned int& my) const { if (width == 0 || height == 0 || !(resolution > 0.0)) { return false; } const double fx = std::floor((x - origin_x) / resolution); const double fy = std::floor((y - origin_y) / resolution); if (fx < 0.0 || fy < 0.0 || fx >= static_cast(width) || fy >= static_cast(height)) { return false; } mx = static_cast(fx); my = static_cast(fy); return true; } void GridScratch::cellCenter(unsigned int mx, unsigned int my, double& x, double& y) const { x = origin_x + (mx + 0.5) * resolution; y = origin_y + (my + 0.5) * resolution; } // --------------------------------------------------------------------------------------------- EDT bool analyzeGrid(const robot_costmap_2d::Costmap2D& grid, unsigned char lethal_threshold, double free_radius, GridScratch& s) { if (!s.ensure(grid)) { return false; } const unsigned char* cost = grid.getCharMap(); const std::size_t n = static_cast(s.width) * s.height; bool any_lethal = false; for (std::size_t i = 0; i < n; ++i) { // NO_INFORMATION (255) không phải vật cản — cùng quy ước với checkPlan và SBPL. const bool lethal = cost[i] >= lethal_threshold && cost[i] != robot_costmap_2d::NO_INFORMATION; s.tmp_[i] = lethal ? 0.0f : kFarSq; any_lethal |= lethal; } s.free_radius = free_radius; if (!any_lethal) { std::fill(s.edt.begin(), s.edt.end(), kInf); std::fill(s.free.begin(), s.free.end(), static_cast(1)); return true; } // Lượt 1: theo hàng (trục x). const int w = static_cast(s.width); const int h = static_cast(s.height); for (int y = 0; y < h; ++y) { float* row = &s.tmp_[static_cast(y) * s.width]; distanceTransform1D(row, w, s.d_.data(), s.v_.data(), s.z_.data()); std::copy(s.d_.begin(), s.d_.begin() + w, row); } // Lượt 2: theo cột (trục y). for (int x = 0; x < w; ++x) { for (int y = 0; y < h; ++y) { s.f_[y] = s.tmp_[static_cast(y) * s.width + x]; } distanceTransform1D(s.f_.data(), h, s.d_.data(), s.v_.data(), s.z_.data()); for (int y = 0; y < h; ++y) { const std::size_t i = static_cast(y) * s.width + x; const float dist = std::sqrt(s.d_[y]) * static_cast(s.resolution); s.edt[i] = dist; s.free[i] = dist >= static_cast(free_radius) ? 1 : 0; } } return true; } double distanceAt(const GridScratch& s, double x, double y) { unsigned int mx = 0; unsigned int my = 0; if (!s.toCell(x, y, mx, my) || s.edt.empty()) { return std::numeric_limits::quiet_NaN(); } return s.edt[s.index(mx, my)]; } // ---------------------------------------------------------------------------------------- geodesic bool computeGeodesic(unsigned int tx, unsigned int ty, GridScratch& s, std::size_t* visited, std::size_t stop_index) { if (visited != nullptr) { *visited = 0; } if (s.width == 0 || tx >= s.width || ty >= s.height || s.free.empty()) { return false; } std::fill(s.geo.begin(), s.geo.end(), kInf); const std::size_t t = s.index(tx, ty); if (!s.free[t]) { return false; } const float res = static_cast(s.resolution); const float diag = res * 1.41421356f; const int w = static_cast(s.width); const int h = static_cast(s.height); s.heap_.clear(); s.geo[t] = 0.0f; s.heap_.push_back(heapKey(0.0, static_cast(t))); std::greater cmp; // 8 láng giềng: (dx, dy, chéo?) static const int kDx[8] = { 1, -1, 0, 0, 1, 1, -1, -1 }; static const int kDy[8] = { 0, 0, 1, -1, 1, -1, 1, -1 }; std::size_t popped = 0; while (!s.heap_.empty()) { std::pop_heap(s.heap_.begin(), s.heap_.end(), cmp); const std::uint64_t key = s.heap_.back(); s.heap_.pop_back(); const std::uint32_t idx = static_cast(key & 0xffffffffu); const double qd = static_cast(key >> 32) / kHeapQuant; if (qd > s.geo[idx] + 0.5 / kHeapQuant) { continue; // mục cũ, đã có đường ngắn hơn } ++popped; if (idx == stop_index) { break; // ô cần hỏi đã có khoảng cách đúng (Dijkstra: pop = chốt); phần còn lại không cần } const int x = static_cast(idx % s.width); const int y = static_cast(idx / s.width); const float base = s.geo[idx]; for (int k = 0; k < 8; ++k) { const int nx = x + kDx[k]; const int ny = y + kDy[k]; if (nx < 0 || ny < 0 || nx >= w || ny >= h) { continue; } const std::size_t ni = s.index(static_cast(nx), static_cast(ny)); if (!s.free[ni]) { continue; } float step = res; if (k >= 4) { // Cấm cắt góc: hai ô trực giao trung gian phải free, không thì đường chui qua khe chéo. const std::size_t a = s.index(static_cast(nx), static_cast(y)); const std::size_t b = s.index(static_cast(x), static_cast(ny)); if (!s.free[a] || !s.free[b]) { continue; } step = diag; } const float nd = base + step; if (nd < s.geo[ni]) { s.geo[ni] = nd; s.heap_.push_back(heapKey(nd, static_cast(ni))); std::push_heap(s.heap_.begin(), s.heap_.end(), cmp); } } } if (visited != nullptr) { *visited = popped; } return true; } bool nearestFreeCell(const GridScratch& s, unsigned int mx, unsigned int my, double max_dist, unsigned int& fx, unsigned int& fy) { if (s.free.empty() || mx >= s.width || my >= s.height) { return false; } if (s.free[s.index(mx, my)]) { fx = mx; fy = my; return true; } const int r = static_cast(std::ceil(max_dist / s.resolution)); long best = -1; for (int dy = -r; dy <= r; ++dy) { for (int dx = -r; dx <= r; ++dx) { const int x = static_cast(mx) + dx; const int y = static_cast(my) + dy; if (!s.inBounds(x, y)) { continue; } const long d2 = static_cast(dx) * dx + static_cast(dy) * dy; if (s.free[s.index(static_cast(x), static_cast(y))] && (best < 0 || d2 < best)) { best = d2; fx = static_cast(x); fy = static_cast(y); } } } return best >= 0 && std::sqrt(static_cast(best)) * s.resolution <= max_dist; } // ------------------------------------------------------------------------------------ body clearance double bodyClearance(const GridScratch& s, double x, double y, double yaw, double front, double rear, double side) { if (s.edt.empty()) { return std::numeric_limits::quiet_NaN(); } const double spacing = 0.5 * s.resolution; const double c = std::cos(yaw); const double sn = std::sin(yaw); double best = std::numeric_limits::infinity(); bool any = false; const double x0[4] = { -rear, front, front, -rear }; const double y0[4] = { -side, -side, side, side }; const double x1[4] = { front, front, -rear, -rear }; const double y1[4] = { -side, side, side, -side }; for (int e = 0; e < 4; ++e) { const double len = std::hypot(x1[e] - x0[e], y1[e] - y0[e]); const int n = std::max(1, static_cast(std::ceil(len / spacing))); for (int i = 0; i <= n; ++i) { const double t = static_cast(i) / n; const double bx = x0[e] + (x1[e] - x0[e]) * t; const double by = y0[e] + (y1[e] - y0[e]) * t; const double wx = x + bx * c - by * sn; const double wy = y + bx * sn + by * c; const double d = distanceAt(s, wx, wy); if (!std::isnan(d)) { any = true; best = std::min(best, d); } } } return any ? best : std::numeric_limits::quiet_NaN(); } // ------------------------------------------------------------------------------------- cost to go CostToGoResult costToGo(const std::vector& plan, std::size_t from_index, double robot_x, double robot_y, const CostToGoParams& params, const PlanarTransform& plan_to_grid, GridScratch& s) { CostToGoResult r; if (plan.size() < 2 || from_index >= plan.size() || s.free.empty()) { return r; } // Độ dài cộng dồn từ from_index tới cuối, và pose plan cuối cùng còn trong lưới. // arc_at[i] chỉ cần cho các pose từ from_index; dùng hai con trỏ chạy để không cấp phát. double total = 0.0; { double px = 0.0; double py = 0.0; plan_to_grid.apply(plan[from_index].pose.position.x, plan[from_index].pose.position.y, px, py); for (std::size_t i = from_index + 1; i < plan.size(); ++i) { double qx = 0.0; double qy = 0.0; plan_to_grid.apply(plan[i].pose.position.x, plan[i].pose.position.y, qx, qy); total += std::hypot(qx - px, qy - py); px = qx; py = qy; } } std::size_t ti = from_index; double arc_ti = 0.0; // độ dài từ from_index tới ti bool found = false; bool ahead = false; { double px = 0.0; double py = 0.0; double walk = 0.0; for (std::size_t i = from_index; i < plan.size(); ++i) { double qx = 0.0; double qy = 0.0; plan_to_grid.apply(plan[i].pose.position.x, plan[i].pose.position.y, qx, qy); if (i > from_index) { walk += std::hypot(qx - px, qy - py); } px = qx; py = qy; unsigned int mx = 0; unsigned int my = 0; if (!s.toCell(qx, qy, mx, my)) { break; // cửa sổ lăn theo robot: ra ngoài một lần là phần còn lại cũng ngoài } ti = i; arc_ti = walk; found = true; if (params.exit_ahead > 0.0 && walk >= params.exit_ahead) { ahead = true; break; // T ở quãng cố định dọc plan: chỉ tiến theo index, không lùi khi cửa sổ trôi } } } if (!found) { return r; // pose plan gần robot nhất cũng ngoài lưới: robot xa plan, việc của off_path } r.target = (ti + 1 == plan.size()) ? CostToGoResult::Target::kGoal : ahead ? CostToGoResult::Target::kAhead : CostToGoResult::Target::kExit; // T phải là ô free; không thì lùi dọc plan tối đa target_backoff. unsigned int tx = 0; unsigned int ty = 0; { double qx = 0.0; double qy = 0.0; plan_to_grid.apply(plan[ti].pose.position.x, plan[ti].pose.position.y, qx, qy); s.toCell(qx, qy, tx, ty); } if (!s.free[s.index(tx, ty)]) { bool backed = false; double back = 0.0; double px = 0.0; double py = 0.0; plan_to_grid.apply(plan[ti].pose.position.x, plan[ti].pose.position.y, px, py); for (std::size_t j = ti; j > from_index; --j) { double qx = 0.0; double qy = 0.0; plan_to_grid.apply(plan[j - 1].pose.position.x, plan[j - 1].pose.position.y, qx, qy); back += std::hypot(qx - px, qy - py); px = qx; py = qy; if (back > params.target_backoff) { break; } unsigned int mx = 0; unsigned int my = 0; if (s.toCell(qx, qy, mx, my) && s.free[s.index(mx, my)]) { ti = j - 1; arc_ti -= back; tx = mx; ty = my; backed = true; break; } } if (!backed) { r.conclusive = true; r.reachable = false; r.target = CostToGoResult::Target::kBlockedExit; r.target_index = ti; r.arc_rest = total - arc_ti; return r; } r.target = CostToGoResult::Target::kBackedOff; } r.target_index = ti; r.arc_rest = std::max(0.0, total - arc_ti); // Ô robot; đang ôm sát vật thì snap sang ô free gần nhất. unsigned int rx = 0; unsigned int ry = 0; if (!s.toCell(robot_x, robot_y, rx, ry)) { return r; } if (!s.free[s.index(rx, ry)]) { r.robot_in_ring = true; unsigned int fx = 0; unsigned int fy = 0; if (!nearestFreeCell(s, rx, ry, params.robot_snap, fx, fy)) { return r; // thân đã nằm sâu trong dải cấm: không kết luận } rx = fx; ry = fy; } std::size_t visited = 0; computeGeodesic(tx, ty, s, &visited, s.index(rx, ry)); // dừng sớm tại ô robot r.cells_visited = visited; r.conclusive = true; const float g = s.geo[s.index(rx, ry)]; r.reachable = std::isfinite(g); r.geo_to_exit = g; r.cost_to_go = r.reachable ? static_cast(g) + r.arc_rest : std::numeric_limits::infinity(); return r; } // ---------------------------------------------------------------------------------------- corridor CorridorResult scanCorridor(const std::vector& plan, std::size_t from_index, const CorridorParams& params, const PlanarTransform& plan_to_grid, const GridScratch& s) { CorridorResult r; r.plan_clear_ahead = params.horizon; if (plan.size() < 2 || from_index >= plan.size() || s.edt.empty()) { return r; } const double need = params.body_width + 2.0 * params.margin; double walk = 0.0; double px = 0.0; double py = 0.0; bool clear_set = false; for (std::size_t i = from_index; i < plan.size(); ++i) { double qx = 0.0; double qy = 0.0; plan_to_grid.apply(plan[i].pose.position.x, plan[i].pose.position.y, qx, qy); if (i > from_index) { walk += std::hypot(qx - px, qy - py); } const double prev_x = px; const double prev_y = py; px = qx; py = qy; if (walk > params.horizon) { break; } unsigned int mx = 0; unsigned int my = 0; if (!s.toCell(qx, qy, mx, my)) { break; } ++r.scanned; if (!clear_set && s.edt[s.index(mx, my)] < static_cast(s.free_radius)) { r.plan_clear_ahead = walk; clear_set = true; } // Hướng tiếp tuyến: tới pose kế, hoặc từ pose trước nếu là pose cuối. double tx = 0.0; double ty = 0.0; if (i + 1 < plan.size()) { double nx = 0.0; double ny = 0.0; plan_to_grid.apply(plan[i + 1].pose.position.x, plan[i + 1].pose.position.y, nx, ny); tx = nx - qx; ty = ny - qy; } else if (i > from_index) { tx = qx - prev_x; ty = qy - prev_y; } const double tn = std::hypot(tx, ty); if (tn < 1e-6) { continue; } const double nx = -ty / tn; const double ny = tx / tn; double width = 0.0; for (double sgn = 1.0; sgn >= -1.0; sgn -= 2.0) { double d = 0.0; while (d < params.side_cap) { d += s.resolution; unsigned int cx = 0; unsigned int cy = 0; if (!s.toCell(qx + sgn * nx * d, qy + sgn * ny * d, cx, cy)) { break; } if (s.edt[s.index(cx, cy)] <= 0.0f) { break; // ô lethal } } width += std::min(d, params.side_cap); } r.min_width = std::min(r.min_width, width); if (!std::isfinite(r.block_dist) && width < need) { r.block_dist = walk; } } return r; } // ------------------------------------------------------------------------------------------- sweep SweepResult sweepTrajectory(const std::vector& trajectory, double robot_x, double robot_y, double robot_yaw, double start_tol, const SweepParams& params, const robot_costmap_2d::Costmap2D& grid, GridScratch& s) { SweepResult r; if (trajectory.size() < 2 || !s.ensure(grid)) { return r; } if (std::hypot(trajectory.front().pose.position.x - robot_x, trajectory.front().pose.position.y - robot_y) > start_tol) { return r; // quỹ đạo không bắt đầu ở robot: không phải chuyển động sắp xảy ra } const unsigned char* cost = grid.getCharMap(); const double front = params.front + params.padding; const double rear = params.rear + params.padding; const double side = params.side + params.padding; auto lethal_at = [&](unsigned int mx, unsigned int my) { const unsigned char c = cost[s.index(mx, my)]; return c >= params.lethal_threshold && c != robot_costmap_2d::NO_INFORMATION; }; // Baseline: ô lethal đang nằm dưới thân đệm tại pose hiện tại (duyệt diện tích, như checkMotion). s.baseline.clear(); if (params.exclude_baseline) { const double c = std::cos(robot_yaw); const double sn = std::sin(robot_yaw); const double cx[4] = { front, front, -rear, -rear }; const double cy[4] = { side, -side, side, -side }; double min_x = std::numeric_limits::max(); double min_y = min_x; double max_x = std::numeric_limits::lowest(); double max_y = max_x; for (int i = 0; i < 4; ++i) { const double wx = robot_x + cx[i] * c - cy[i] * sn; const double wy = robot_y + cx[i] * sn + cy[i] * c; min_x = std::min(min_x, wx); max_x = std::max(max_x, wx); min_y = std::min(min_y, wy); max_y = std::max(max_y, wy); } int mx0 = 0; int my0 = 0; int mx1 = 0; int my1 = 0; grid.worldToMapEnforceBounds(min_x, min_y, mx0, my0); grid.worldToMapEnforceBounds(max_x, max_y, mx1, my1); const double slack = 0.5 * s.resolution; for (int my = my0; my <= my1; ++my) { for (int mx = mx0; mx <= mx1; ++mx) { if (!lethal_at(static_cast(mx), static_cast(my))) { continue; } double wx = 0.0; double wy = 0.0; s.cellCenter(static_cast(mx), static_cast(my), wx, wy); const double dx = wx - robot_x; const double dy = wy - robot_y; const double bx = dx * c + dy * sn; const double by = -dx * sn + dy * c; if (bx < -rear - slack || bx > front + slack || std::fabs(by) > side + slack) { continue; } s.baseline.push_back(static_cast(s.index(static_cast(mx), static_cast(my)))); } } std::sort(s.baseline.begin(), s.baseline.end()); } r.baseline_cells = static_cast(s.baseline.size()); buildPerimeter(front, rear, side, 0.5 * s.resolution, s.perim_); const std::size_t npts = s.perim_.size() / 3; auto hit_at = [&](double px, double py, double yaw, int& edge) { const double c = std::cos(yaw); const double sn = std::sin(yaw); for (std::size_t k = 0; k < npts; ++k) { const double bx = s.perim_[3 * k]; const double by = s.perim_[3 * k + 1]; const double wx = px + bx * c - by * sn; const double wy = py + bx * sn + by * c; unsigned int mx = 0; unsigned int my = 0; if (!s.toCell(wx, wy, mx, my) || !lethal_at(mx, my)) { continue; } const std::uint32_t idx = static_cast(s.index(mx, my)); if (!s.baseline.empty() && std::binary_search(s.baseline.begin(), s.baseline.end(), idx)) { continue; } edge = static_cast(s.perim_[3 * k + 2]); return true; } return false; }; double walk = 0.0; for (std::size_t i = 1; i < trajectory.size(); ++i) { const double ax = trajectory[i - 1].pose.position.x; const double ay = trajectory[i - 1].pose.position.y; const double bx = trajectory[i].pose.position.x; const double by = trajectory[i].pose.position.y; const double seg = std::hypot(bx - ax, by - ay); const double yaw = yawOf(trajectory[i]); // Chèn mẫu để bước dọc quỹ đạo không quá một ô: tường mỏng một ô không lọt giữa hai mẫu. const int nsub = std::max(1, static_cast(std::ceil(seg / s.resolution))); for (int k = 1; k <= nsub; ++k) { const double t = static_cast(k) / nsub; const double px = ax + (bx - ax) * t; const double py = ay + (by - ay) * t; const double w = walk + seg * t; if (w > params.lookahead) { r.conclusive = true; return r; } if (w < kSkipOwnFootprintDist) { continue; } ++r.scanned; int edge = -1; if (hit_at(px, py, yaw, edge)) { r.conclusive = true; r.blocked = true; r.distance = w; r.sample = i; r.hit_edge = edge; return r; } } walk += seg; } r.conclusive = r.scanned > 0; return r; } } // namespace move_base2