diff --git a/CMakeLists.txt b/CMakeLists.txt index 2904bd4..8adc7e4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -32,6 +32,7 @@ add_library(lane_route_core SHARED src/lattice_cspace.cpp src/lattice_heuristic.cpp src/lattice_search.cpp + src/lattice_smoother.cpp src/lattice_tier.cpp src/path_verifier.cpp src/route_graph_path.cpp diff --git a/include/lane_route_core/grid_checks.h b/include/lane_route_core/grid_checks.h index b16fb41..f95947d 100644 --- a/include/lane_route_core/grid_checks.h +++ b/include/lane_route_core/grid_checks.h @@ -42,6 +42,8 @@ bool endpointOk(const Path& path, const Pose2& start, const Pose2& goal); /** @brief Reason string when an in-place turn at a path end hits something, otherwise null. */ const char* blockedEndpointTurn(const Path& path, const GridRef& grid, double half_x, double half_y); +const char* blockedEndpointTurn(const Path& path, const GridRef& grid, double half_x, double half_y, + const std::atomic* cancel, const std::chrono::steady_clock::time_point* deadline); /** @brief True only when start and goal lie in different 8-connected components of free cells: no centre path exists. */ bool enclosedByObstacles(const GridRef& grid, const Point2& start, const Point2& goal, diff --git a/include/lane_route_core/route_planner.h b/include/lane_route_core/route_planner.h index a273ea8..8dec60c 100644 --- a/include/lane_route_core/route_planner.h +++ b/include/lane_route_core/route_planner.h @@ -63,6 +63,17 @@ struct PlanInfo double lattice_field_ms = 0.0; ///< [ms] Field construction across rungs. double lattice_search_ms = 0.0; ///< [ms] Search excluding final candidate verification. double lattice_verify_ms = 0.0; ///< [ms] Final candidate checks, included in lattice_ms. + double lattice_smooth_ms = 0.0; ///< [ms] Smoothing including verification. + uint64_t lattice_smooth_checks = 0; ///< Clearance probes, C-space pose checks and verification sample estimates. + int lattice_smoothed = 0; ///< 0: raw, 1: S3, 2: S3 plus clothoid. + uint64_t curvature_sign_changes = 0; ///< Changes of nonzero curvature sign, ignoring end spins. + double path_length_m = 0.0; ///< [m] Translational length of the returned path. + double straight_share = 0.0; ///< Fraction of path length with curvature magnitude below 0.001 1/m. + uint64_t lattice_smooth_connectors_tried = 0; ///< Dubins words actually checked. + uint64_t lattice_smooth_connectors_ok = 0; ///< Endpoint-matching connectors accepted by C-space. + uint64_t lattice_smooth_candidates = 0; ///< Whole-path verification attempts. + uint64_t lattice_smooth_rejects_verify = 0; ///< Whole paths rejected by verification, excluding interruption. + std::string lattice_smooth_stop; ///< accepted, no_route, verify_failed, budget (checks/states/memory), or deadline; empty when not run. }; /** @brief Outcome of a request. */ diff --git a/include/lane_route_core/types.h b/include/lane_route_core/types.h index 9599540..0d3a6d1 100644 --- a/include/lane_route_core/types.h +++ b/include/lane_route_core/types.h @@ -144,6 +144,8 @@ struct PlannerConfig double fallback_time_limit_s = 3.0; ///< [s] Shared across all lattice rungs and later smoothing. double lattice_end_relax_radius_m = 1.0; ///< [m] Within this distance of start or goal the C-space gap is that end pose's own gap minus 1 mm (capped at footprint_min_gap_m); the final gap check still applies. int64_t lattice_max_memory_mb = 512; ///< [MiB] Cap on tracked lattice allocations; see R1_design.md. + bool lattice_smooth_enabled = true; ///< Smooth a verified lattice path within the fallback deadline. + int64_t lattice_smooth_max_checks = 450000; ///< Maximum counted smoothing pose checks per request. /** @return Empty when valid, otherwise a description of the first bad value. */ std::string validate() const; diff --git a/src/grid_checks.cpp b/src/grid_checks.cpp index 0c9306e..96df84e 100644 --- a/src/grid_checks.cpp +++ b/src/grid_checks.cpp @@ -122,7 +122,7 @@ std::string PlannerConfig::validate() const lattice_field_cell_factor < 0 || lattice_field_max_cells < 1 || lattice_field_max_cells > std::numeric_limits::max() || !positive(fallback_time_limit_s) || fallback_time_limit_s > 86400.0 || !not_negative(lattice_end_relax_radius_m) || - lattice_max_memory_mb < 1 || lattice_max_memory_mb > 1048576)) + lattice_max_memory_mb < 1 || lattice_max_memory_mb > 1048576 || lattice_smooth_max_checks < 0)) error << "invalid lattice analytic, time or memory limits"; return error.str(); } @@ -309,18 +309,29 @@ bool endpointOk(const Path& path, const Pose2& start, const Pose2& goal) const char* blockedEndpointTurn(const Path& path, const GridRef& grid, double half_x, double half_y) { + return blockedEndpointTurn(path, grid, half_x, half_y, nullptr, nullptr); +} + +const char* blockedEndpointTurn(const Path& path, const GridRef& grid, double half_x, double half_y, + const std::atomic* cancel, const std::chrono::steady_clock::time_point* deadline) +{ + const auto expired = [&]() { + return (cancel && cancel->load(std::memory_order_relaxed)) || + (deadline && std::chrono::steady_clock::now() >= *deadline); + }; const auto turn_hits = [&](const PathPoint& a, const PathPoint& b) { const double delta = wrapAngle(b.yaw - a.yaw); if (std::abs(delta) < 1e-12) return false; const int samples = std::max(1, static_cast(std::ceil(std::abs(delta) / 0.03))); for (int j = 0; j <= samples; ++j) - if (footprintCollides(grid, a.x, a.y, a.yaw + delta * j / samples, half_x, half_y)) + if (expired() || footprintCollides(grid, a.x, a.y, a.yaw + delta * j / samples, half_x, half_y)) return true; return false; }; for (std::size_t i = 0; i + 1 < path.size(); ++i) { + if (expired()) return "cancelled"; if (std::hypot(path[i + 1].x - path[i].x, path[i + 1].y - path[i].y) > 1e-7) break; if (turn_hits(path[i], path[i + 1])) @@ -328,6 +339,7 @@ const char* blockedEndpointTurn(const Path& path, const GridRef& grid, double ha } for (std::size_t i = path.size(); i-- > 1;) { + if (expired()) return "cancelled"; if (std::hypot(path[i].x - path[i - 1].x, path[i].y - path[i - 1].y) > 1e-7) break; if (turn_hits(path[i - 1], path[i])) diff --git a/src/lattice_cspace.cpp b/src/lattice_cspace.cpp index 5c64f90..5e49075 100644 --- a/src/lattice_cspace.cpp +++ b/src/lattice_cspace.cpp @@ -105,7 +105,8 @@ uint32_t LatticeCSpace::blockedCount(int32_t x0, int32_t y0, int32_t x1, int32_t bool LatticeCSpace::poseFree(double x, double y, double yaw, double sweep_margin, double centre_sweep) { if (context_.expired()) return false; - ++context_.info.lattice_pose_checks; + if (context_.smooth_checks) ++*context_.smooth_checks; + else ++context_.info.lattice_pose_checks; const GridRef& g = context_.grid; const PlannerConfig& c = context_.config; const double fx = std::floor((x - g.origin_x) / g.resolution); diff --git a/src/lattice_internal.h b/src/lattice_internal.h index c8bf0cb..75a1cef 100644 --- a/src/lattice_internal.h +++ b/src/lattice_internal.h @@ -1,6 +1,7 @@ #ifndef LANE_ROUTE_CORE_LATTICE_INTERNAL_H_ #define LANE_ROUTE_CORE_LATTICE_INTERNAL_H_ +#include #include #include #include @@ -53,9 +54,11 @@ struct LatticeContext TimePoint deadline; PlanInfo& info; LatticeMemory& memory; + uint64_t* smooth_checks = nullptr; + uint64_t smooth_limit = 0; bool cancelled() const { return request.cancel && request.cancel->load(std::memory_order_relaxed); } - bool expired() const { return cancelled() || Clock::now() >= deadline; } + bool expired() const { return cancelled() || Clock::now() >= deadline || (smooth_checks && *smooth_checks >= smooth_limit); } }; struct LatticeTierInput @@ -65,8 +68,17 @@ struct LatticeTierInput const PlannerConfig& config; double deviation_deg; TimePoint deadline; + TimePoint smooth_deadline; }; +class LatticeCSpace; +struct LatticeMotion { double curvature; double length; }; +struct LatticeDubinsWord { std::array motion; double length; }; +int latticeDubinsWords(const PathPoint& start, double x, double y, double yaw, double radius, + std::array* words); +bool latticeAppendMotion(LatticeContext& context, LatticeCSpace& space, const LatticeMotion& motion, Path* path, bool check = true); +bool latticeAppendSpin(LatticeContext& context, LatticeCSpace& space, double yaw, Path* path); + struct LatticeStateKey { int32_t x, y, heading; @@ -146,6 +158,7 @@ bool rejectLatticeCrossing(LatticeContext& context, const Path& path); bool verifyLatticeCandidate(LatticeContext& context, const Path& path, PathCheck* check); bool buildLatticeField(LatticeContext& context, LatticeField* field, TimePoint field_deadline); bool searchLattice(LatticeContext& context, LatticeCSpace& space, const LatticeField& field, Path* path, PathCheck* check); +void smoothLatticePath(LatticeContext& context, LatticeCSpace& space, Path* path, PathCheck* check); bool planLatticeTier(const LatticeTierInput& input, GraphTierOutput output); } // namespace detail diff --git a/src/lattice_search.cpp b/src/lattice_search.cpp index 10b8d7d..ec8e591 100644 --- a/src/lattice_search.cpp +++ b/src/lattice_search.cpp @@ -19,16 +19,8 @@ namespace detail namespace { -struct Motion -{ - double curvature; - double length; -}; -struct DubinsWord -{ - std::array motion; - double length; -}; +using Motion = LatticeMotion; +using DubinsWord = LatticeDubinsWord; struct AnalyticCandidate { DubinsWord word; @@ -245,7 +237,8 @@ bool verifyCandidateImpl(LatticeContext& context, const Path& path, PathCheck* c return false; } if (!check->valid || !freeClearanceOk(path, context.grid, clearanceThresholdMm(context.config.clearance_min_m), context.request.cancel, &context.deadline) || - blockedEndpointTurn(path, context.grid, context.config.half_x_m, context.config.half_y_m) != nullptr) return false; + blockedEndpointTurn(path, context.grid, context.config.half_x_m, context.config.half_y_m, + context.request.cancel, &context.deadline) != nullptr) return false; if (context.expired()) return false; const GapCheck gap = checkFootprintGap(path, context.grid, context.config.footprint_min_gap_m, context.config.half_x_m, context.config.half_y_m, context.request.cancel, &context.deadline, @@ -258,6 +251,22 @@ bool verifyCandidateImpl(LatticeContext& context, const Path& path, PathCheck* c } // namespace +int latticeDubinsWords(const PathPoint& start, double x, double y, double yaw, double radius, + std::array* words) +{ + return dubinsWords(start, x, y, yaw, radius, words); +} + +bool latticeAppendMotion(LatticeContext& context, LatticeCSpace& space, const LatticeMotion& motion, Path* path, bool check) +{ + return appendMotion(context, space, motion, path, check); +} + +bool latticeAppendSpin(LatticeContext& context, LatticeCSpace& space, double yaw, Path* path) +{ + return appendSpin(context, space, yaw, path); +} + bool rejectLatticeCrossing(LatticeContext& context, const Path& path) { if (!hasCrossing(context, path)) return false; diff --git a/src/lattice_smoother.cpp b/src/lattice_smoother.cpp new file mode 100644 index 0000000..1215ac6 --- /dev/null +++ b/src/lattice_smoother.cpp @@ -0,0 +1,615 @@ +#include "lattice_internal.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace lane_route_core +{ +namespace detail +{ +namespace +{ +constexpr double kHeadingBin = 3.0 * kPi / 180.0; +constexpr double kHeadingFilterM = 0.35; +constexpr uint64_t kImprovementChecks = 30000; + +struct Score +{ + int changes = 0; + double turn = 0.0; + double length = 0.0; +}; + +Score score(const Path& path) +{ + Score out; + int sign = 0; + double run = 0.0; + int runs = 0; + for (std::size_t i = 1; i < path.size(); ++i) + { + const double ds = std::hypot(path[i].x - path[i-1].x, path[i].y - path[i-1].y); + if (ds < 1e-8) continue; + const double turn = wrapAngle(path[i].yaw - path[i-1].yaw); + out.length += ds; + out.turn += std::abs(turn); + const int next = turn > 1e-5 ? 1 : turn < -1e-5 ? -1 : 0; + if (next && sign && next != sign) + { + if (std::abs(run) >= kPi / 180.0) ++runs; + run = 0.0; + } + if (next) { sign = next; run += turn; } + } + if (std::abs(run) >= kPi / 180.0) ++runs; + out.changes = std::max(0, runs - 1); + return out; +} + +bool better(const Score& a, const Score& b) +{ + if (a.changes != b.changes) return a.changes < b.changes; + if (a.turn != b.turn) return a.turn < b.turn; + return a.length < b.length; +} + +struct WordChoice +{ + LatticeDubinsWord word; + double score; + std::size_t serial; +}; + +struct Anchor +{ + std::size_t index; + double low_yaw; +}; + +struct State +{ + std::size_t anchor; + double yaw; + double cost; + int64_t parent; + bool raw; + std::pmr::vector piece; +}; + +class Smoother +{ +public: + Smoother(LatticeContext& context, LatticeCSpace& space, Path* output, PathCheck* check) + : context_(context), space_(space), output_(output), check_(check), witness_(*output), best_(score(*output)) {} + + void run() + { + if (context_.expired() || witness_.size() < 2) return; + while (first_ + 1 < witness_.size() && distance(witness_[first_], witness_[first_+1]) <= 1e-8) ++first_; + last_ = witness_.size()-1; + while (last_ > first_ && distance(witness_[last_], witness_[last_-1]) <= 1e-8) --last_; + if (last_ <= first_ || !anchors()) return; + + Path direct; + const auto& a = witness_[first_]; + const auto& b = witness_[last_]; + const double bearing = std::atan2(b.y-a.y, b.x-a.x); + if (!chordBlocked(a, b) && connectStartGoal(bearing, bearing, &direct) && score(direct).turn < 1e-6 && accept(direct)) return; + if (context_.expired()) return; + const bool greedy_ok = runGreedy(); + if (context_.expired()) return; + const uint64_t used = *context_.smooth_checks; + const uint64_t limit = !greedy_ok || used > std::numeric_limits::max()-kImprovementChecks ? + std::numeric_limits::max() : used+kImprovementChecks; + const uint64_t saved_limit = context_.smooth_limit; + context_.smooth_limit = std::min(saved_limit, limit); + runGraph(greedy_ok, limit); + context_.smooth_limit = saved_limit; + if (!context_.expired() && context_.info.lattice_smoothed == 1) finishClothoids(); + } + +private: + static double distance(const PathPoint& a, const PathPoint& b) { return std::hypot(b.x-a.x, b.y-a.y); } + + bool chordBlocked(const PathPoint& a, const PathPoint& b) const + { + const double length = distance(a, b); + if (length < 3.0) return false; + const GridRef& grid = context_.grid; + const double count = std::floor(length / grid.resolution); + if (!std::isfinite(count) || count >= std::numeric_limits::max()) return true; + const int steps = std::max(1, static_cast(count)); + const double minimum = std::min(context_.config.half_x_m, context_.config.half_y_m) + context_.config.footprint_min_gap_m; + for (int i = 0; i <= steps; ++i) + { + if ((i & 255) == 0 && context_.expired()) return true; + const double t = static_cast(i) / steps; + const double x = std::floor((a.x+t*(b.x-a.x)-grid.origin_x)/grid.resolution); + const double y = std::floor((a.y+t*(b.y-a.y)-grid.origin_y)/grid.resolution); + if (x < 0 || y < 0 || x >= grid.width || y >= grid.height) return true; + if (grid.clearance_mm[static_cast(y)*grid.width+static_cast(x)]/1000.0 < minimum) return true; + } + return false; + } + + bool anchors() + { + cumulative_.resize(last_-first_+1, 0.0); + unwrapped_.resize(cumulative_.size()); + unwrapped_[0] = witness_[first_].yaw; + for (std::size_t i = first_+1; i <= last_; ++i) + { + if ((i & 1023u) == 0 && context_.expired()) return false; + cumulative_[i-first_] = cumulative_[i-first_-1] + distance(witness_[i-1], witness_[i]); + unwrapped_[i-first_] = unwrapped_[i-first_-1] + wrapAngle(witness_[i].yaw-witness_[i-1].yaw); + } + const double spacing = std::max(cumulative_.back() / static_cast(last_-first_), 1e-3); + const double sigma = kHeadingFilterM / spacing; + if (sigma <= 1e-12) filter_.push_back(1.0); + else + { + const int radius = static_cast(4.0*sigma + 0.5); + filter_.reserve(static_cast(2*radius+1)); + for (int k = -radius; k <= radius; ++k) filter_.push_back(std::exp(-0.5*k*k/(sigma*sigma))); + } + std::size_t index = first_; + while (index < last_) + { + if (context_.expired()) return false; + anchor_.push_back({index, lowHeading(index)}); + const auto& p = witness_[index]; + const GridRef& grid = context_.grid; + const int x = static_cast(std::floor((p.x-grid.origin_x)/grid.resolution)); + const int y = static_cast(std::floor((p.y-grid.origin_y)/grid.resolution)); + if (x < 0 || y < 0 || x >= grid.width || y >= grid.height) return false; + const double clear = grid.clearance_mm[static_cast(y)*grid.width+x] / 1000.0; + const double next = cumulative_[index-first_] + std::clamp(clear, 0.5, 8.0); + const auto it = std::lower_bound(cumulative_.begin() + static_cast(index-first_+1), cumulative_.end(), next); + if (it == cumulative_.end()) break; + index = first_ + static_cast(it-cumulative_.begin()); + } + anchor_.push_back({last_, witness_[last_].yaw}); + return anchor_.size() >= 2; + } + + double lowHeading(std::size_t index) const + { + if (index == first_ || index == last_) return witness_[index].yaw; + const int radius = static_cast(filter_.size()/2); + const int64_t center = static_cast(index-first_); + double sum = 0.0, weight = 0.0; + for (int k = -radius; k <= radius; ++k) + { + if ((k & 1023) == 0 && context_.expired()) return witness_[index].yaw; + const int64_t sample = std::clamp(center+k, 0, static_cast(unwrapped_.size()-1)); + const double w = filter_[static_cast(k+radius)]; + sum += w*unwrapped_[static_cast(sample)]; + weight += w; + } + return sum/weight; + } + + bool connector(const PathPoint& start, const PathPoint& goal, Path* piece, double* edge_score = nullptr) + { + std::pmr::vector choices(&context_.memory); + const auto& configured = context_.config.corner_radii_m; + const std::array radii{{configured.front(), configured[2*(configured.size()-1)/3], configured.back()}}; + const double chord = distance(start, goal); + const double heading_change = std::abs(wrapAngle(goal.yaw-start.yaw)); + for (double radius : radii) + { + if (context_.expired()) return false; + std::array words; + const int count = latticeDubinsWords(start, goal.x, goal.y, goal.yaw, radius, &words); + for (int i = 0; i < std::min(count, 4); ++i) + { + const auto& word = words[i]; + if (!std::isfinite(word.length) || word.length > std::max(1.6*chord+1.0, chord+3.0)) continue; + double turn = 0.0; + int previous = 0, changes = 0; + for (const auto& motion : word.motion) + { + turn += std::abs(motion.curvature * motion.length); + const int sign = std::abs(motion.curvature * motion.length) > kPi/180.0 ? + (motion.curvature > 0 ? 1 : motion.curvature < 0 ? -1 : 0) : 0; + if (sign && previous && sign != previous) ++changes; + if (sign) previous = sign; + } + // Same pruning as the Python S3 that the user graded: drop words that turn more than the heading change plus 1.6 rad. A + // tighter rule (heading change + 0.015 rad and no sign change) left about 40% of regress7 lattice paths unsmoothed, because + // an offset between two anchors needs an S. S words stay possible; the score below charges each sign change. + if (turn > heading_change + 1.6) continue; + choices.push_back({word, turn*180.0/kPi + 3.0*word.length + 30.0*changes, choices.size()}); + } + } + std::sort(choices.begin(), choices.end(), [](const WordChoice& a, const WordChoice& b) { + return a.score != b.score ? a.score < b.score : a.serial < b.serial; + }); + for (const auto& choice : choices) + { + if (context_.expired()) return false; + ++context_.info.lattice_smooth_connectors_tried; + Path candidate(1, start); + bool ok = true; + for (const auto& motion : choice.word.motion) + if (ok) ok = latticeAppendMotion(context_, space_, motion, &candidate, false); + if (!ok || candidate.empty()) continue; + if (distance(candidate.back(), goal) > 1e-6 || std::abs(wrapAngle(candidate.back().yaw-goal.yaw)) > 1e-6) continue; + // S3's sparse centre-clearance probe rejects obvious failures before the full swept-footprint checks. + const GridRef& grid = context_.grid; + const double probe_min = std::min(context_.config.half_x_m, context_.config.half_y_m) - grid.resolution; + for (std::size_t i = 0; i < candidate.size(); i += 4) + { + if (context_.expired()) return false; + ++*context_.smooth_checks; + const double x = std::floor((candidate[i].x-grid.origin_x)/grid.resolution); + const double y = std::floor((candidate[i].y-grid.origin_y)/grid.resolution); + if (x < 0 || y < 0 || x >= grid.width || y >= grid.height || + grid.clearance_mm[static_cast(y)*grid.width+static_cast(x)]/1000.0 < probe_min) + { + ok = false; + break; + } + } + if (!ok || context_.expired()) continue; + for (std::size_t i = 1; i < candidate.size(); ++i) + if (!space_.segmentLegal(candidate[i-1], candidate[i])) { ok = false; break; } + if (!ok || context_.expired()) continue; + ++context_.info.lattice_smooth_connectors_ok; + if (edge_score) *edge_score = choice.score; + *piece = std::move(candidate); + return true; + } + return false; + } + + bool initial(double yaw, Path* out) + { + const Pose2& start = context_.request.start; + out->assign(1, {start.x, start.y, start.has_yaw ? start.yaw : yaw, 0.0}); + return !start.has_yaw || std::abs(wrapAngle(yaw-start.yaw)) < 1e-10 || latticeAppendSpin(context_, space_, yaw, out); + } + + bool finish(Path* path) + { + const Pose2& goal = context_.request.goal; + if (goal.has_yaw && std::abs(wrapAngle(path->back().yaw-goal.yaw)) > 1e-10 && + !latticeAppendSpin(context_, space_, goal.yaw, path)) return false; + return true; + } + + bool clothoidSegmentLegal(const PathPoint& a, const PathPoint& b) + { + if (!space_.segmentLegal(a, b)) return false; + const double turn = std::abs(wrapAngle(b.yaw-a.yaw)); + if (turn >= kPi/3.0) return false; + const double bound = distance(a,b)/std::cos(turn) + 1e-9; + const GridRef& g = context_.grid; + const auto cell = [](double coordinate, int limit) { + return static_cast(std::clamp(std::floor(coordinate), 0.0, static_cast(limit-1))); + }; + const int x0 = cell((a.x-bound-g.origin_x)/g.resolution, g.width); + const int x1 = cell((a.x+bound-g.origin_x)/g.resolution, g.width); + const int y0 = cell((a.y-bound-g.origin_y)/g.resolution, g.height); + const int y1 = cell((a.y+bound-g.origin_y)/g.resolution, g.height); + for (int y = y0; y <= y1; ++y) + for (int x = x0; x <= x1; ++x) + { + if (context_.expired()) return false; + const std::size_t cell = static_cast(y)*g.width+x; + if (g.cost[cell] >= kInscribedCost) return false; + const uint8_t zone = g.direction ? g.direction[cell] : 0; + if (zone == 0 && g.clearance_mm[cell] < clearanceThresholdMm(context_.config.clearance_min_m)) return false; + if (zone != 0) + { + const double angle = (zone-1)*kPi/4.0; + if (std::max(std::abs(wrapAngle(a.yaw-angle)), std::abs(wrapAngle(b.yaw-angle))) + turn > + context_.deviation_deg*kPi/180.0 + 1e-9) return false; + } + } + const double radius = std::hypot(context_.config.half_x_m, context_.config.half_y_m) + context_.config.footprint_min_gap_m; + return space_.poseFree(a.x, a.y, a.yaw, bound + 2.0*radius*std::sin(turn/2.0), bound); + } + + bool connectStartGoal(double from, double to, Path* path) + { + if (!initial(from, path)) return false; + Path piece; + const auto& end = witness_[last_]; + if (!connector(path->back(), {end.x, end.y, to, 0.0}, &piece)) return false; + path->insert(path->end(), piece.begin()+1, piece.end()); + return finish(path); + } + + bool accept(const Path& candidate, bool improve_smoothed = false) + { + if (context_.expired() || (improve_smoothed && context_.info.lattice_smoothed != 0 && !better(score(candidate), best_))) return false; + Path ready(candidate); + // Account for the verifier's dense pose samples before starting it; never replace the verified witness on exhaustion. + uint64_t estimate = 1; + for (std::size_t i = 1; i < candidate.size(); ++i) + { + const double ds = distance(candidate[i-1], candidate[i]); + const double da = std::abs(wrapAngle(candidate[i].yaw-candidate[i-1].yaw)); + const double samples = std::max({1.0, std::ceil(ds/0.01), std::ceil(da/0.03)}) + 1.0 + + std::max({1.0, std::ceil(ds/0.04), std::ceil(da/0.03)}) + + (ds < 1e-7 && da > 1e-12 ? std::max(1.0, std::ceil(da/0.03)) + 1.0 : 0.0); + if (estimate > context_.smooth_limit - *context_.smooth_checks || + samples > static_cast(context_.smooth_limit - *context_.smooth_checks - estimate)) + { + *context_.smooth_checks = context_.smooth_limit; + return false; + } + estimate += static_cast(samples); + } + *context_.smooth_checks += estimate; + if (context_.expired()) return false; + PathCheck candidate_check; + ++context_.info.lattice_smooth_candidates; + if (!verifyLatticeCandidate(context_, candidate, &candidate_check)) + { + if (!context_.expired()) ++context_.info.lattice_smooth_rejects_verify; + return false; + } + output_->swap(ready); + *check_ = candidate_check; + best_ = score(candidate); + context_.info.lattice_smoothed = 1; + return true; + } + + bool runGreedy(); + void runGraph(bool improve_smoothed, uint64_t check_limit); + void finishClothoids(); + + LatticeContext& context_; + LatticeCSpace& space_; + Path* output_; + PathCheck* check_; + Path witness_; + Score best_; + std::size_t first_ = 0, last_ = 0; + std::vector cumulative_; + std::vector unwrapped_; + std::vector filter_; + std::vector anchor_; +}; + +bool Smoother::runGreedy() +{ + Path route; + if (!initial(witness_[first_].yaw, &route)) return false; + std::size_t n = 0; + while (n + 1 < anchor_.size() && !context_.expired()) + { + const PathPoint from = route.back(); + bool landed = false; + for (std::size_t j = anchor_.size(); j-- > n+1 && !context_.expired();) + { + const auto& target = witness_[anchor_[j].index]; + if (chordBlocked(from, target)) continue; + const double bearing = std::atan2(target.y-from.y, target.x-from.x); + const std::array headings{{bearing, anchor_[j].low_yaw}}; + for (double yaw : headings) + { + Path piece; + if (!connector(from, {target.x, target.y, yaw, 0.0}, &piece)) continue; + route.insert(route.end(), piece.begin()+1, piece.end()); + n = j; + landed = true; + break; + } + if (landed) break; + } + if (!landed) return false; + } + return n + 1 == anchor_.size() && finish(&route) && accept(route); +} + +void Smoother::runGraph(bool improve_smoothed, uint64_t check_limit) +{ + std::pmr::vector states(&context_.memory); + std::pmr::map, std::size_t> best(&context_.memory); + const auto alive = [&]() { return !context_.expired() && *context_.smooth_checks < check_limit; }; + const auto headingKey = [](double yaw) { return static_cast(std::nearbyint(wrapAngle(yaw)/kHeadingBin)); }; + constexpr int kRawHeading = 100000; + const auto offer = [&](std::size_t n, double yaw, double cost, int64_t parent, bool raw, Path piece) { + const auto key = std::make_pair(n, raw ? kRawHeading : headingKey(yaw)); + const auto found = best.find(key); + if (found != best.end() && states[found->second].cost <= cost) return; + if (states.size() >= 10000) { context_.info.lattice_smooth_stop = "budget"; return; } + const std::size_t id = states.size(); + std::pmr::vector stored(piece.begin(), piece.end(), &context_.memory); + states.push_back({n, yaw, cost, parent, raw, std::move(stored)}); + best[key] = id; + }; + Path raw_root; + if (!initial(witness_[first_].yaw, &raw_root)) return; + offer(0, witness_[first_].yaw, 0.0, -1, true, std::move(raw_root)); + for (std::size_t j = anchor_.size(); j-- > 1 && alive();) + { + const auto& target = witness_[anchor_[j].index]; + const auto& start = witness_[first_]; + if (chordBlocked(start, target)) continue; + const double bearing = std::atan2(target.y-start.y, target.x-start.x); + std::vector> choices{{bearing, bearing}}; + if (j + 1 != anchor_.size() || context_.request.goal.has_yaw) + { + const std::array end_yaws{{anchor_[j].low_yaw, target.yaw}}; + const auto& radii = context_.config.corner_radii_m; + for (double end_yaw : end_yaws) + for (double radius : {radii.front(), radii.back()}) + for (int side : {1, -1}) + { + const double cx = target.x - side*radius*std::sin(end_yaw); + const double cy = target.y + side*radius*std::cos(end_yaw); + const double d = std::hypot(cx-start.x, cy-start.y); + if (d > radius + 1e-6) + choices.emplace_back(std::atan2(cy-start.y,cx-start.x) - side*std::asin(radius/d), end_yaw); + } + } + bool landed = false; + for (const auto& choice : choices) + { + if (!alive()) return; + Path root; + if (!initial(choice.first, &root)) continue; + Path piece; + double edge_score = 0.0; + if (!connector(root.back(), {target.x, target.y, choice.second, 0.0}, &piece, &edge_score)) continue; + if (states.size() >= 10000) { context_.info.lattice_smooth_stop = "budget"; return; } + const std::size_t root_id = states.size(); + std::pmr::vector stored(root.begin(), root.end(), &context_.memory); + states.push_back({0, choice.first, 0.0, -1, false, std::move(stored)}); + offer(j, choice.second, edge_score, static_cast(root_id), false, std::move(piece)); + landed = true; + } + if (landed) break; + } + + for (std::size_t n = 0; n + 1 < anchor_.size() && alive(); ++n) + { + // Edges always advance to a later anchor, so every predecessor is complete before this anchor is visited. + std::vector at; + for (const auto& item : best) if (item.first.first == n) at.push_back(item.second); + for (std::size_t id : at) + { + if (!alive()) return; + const double state_yaw = states[id].yaw; + const double state_cost = states[id].cost; + const bool raw_state = states[id].raw; + const auto& point = witness_[anchor_[n].index]; + const PathPoint from{point.x, point.y, state_yaw, 0.0}; + bool landed = false; + for (std::size_t j = anchor_.size(); j-- > n+1 && alive();) + { + const auto& target = witness_[anchor_[j].index]; + if (chordBlocked(from, target)) continue; + const double bearing = std::atan2(target.y-from.y, target.x-from.x); + const std::array headings{{bearing, anchor_[j].low_yaw, context_.request.goal.yaw}}; + std::array used{{10000,10000,10000}}; + std::size_t used_count = 0; + const std::size_t heading_count = j + 1 == anchor_.size() && context_.request.goal.has_yaw ? 3 : 2; + for (std::size_t h = 0; h < heading_count; ++h) + { + const double yaw = headings[h]; + if (!alive()) return; + const int key = headingKey(yaw); + if (std::find(used.begin(), used.begin()+static_cast(used_count), key) != used.begin()+static_cast(used_count)) continue; + used[used_count++] = key; + Path piece; + double edge_score = 0.0; + if (!connector(from, {target.x, target.y, yaw, 0.0}, &piece, &edge_score)) continue; + const double cost = state_cost + edge_score; + offer(j, yaw, cost, static_cast(id), false, std::move(piece)); + landed = true; + } + if (landed) break; // S3 keeps the farthest successful target for each state. + } + if (raw_state) + { + const std::size_t next = anchor_[n+1].index; + Path piece(witness_.begin()+static_cast(anchor_[n].index), + witness_.begin()+static_cast(next+1)); + const Score local = score(piece); + offer(n+1, witness_[next].yaw, state_cost+100.0+local.turn*180.0/kPi+3.0*local.length, + static_cast(id), true, std::move(piece)); + } + } + } + std::vector goals; + for (const auto& item : best) if (item.first.first + 1 == anchor_.size()) goals.push_back(item.second); + std::sort(goals.begin(), goals.end(), [&](std::size_t a, std::size_t b) { return states[a].cost < states[b].cost; }); + for (std::size_t goal : goals) + { + if (!alive()) return; + std::vector chain; + for (int64_t id = static_cast(goal); id >= 0; id = states[static_cast(id)].parent) + chain.push_back(static_cast(id)); + std::reverse(chain.begin(), chain.end()); + Path candidate(states[chain.front()].piece.begin(), states[chain.front()].piece.end()); + for (std::size_t i = 1; i < chain.size(); ++i) + candidate.insert(candidate.end(), states[chain[i]].piece.begin()+1, states[chain[i]].piece.end()); + if (finish(&candidate) && accept(candidate, improve_smoothed)) return; + } +} + +void Smoother::finishClothoids() +{ + // Only replace a complete line-arc-line run; preserve the last fully verified path after each attempt. + const Path source = *output_; + for (std::size_t i = 1; i + 2 < source.size() && !context_.expired(); ++i) + { + if (std::abs(source[i].curvature) > 1e-5 || std::abs(source[i+1].curvature) < 1e-5) continue; + const double sign = source[i+1].curvature > 0.0 ? 1.0 : -1.0; + std::size_t end = i+1; + while (end+1 < source.size() && sign*source[end+1].curvature > 1e-5) ++end; + if (end+1 >= source.size() || std::abs(source[end+1].curvature) > 1e-5) continue; + std::size_t before = i; + while (before > 0 && std::abs(source[before].curvature) < 1e-5 && distance(source[before-1],source[before]) > 1e-8) --before; + std::size_t after = end+1; + while (after+1 < source.size() && std::abs(source[after+1].curvature) < 1e-5 && distance(source[after],source[after+1]) > 1e-8) ++after; + const auto& a = source[before]; + const auto& c = source[after]; + const double h0 = source[i].yaw, h1 = source[end].yaw; + const double det = std::sin(h1-h0); + if (std::abs(det) < 1e-6) { i = end; continue; } + const double dx = c.x-a.x, dy = c.y-a.y; + const double along = (dx*std::sin(h1)-dy*std::cos(h1))/det; + const Point2 vertex{a.x+along*std::cos(h0), a.y+along*std::sin(h0)}; + for (double radius : context_.config.corner_radii_m) + for (double sharpness : kSharpness) + { + if (context_.expired()) return; + double trim = 0.0; + const Path curve = placedCorner({a.x,a.y}, vertex, {c.x,c.y}, radius, sharpness, context_.config.output_step_m, &trim); + if (curve.empty() || trim >= std::min(std::hypot(vertex.x-a.x,vertex.y-a.y), std::hypot(vertex.x-c.x,vertex.y-c.y))) continue; + Path candidate(source.begin(), source.begin()+static_cast(before+1)); + bool legal = latticeAppendMotion(context_, space_, {0.0, distance(a,curve.front())}, &candidate); + if (legal && (distance(candidate.back(), curve.front()) > 1e-6 || + std::abs(wrapAngle(candidate.back().yaw-curve.front().yaw)) > 1e-6)) legal = false; + for (std::size_t k = 1; legal && k < curve.size(); ++k) + { + legal = clothoidSegmentLegal(candidate.back(), curve[k]); + if (legal) candidate.push_back(curve[k]); + } + if (!legal) continue; + legal = latticeAppendMotion(context_, space_, {0.0, distance(curve.back(),c)}, &candidate); + if (!legal || distance(candidate.back(), c) > 1e-6 || std::abs(wrapAngle(candidate.back().yaw-c.yaw)) > 1e-6) continue; + candidate.insert(candidate.end(), source.begin()+static_cast(after+1), source.end()); + const Score previous = best_; + // Clothoids may be slightly longer, but must not introduce additional turning or sign changes. + const Score next = score(candidate); + if (next.changes > previous.changes || next.turn > previous.turn+1e-4) continue; + const bool accepted = accept(candidate); + if (accepted) { context_.info.lattice_smoothed = 2; return; } + } + i = end; + } +} + +} // namespace + +void smoothLatticePath(LatticeContext& context, LatticeCSpace& space, Path* path, PathCheck* check) +{ + Smoother(context, space, path, check).run(); + if (context.cancelled()) return; + if (Clock::now() >= context.deadline) context.info.lattice_smooth_stop = "deadline"; + else if (*context.smooth_checks >= context.smooth_limit || context.info.lattice_smooth_stop == "budget") + context.info.lattice_smooth_stop = "budget"; + else if (context.info.lattice_smoothed != 0) context.info.lattice_smooth_stop = "accepted"; + else if (context.info.lattice_smooth_rejects_verify != 0) context.info.lattice_smooth_stop = "verify_failed"; + else context.info.lattice_smooth_stop = "no_route"; +} + +} // namespace detail +} // namespace lane_route_core diff --git a/src/lattice_tier.cpp b/src/lattice_tier.cpp index 8c04714..9f60170 100644 --- a/src/lattice_tier.cpp +++ b/src/lattice_tier.cpp @@ -37,6 +37,7 @@ bool planLatticeTier(const LatticeTierInput& input, GraphTierOutput output) LatticeContext context{ input.request, input.grid, input.config, input.deviation_deg, input.deadline, output.info, memory }; output.info.lattice_reason.clear(); bool ok = false; + bool search_timed_out = false; try { LatticeCSpace space(context); @@ -50,8 +51,28 @@ bool planLatticeTier(const LatticeTierInput& input, GraphTierOutput output) } if (field_ok) { - StageTimer timer(output.info.lattice_search_ms, &output.info.lattice_verify_ms); - ok = searchLattice(context, space, field, &output.path, &output.check); + { + StageTimer timer(output.info.lattice_search_ms, &output.info.lattice_verify_ms); + ok = searchLattice(context, space, field, &output.path, &output.check); + } + search_timed_out = Clock::now() >= input.deadline; + if (ok && !search_timed_out && input.config.lattice_smooth_enabled && !context.cancelled()) + { + // The wavefront is no longer needed; release it before the smoother allocates its anchor graph. + { + std::pmr::vector values(&memory); + std::pmr::vector settled(&memory); + values.swap(field.values); + settled.swap(field.settled); + } + const TimePoint smooth_began = Clock::now(); + context.deadline = input.smooth_deadline; + context.smooth_checks = &output.info.lattice_smooth_checks; + context.smooth_limit = static_cast(input.config.lattice_smooth_max_checks); + try { smoothLatticePath(context, space, &output.path, &output.check); } + catch (const std::bad_alloc&) { output.info.lattice_smooth_stop = "budget"; } + output.info.lattice_smooth_ms += msSince(smooth_began); + } } } catch (const std::bad_alloc&) @@ -61,7 +82,7 @@ bool planLatticeTier(const LatticeTierInput& input, GraphTierOutput output) output.info.lattice_peak_bytes = std::max(output.info.lattice_peak_bytes, static_cast(memory.peak())); output.info.lattice_ms += msSince(began); const bool cancelled = context.cancelled(); - const bool timed_out = Clock::now() >= input.deadline; + const bool timed_out = !ok ? Clock::now() >= input.deadline : search_timed_out; if (cancelled) output.info.lattice_reason = "cancelled"; else if (timed_out) output.info.lattice_reason = "lattice_timeout"; else if (ok) output.info.lattice_reason = "verified"; diff --git a/src/route_planner.cpp b/src/route_planner.cpp index 6f4e396..5974686 100644 --- a/src/route_planner.cpp +++ b/src/route_planner.cpp @@ -40,6 +40,30 @@ PlanResult planRoute(const GraphProvider& graphs, const RouteRequest& request, c result.path.clear(); result.info.reason = "cancelled"; } + if (result.ok) + { + int previous_sign = 0; + double straight = 0.0; + for (std::size_t i = 1; i < result.path.size(); ++i) + { + const PathPoint& a = result.path[i - 1]; + const PathPoint& b = result.path[i]; + const double length = std::hypot(b.x - a.x, b.y - a.y); + if (length < 1e-9) continue; + const double turn = wrapAngle(b.yaw - a.yaw); + const double arc = std::abs(turn) < 1e-9 ? length : length * std::abs(turn) / (2.0 * std::abs(std::sin(turn / 2.0))); + result.info.path_length_m += arc; + const double curvature = turn / arc; + const int sign = curvature > 0.001 ? 1 : curvature < -0.001 ? -1 : 0; + if (sign == 0) straight += arc; + else + { + if (previous_sign != 0 && sign != previous_sign) ++result.info.curvature_sign_changes; + previous_sign = sign; + } + } + if (result.info.path_length_m > 0.0) result.info.straight_share = straight / result.info.path_length_m; + } return result; }; const std::string config_error = config.validate(); @@ -144,7 +168,7 @@ PlanResult planRoute(const GraphProvider& graphs, const RouteRequest& request, c break; } const TimePoint rung_deadline = now + (fallback_deadline - now) / static_cast(rungs.size() - rung); - if (detail::planLatticeTier({ request, live, config, deviation, rung_deadline }, + if (detail::planLatticeTier({ request, live, config, deviation, rung_deadline, fallback_deadline }, { result.path, result.check, result.info })) { result.ok = true; diff --git a/test/lane_route_core_test.cpp b/test/lane_route_core_test.cpp index efd8e62..9c80a44 100644 --- a/test/lane_route_core_test.cpp +++ b/test/lane_route_core_test.cpp @@ -983,6 +983,7 @@ PlannerConfig latticeConfig() { PlannerConfig c; c.lattice_enabled = true; + c.lattice_smooth_enabled = false; // R1 tests inspect the unsmoothed lattice result. c.time_limit_s = 10.0; c.fallback_time_limit_s = 3.0; return c; @@ -1453,6 +1454,11 @@ TEST(Lattice, InvalidParametersAreRejected) EXPECT_FALSE(config.validate().empty()); config.lattice_enabled = false; EXPECT_TRUE(config.validate().empty()); + config = latticeConfig(); + config.lattice_smooth_max_checks = -1; + EXPECT_FALSE(config.validate().empty()); + config.lattice_smooth_max_checks = 0; + EXPECT_TRUE(config.validate().empty()); } TEST(Lattice, DirectionChecksBothCellsOnAnExactBoundary) @@ -1667,3 +1673,198 @@ TEST(Lattice, GapBelowEndpointFloorIsRejected) EXPECT_FALSE(detail::verifyLatticeCandidate(context, path, &check)); EXPECT_TRUE(check.valid); // Collision, curvature, directions and crossing passed; the gap rejected it. } + +namespace +{ + +void appendSmoothingTestMotion(Path* path, double curvature, double length) +{ + const PathPoint start = path->back(); + const int samples = std::max(1, static_cast(std::ceil(length / 0.04))); + for (int i = 1; i <= samples; ++i) + { + const double s = length * i / samples; + const double yaw = start.yaw + curvature * s; + if (std::abs(curvature) < 1e-12) + path->push_back({start.x+s*std::cos(start.yaw), start.y+s*std::sin(start.yaw), yaw, 0.0}); + else + path->push_back({start.x+(std::sin(yaw)-std::sin(start.yaw))/curvature, + start.y-(std::cos(yaw)-std::cos(start.yaw))/curvature, yaw, curvature}); + } +} + +/** Real clearance for a test grid: distance [mm] from each cell centre to the nearest lethal cell centre, as the costmap provides. + * The default fixture value of 10 m everywhere makes the smoother place anchors 8 m apart. */ +void fillClearance(LatticeTestGrid* map) +{ + const double resolution = kResolution; + for (int y = 0; y < map->height; ++y) + for (int x = 0; x < map->width; ++x) + { + double best = 10.0; + for (int r = 0; r < std::max(map->width, map->height) && r * resolution < best; ++r) + for (int dy = -r; dy <= r; ++dy) + for (int dx = -r; dx <= r; ++dx) + { + if (std::max(std::abs(dx), std::abs(dy)) != r) continue; + const int nx = x + dx, ny = y + dy; + if (nx < 0 || ny < 0 || nx >= map->width || ny >= map->height) continue; + if (map->cost[static_cast(ny) * map->width + nx] == kLethalCost) + best = std::min(best, std::hypot(dx, dy) * resolution); + } + map->clearance[static_cast(y) * map->width + x] = static_cast(std::lround(best * 1000.0)); + } +} + +Path smoothingZigzag() +{ + Path path{{2.0, 2.0, 0.0, 0.0}}; + for (int i = 0; i < 4; ++i) + { + appendSmoothingTestMotion(&path, 1.0/1.08, 0.18); + appendSmoothingTestMotion(&path, -1.0/1.08, 0.18); + } + return path; +} + +struct SmoothingResult +{ + Path path; + PathCheck check; + PlanInfo info; +}; + +SmoothingResult runSmoothing(const LatticeTestGrid& map, const Path& input, int64_t limit = 450000) +{ + PlannerConfig config = latticeConfig(); + config.lattice_smooth_enabled = true; + config.lattice_smooth_max_checks = limit; + RouteRequest request = latticeRequest(pose(input.front().x, input.front().y, input.front().yaw), + pose(input.back().x, input.back().y, input.back().yaw)); + request.start.has_yaw = false; + request.goal.has_yaw = false; + GridRef grid = map.view(); + SmoothingResult result; + result.path = input; + detail::LatticeMemory memory(128u * 1024u * 1024u); + detail::LatticeContext context{request, grid, config, 90.0, detail::Clock::now()+std::chrono::seconds(10), result.info, memory}; + detail::LatticeCSpace space(context); + EXPECT_TRUE(detail::verifyLatticeCandidate(context, result.path, &result.check)); + context.smooth_checks = &result.info.lattice_smooth_checks; + context.smooth_limit = static_cast(limit); + detail::smoothLatticePath(context, space, &result.path, &result.check); + return result; +} + +} // namespace + +TEST(LatticeSmoother, OpenZigzagBecomesStraight) +{ + LatticeTestGrid map(160, 160); + const SmoothingResult result = runSmoothing(map, smoothingZigzag()); + ASSERT_EQ(result.info.lattice_smoothed, 1); + ASSERT_TRUE(result.check.valid); + EXPECT_GT(result.info.lattice_smooth_connectors_tried, 0u); + EXPECT_GT(result.info.lattice_smooth_connectors_ok, 0u); + EXPECT_GT(result.info.lattice_smooth_candidates, 0u); + EXPECT_EQ(result.info.lattice_smooth_stop, "accepted"); + for (std::size_t i = 1; i < result.path.size(); ++i) + EXPECT_NEAR(wrapAngle(result.path[i].yaw-result.path[i-1].yaw), 0.0, 1e-6); +} + +TEST(LatticeSmoother, LShapedCorridorKeepsOneCleanTurn) +{ + LatticeTestGrid map(160, 160); + for (int y = 0; y < map.height; ++y) + for (int x = 0; x < map.width; ++x) + { + const double wx = (x+0.5)*kResolution, wy = (y+0.5)*kResolution; + const bool horizontal = wx >= 0.8 && wx <= 5.9 && wy >= 0.9 && wy <= 3.0; + const bool vertical = wx >= 3.9 && wx <= 6.1 && wy >= 0.9 && wy <= 6.5; + if (!horizontal && !vertical) map.cost[static_cast(y)*map.width+x] = kLethalCost; + } + fillClearance(&map); + Path path = smoothingZigzag(); + appendSmoothingTestMotion(&path, 0.0, 0.5); + appendSmoothingTestMotion(&path, 1.0/1.08, 1.08*kPi/2.0); + appendSmoothingTestMotion(&path, 0.0, 1.5); + const SmoothingResult result = runSmoothing(map, path); + ASSERT_TRUE(result.check.valid); + ASSERT_GE(result.info.lattice_smoothed, 1); + double min_yaw = 1e9, max_yaw = -1e9; + for (const auto& p : result.path) { min_yaw = std::min(min_yaw, p.yaw); max_yaw = std::max(max_yaw, p.yaw); } + EXPECT_GE(min_yaw, -0.05); + EXPECT_LE(max_yaw, kPi/2.0+0.05); +} + +TEST(LatticeSmoother, NoBudgetKeepsVerifiedRawPath) +{ + LatticeTestGrid map(160, 160); + const Path raw = smoothingZigzag(); + const SmoothingResult result = runSmoothing(map, raw, 0); + ASSERT_TRUE(result.check.valid); + EXPECT_EQ(result.info.lattice_smoothed, 0); + EXPECT_EQ(result.info.lattice_smooth_stop, "budget"); + ASSERT_EQ(result.path.size(), raw.size()); + for (std::size_t i = 0; i < raw.size(); ++i) + { + EXPECT_DOUBLE_EQ(result.path[i].x, raw[i].x); + EXPECT_DOUBLE_EQ(result.path[i].y, raw[i].y); + EXPECT_DOUBLE_EQ(result.path[i].yaw, raw[i].yaw); + EXPECT_DOUBLE_EQ(result.path[i].curvature, raw[i].curvature); + } +} + +TEST(LatticeSmoother, ExhaustionReturnsVerifiedPath) +{ + LatticeTestGrid map(160, 160); + const SmoothingResult result = runSmoothing(map, smoothingZigzag(), 5); + EXPECT_TRUE(result.check.valid); + EXPECT_LE(result.info.lattice_smooth_checks, 5u); +} + +TEST(LatticeSmoother, DeterministicForSameInput) +{ + LatticeTestGrid map(160, 160); + const Path raw = smoothingZigzag(); + const SmoothingResult a = runSmoothing(map, raw), b = runSmoothing(map, raw); + ASSERT_EQ(a.path.size(), b.path.size()); + for (std::size_t i = 0; i < a.path.size(); ++i) + { + EXPECT_DOUBLE_EQ(a.path[i].x, b.path[i].x); + EXPECT_DOUBLE_EQ(a.path[i].y, b.path[i].y); + EXPECT_DOUBLE_EQ(a.path[i].yaw, b.path[i].yaw); + EXPECT_DOUBLE_EQ(a.path[i].curvature, b.path[i].curvature); + } +} + +TEST(LatticeSmoother, EqualScoreStraightCandidateIsAccepted) +{ + LatticeTestGrid map(160, 160); + Path raw{{2.0, 2.0, 0.0, 0.0}}; + appendSmoothingTestMotion(&raw, 0.0, 2.0); + const SmoothingResult result = runSmoothing(map, raw); + ASSERT_TRUE(result.check.valid); + EXPECT_EQ(result.info.lattice_smoothed, 1); + EXPECT_EQ(result.info.lattice_smooth_stop, "accepted"); + EXPECT_GT(result.info.lattice_smooth_candidates, 0u); + EXPECT_NEAR(result.path.back().x, raw.back().x, 1e-6); + EXPECT_NEAR(result.path.back().y, raw.back().y, 1e-6); + for (const auto& point : result.path) EXPECT_NEAR(point.y, raw.front().y, 1e-6); +} + +TEST(LatticeSmoother, PlannerRunsEnabledSmoother) +{ + LatticeTestGrid map(120, 120); + PlannerConfig config = latticeConfig(); + config.lattice_smooth_enabled = true; + const PlanResult result = map.plan(latticeRequest(pose(1.0, 3.0, 0.0), pose(4.0, 3.0, 0.0)), config); + ASSERT_TRUE(result.ok) << result.info.reason; + EXPECT_TRUE(result.check.valid); + EXPECT_EQ(result.info.tier_used, "lattice"); + EXPECT_GE(result.info.lattice_smooth_ms, 0.0); + EXPECT_LE(result.info.lattice_smooth_checks, static_cast(config.lattice_smooth_max_checks)); + EXPECT_LE(result.info.lattice_smooth_connectors_ok, result.info.lattice_smooth_connectors_tried); + EXPECT_LE(result.info.lattice_smooth_rejects_verify, result.info.lattice_smooth_candidates); + EXPECT_FALSE(result.info.lattice_smooth_stop.empty()); +} diff --git a/tools/lane_route_eval.cpp b/tools/lane_route_eval.cpp index c693676..f95c298 100644 --- a/tools/lane_route_eval.cpp +++ b/tools/lane_route_eval.cpp @@ -149,6 +149,10 @@ void applyOverrides(PlannerConfig* config) const std::map longs{ { "lattice_field_max_cells", &config->lattice_field_max_cells }, { "lattice_max_memory_mb", &config->lattice_max_memory_mb }, + { "lattice_smooth_max_checks", &config->lattice_smooth_max_checks }, + }; + const std::map bools{ + { "lattice_smooth_enabled", &config->lattice_smooth_enabled }, }; std::stringstream stream(text); std::string item; @@ -165,6 +169,8 @@ void applyOverrides(PlannerConfig* config) *ints.at(key) = std::stoi(value); else if (longs.count(key) != 0) *longs.at(key) = std::stoll(value); + else if (bools.count(key) != 0) + *bools.at(key) = std::stoi(value) != 0; else throw std::runtime_error("unknown LANE_ROUTE_EVAL_SET key: " + key); std::cerr << "override " << key << "=" << value << std::endl; @@ -346,7 +352,15 @@ int main(int argc, char** argv) << ",\"lattice_crossing_rejects\":" << info.lattice_crossing_rejects << ",\"lattice_field_ms\":" << info.lattice_field_ms << ",\"lattice_search_ms\":" << info.lattice_search_ms << ",\"lattice_verify_ms\":" << info.lattice_verify_ms - << ",\"lattice_ms\":" << info.lattice_ms << "}\n"; + << ",\"lattice_ms\":" << info.lattice_ms + << ",\"lattice_smooth_ms\":" << info.lattice_smooth_ms << ",\"lattice_smooth_checks\":" << info.lattice_smooth_checks + << ",\"lattice_smoothed\":" << info.lattice_smoothed << ",\"curvature_sign_changes\":" << info.curvature_sign_changes + << ",\"path_length_m\":" << info.path_length_m << ",\"straight_share\":" << info.straight_share + << ",\"lattice_smooth_connectors_tried\":" << info.lattice_smooth_connectors_tried + << ",\"lattice_smooth_connectors_ok\":" << info.lattice_smooth_connectors_ok + << ",\"lattice_smooth_candidates\":" << info.lattice_smooth_candidates + << ",\"lattice_smooth_rejects_verify\":" << info.lattice_smooth_rejects_verify + << ",\"lattice_smooth_stop\":\"" << info.lattice_smooth_stop << "\"}\n"; std::cout << id << " " << deviation << " " << info.reason << " " << info.query_ms << " ms" << std::endl; } }