feat(lane_route): smooth lattice paths (R2) and expose the lattice tier in the plugin (R3)

- lane_route_core: port of the S3 smoother for lattice paths (direct,
  greedy and bounded graph improvement over witness anchors, then
  clothoid corners when budget remains), shape metrics and smoother
  diagnostics in PlanInfo and lane_route_eval.
- lane_route_planner: loads the lattice keys from YAML, logs a config
  summary at start-up and one debug/fallback line per lattice request.

regress7: coverage unchanged from R1, every lattice path smoothed, 0 bad
in the independent recheck. Local snapshot for history only; not pushed.
This commit is contained in:
2026-11-09 16:11:34 +07:00
parent 24822f5408
commit b0a3954541
13 changed files with 946 additions and 20 deletions

View File

@@ -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<int32_t>::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<bool>* 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<int>(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]))

View File

@@ -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);

View File

@@ -1,6 +1,7 @@
#ifndef LANE_ROUTE_CORE_LATTICE_INTERNAL_H_
#define LANE_ROUTE_CORE_LATTICE_INTERNAL_H_
#include <array>
#include <chrono>
#include <cmath>
#include <cstddef>
@@ -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<LatticeMotion, 3> motion; double length; };
int latticeDubinsWords(const PathPoint& start, double x, double y, double yaw, double radius,
std::array<LatticeDubinsWord, 6>* 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

View File

@@ -19,16 +19,8 @@ namespace detail
namespace
{
struct Motion
{
double curvature;
double length;
};
struct DubinsWord
{
std::array<Motion, 3> 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<LatticeDubinsWord, 6>* 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;

615
src/lattice_smoother.cpp Normal file
View File

@@ -0,0 +1,615 @@
#include "lattice_internal.h"
#include <algorithm>
#include <array>
#include <cmath>
#include <cstddef>
#include <limits>
#include <map>
#include <utility>
#include <vector>
#include <lane_route_core/clothoid.h>
#include <lane_route_core/grid_checks.h>
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<PathPoint> 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<uint64_t>::max()-kImprovementChecks ?
std::numeric_limits<uint64_t>::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<int>::max()) return true;
const int steps = std::max(1, static_cast<int>(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<double>(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<std::size_t>(y)*grid.width+static_cast<std::size_t>(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<double>(last_-first_), 1e-3);
const double sigma = kHeadingFilterM / spacing;
if (sigma <= 1e-12) filter_.push_back(1.0);
else
{
const int radius = static_cast<int>(4.0*sigma + 0.5);
filter_.reserve(static_cast<std::size_t>(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<int>(std::floor((p.x-grid.origin_x)/grid.resolution));
const int y = static_cast<int>(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<std::size_t>(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<std::ptrdiff_t>(index-first_+1), cumulative_.end(), next);
if (it == cumulative_.end()) break;
index = first_ + static_cast<std::size_t>(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<int>(filter_.size()/2);
const int64_t center = static_cast<int64_t>(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<int64_t>(center+k, 0, static_cast<int64_t>(unwrapped_.size()-1));
const double w = filter_[static_cast<std::size_t>(k+radius)];
sum += w*unwrapped_[static_cast<std::size_t>(sample)];
weight += w;
}
return sum/weight;
}
bool connector(const PathPoint& start, const PathPoint& goal, Path* piece, double* edge_score = nullptr)
{
std::pmr::vector<WordChoice> choices(&context_.memory);
const auto& configured = context_.config.corner_radii_m;
const std::array<double, 3> 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<LatticeDubinsWord, 6> 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<std::size_t>(y)*grid.width+static_cast<std::size_t>(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<int>(std::clamp(std::floor(coordinate), 0.0, static_cast<double>(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<std::size_t>(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<double>(context_.smooth_limit - *context_.smooth_checks - estimate))
{
*context_.smooth_checks = context_.smooth_limit;
return false;
}
estimate += static_cast<uint64_t>(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<double> cumulative_;
std::vector<double> unwrapped_;
std::vector<double> filter_;
std::vector<Anchor> 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<double, 2> 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<State> states(&context_.memory);
std::pmr::map<std::pair<std::size_t, int>, 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<int>(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<PathPoint> 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<std::pair<double, double>> choices{{bearing, bearing}};
if (j + 1 != anchor_.size() || context_.request.goal.has_yaw)
{
const std::array<double, 2> 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<PathPoint> 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<int64_t>(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<std::size_t> 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<double, 3> headings{{bearing, anchor_[j].low_yaw, context_.request.goal.yaw}};
std::array<int, 3> 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<std::ptrdiff_t>(used_count), key) != used.begin()+static_cast<std::ptrdiff_t>(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<int64_t>(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<std::ptrdiff_t>(anchor_[n].index),
witness_.begin()+static_cast<std::ptrdiff_t>(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<int64_t>(id), true, std::move(piece));
}
}
}
std::vector<std::size_t> 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<std::size_t> chain;
for (int64_t id = static_cast<int64_t>(goal); id >= 0; id = states[static_cast<std::size_t>(id)].parent)
chain.push_back(static_cast<std::size_t>(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<std::ptrdiff_t>(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<std::ptrdiff_t>(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

View File

@@ -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<float> values(&memory);
std::pmr::vector<uint8_t> 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<uint64_t>(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<uint64_t>(output.info.lattice_peak_bytes, static_cast<uint64_t>(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";

View File

@@ -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<Clock::duration::rep>(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;