Files
lane_route_core/src/route_graph_search.cpp
duongtd 24822f5408 feat(lane_route): add lane_route_core and lane_route_planner (R0 + R1)
lane_route_core plans on a precomputed coarse graph (Voronoi ridges and
direction-zone lanes) and, when enabled, falls back to a weighted A*
search over an SE(2) lattice that enforces forward motion, the minimum
turn radius, end-only spins, the footprint gap and direction zones.

- R0: route_planner.cpp split into graph search, path building and the
  graph tier; regress7 output identical to the previous build.
- R1: lattice tier (lazy packed C-space tiles, direction-aware heuristic
  field, analytic Dubins and point connectors, end-gap floors counting
  unknown cells). Off by default (lattice_enabled = false).
- lane_route_eval takes an optional tier mode and LANE_ROUTE_EVAL_SET
  overrides for offline tuning.

Local snapshot for history only; not pushed.
2026-11-09 13:44:17 +07:00

303 lines
11 KiB
C++

#include "route_planner_internal.h"
#include <algorithm>
#include <array>
#include <chrono>
#include <cmath>
#include <cstddef>
#include <limits>
#include <map>
#include <queue>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <lane_route_core/clothoid.h>
#include <lane_route_core/grid_checks.h>
#include <lane_route_core/swing_chain.h>
namespace lane_route_core
{
namespace detail
{
namespace
{
struct TemporaryLane
{
bool is_start;
uint8_t direction_index;
Point2 entry, exit;
};
/** Trace from an endpoint inside a direction region until it leaves that region. */
std::vector<TemporaryLane> temporaryLanes(const Point2& start, const Point2& goal, const GridRef& grid)
{
std::vector<TemporaryLane> result;
if (grid.direction == nullptr)
return result;
const auto code_at = [&](double x, double y) -> int {
const double fx = std::floor((x - grid.origin_x) / grid.resolution);
const double fy = std::floor((y - grid.origin_y) / grid.resolution);
if (fx < 0.0 || fy < 0.0 || fx >= grid.width || fy >= grid.height)
return -1;
return grid.direction[static_cast<int32_t>(fy) * grid.width + static_cast<int32_t>(fx)];
};
for (bool is_start : { true, false })
{
const Point2 position = is_start ? start : goal;
const int code = code_at(position.x, position.y);
if (code <= 0)
continue;
const double yaw = (code - 1) * kPi / 4.0;
const double ux = std::cos(yaw);
const double uy = std::sin(yaw);
const double sign = is_start ? 1.0 : -1.0;
const double step = grid.resolution * 0.25;
Point2 last = position;
const int limit = 4 * (grid.width + grid.height);
for (int k = 1; k <= limit; ++k)
{
const Point2 trial{ position.x + sign * k * step * ux, position.y + sign * k * step * uy };
if (code_at(trial.x, trial.y) != code)
break;
last = trial;
}
if (distanceOf(position, last) > 1e-8)
{
TemporaryLane lane;
lane.is_start = is_start;
lane.direction_index = static_cast<uint8_t>(code - 1);
lane.entry = is_start ? position : last;
lane.exit = is_start ? last : position;
result.push_back(lane);
}
}
return result;
}
} // namespace
/** Start, goal, temporary lanes and translated lane exits, all as query-only nodes and edges. */
void addQueryEdges(QueryGraph* query, const QueryContext& context, const Point2& start, const Point2& goal, int32_t* start_node,
int32_t* goal_node)
{
const CompiledGraph& base = query->base();
const int32_t base_nodes = query->baseNodes();
const int32_t s = query->addNode(start);
const int32_t g = query->addNode(goal);
*start_node = s;
*goal_node = g;
for (bool is_start : { true, false })
{
const int32_t id = is_start ? s : g;
const Point2 here = is_start ? start : goal;
int accepted = 0;
for (const auto& found : nearestNodes(base.nodes, base_nodes, here, std::min(base_nodes, kStartLinks), kStartRadiusM))
{
const Point2 there = query->node(found.second);
const Point2 a = is_start ? here : there;
const Point2 b = is_start ? there : here;
if (context.lineLegal(a, b))
{
if (is_start)
query->addEdge(id, found.second, { a, b }, EdgeKind::kAttach, found.first);
else
query->addEdge(found.second, id, { a, b }, EdgeKind::kAttach, found.first);
if (++accepted >= kAttachLimit)
break;
}
}
}
if (context.lineLegal(start, goal))
query->addEdge(s, g, { start, goal }, EdgeKind::kDirect, distanceOf(start, goal));
for (const TemporaryLane& lane : temporaryLanes(start, goal, context.grid))
{
const double angle = lane.direction_index * kPi / 4.0;
const double ux = std::cos(angle);
const double uy = std::sin(angle);
const Point2 anchor = lane.is_start ? lane.exit : lane.entry;
Point2 position = anchor;
for (int step = 1; step <= 10; ++step)
{
const double distance = lane.is_start ? 0.25 * step : -0.25 * step;
const Point2 trial{ anchor.x + distance * ux, anchor.y + distance * uy };
const bool legal = lane.is_start ? context.lineLegal(position, trial) : context.lineLegal(trial, position);
if (!legal)
break;
position = trial;
}
const int32_t q = query->addNode(position);
std::vector<Point2> points;
if (lane.is_start)
points = { lane.entry, position };
else
points = { position, lane.exit };
if (!polylineOk(context.grid, points, context.deviation_deg, context.hard_mm))
continue;
const double length = distanceOf(points[0], points[1]);
if (lane.is_start)
query->addEdge(s, q, points, EdgeKind::kTemporaryLane, length);
else
query->addEdge(q, g, points, EdgeKind::kTemporaryLane, length);
int count = 0;
for (const auto& found : nearestNodes(base.nodes, base_nodes, position, std::min(base_nodes, kTemporaryLinks), kTemporaryRadiusM))
{
const Point2 there = query->node(found.second);
const Point2 a = lane.is_start ? position : there;
const Point2 b = lane.is_start ? there : position;
if (context.lineLegal(a, b))
{
if (lane.is_start)
query->addEdge(q, found.second, { a, b }, EdgeKind::kAttach, found.first);
else
query->addEdge(found.second, q, { a, b }, EdgeKind::kAttach, found.first);
if (++count >= kAttachLimit)
break;
}
}
}
// A goal close to a lane exit: translate the whole lane parallel to itself so its straight passes through the goal.
// The direction grid and live clearance still decide every segment.
std::set<std::pair<int64_t, int64_t>> seen;
for (const GraphEdge& edge : base.edges)
{
if (context.cancel && context.cancel->load(std::memory_order_relaxed)) return;
if (edge.kind != EdgeKind::kLane)
continue;
const Point2& a = edge.points.front();
const Point2& b = edge.points.back();
const double length = distanceOf(a, b);
if (length < 1.0)
continue;
const double dx = (b.x - a.x) / length;
const double dy = (b.y - a.y) / length;
const double offset = (goal.x - a.x) * -dy + (goal.y - a.y) * dx;
const double along = (goal.x - b.x) * dx + (goal.y - b.y) * dy;
if (std::abs(offset) > 1.5 || along < -2.5 || along > 2.5)
continue;
const Point2 entry{ a.x + offset * -dy, a.y + offset * dx };
const std::pair<int64_t, int64_t> key(static_cast<int64_t>(std::rint(entry.x * 100.0)), static_cast<int64_t>(std::rint(entry.y * 100.0)));
if (!seen.insert(key).second || !context.lineLegal(entry, goal))
continue;
const int32_t q = query->addNode(entry);
query->addEdge(q, g, { entry, goal }, EdgeKind::kTemporaryLane, distanceOf(entry, goal));
for (const auto& found : nearestNodes(base.nodes, base_nodes, entry, std::min(base_nodes, kTranslatedLinks), kTemporaryRadiusM))
{
const Point2 there = query->node(found.second);
if (context.lineLegal(there, entry))
query->addEdge(found.second, q, { there, entry }, EdgeKind::kAttach, found.first);
}
}
}
namespace
{
/** Only a fixed lane-to-lane turn can be rejected by this map-wide bound: even a full-map straight could not fit the trim. */
bool turnProvablyImpossible(const GraphEdge& previous, const GraphEdge& current, double max_straight_m, double min_radius_m)
{
if (!isLocked(previous.kind) || !isLocked(current.kind))
return false;
const std::vector<Point2>& p = previous.points;
const double turn = std::abs(wrapAngle(headingOf(current.points[0], current.points[1]) - headingOf(p[p.size() - 2], p[p.size() - 1])));
return turn > 1e-8 && min_radius_m * std::tan(turn / 2.0) > max_straight_m;
}
} // namespace
/** Least-cost route over (node, incoming edge), so a turn penalty can apply. */
bool searchRoute(const QueryGraph& query, int32_t start, int32_t goal, const std::vector<uint8_t>& blocked,
const std::set<std::pair<int32_t, int32_t>>& blocked_pairs, double max_straight_m, double min_radius_m,
const std::vector<double>& factors, std::vector<int32_t>* route, const std::atomic<bool>* cancel)
{
const auto key_of = [](int32_t node, int32_t previous) {
return (static_cast<uint64_t>(static_cast<uint32_t>(node)) << 32) | static_cast<uint32_t>(previous + 1);
};
struct Entry
{
double score;
uint64_t serial;
int32_t node, previous;
bool operator>(const Entry& other) const
{
return score != other.score ? score > other.score : serial > other.serial;
}
};
std::priority_queue<Entry, std::vector<Entry>, std::greater<Entry>> queue;
std::unordered_map<uint64_t, double> best;
std::unordered_map<uint64_t, std::pair<uint64_t, int32_t>> parent;
best.reserve(8192);
parent.reserve(8192);
queue.push({ 0.0, 0, start, -1 });
best[key_of(start, -1)] = 0.0;
uint64_t serial = 1;
bool reached = false;
uint64_t final_key = 0;
while (!queue.empty())
{
if (cancel && cancel->load(std::memory_order_relaxed)) return false;
const Entry top = queue.top();
queue.pop();
const uint64_t key = key_of(top.node, top.previous);
if (top.score != best[key])
continue;
if (top.node == goal)
{
reached = true;
final_key = key;
break;
}
double previous_angle = 0.0;
if (top.previous >= 0)
{
const std::vector<Point2>& p = query.edge(top.previous).points;
previous_angle = headingOf(p[p.size() - 2], p[p.size() - 1]);
}
query.forOutgoing(top.node, [&](int32_t index) {
if (blocked[static_cast<std::size_t>(index)] != 0)
return;
const GraphEdge& edge = query.edge(index);
if (edge.to == top.node || blocked_pairs.count({ top.previous, index }) != 0)
return;
const double angle = headingOf(edge.points[0], edge.points[1]);
const double turn = top.previous < 0 ? 0.0 : std::abs(wrapAngle(angle - previous_angle));
if (top.previous >= 0 && turnProvablyImpossible(query.edge(top.previous), edge, max_straight_m, min_radius_m))
return;
const double weight = edge.kind == EdgeKind::kVoronoi ? kVoronoiWeight : 1.0;
const double traversal = edge.cost * weight * factors[static_cast<std::size_t>(index)];
if (!std::isfinite(traversal))
return;
const double next = top.score + traversal + kTurnWeight * turn;
const uint64_t next_key = key_of(edge.to, index);
const auto known = best.find(next_key);
if (known != best.end() && next >= known->second)
return;
best[next_key] = next;
parent[next_key] = { key, index };
queue.push({ next, serial++, edge.to, index });
});
}
if (!reached)
return false;
route->clear();
uint64_t cursor = final_key;
while (static_cast<int32_t>(cursor >> 32) != start)
{
const auto step = parent.at(cursor);
route->push_back(step.second);
cursor = step.first;
}
std::reverse(route->begin(), route->end());
return true;
}
} // namespace detail
} // namespace lane_route_core