feat(lane_route_core): follow preferred lanes, fail fast on blocked goals, allow_unknown (R2.14)

- Start and goal attach to the middle of nearby edges: query-time split points
  (projection and +-1.5 m) on up to 6 directed edges within 3 m, plus up to 4
  preferred edges within 8 m. The compiled graph is unchanged; retries block the
  parent edge.
- Preferred lanes join each other and split nodes; lane ends are protected from
  swing merging, and turns next to a preferred ridge are not penalised. Hard
  rules (forward only, radius, 30 mm gap) are unchanged.
- Goal footprint on a lethal cell returns goal_in_obstacle before any search;
  on unknown it returns goal_in_unknown unless allow_unknown.
- allow_unknown (default false): when true every planner check treats unknown
  as free. The reference graph from robot_costmap_2d still skips unknown.

SEHC replay: lane metres m4 0.3 -> 13.3, m7 1.1 -> 13.8, m8 0.4 -> 26.4.
Random near-lane 190/200 both; NVC 316/316; regress7 3418 (4 losses all solve
when run alone); m15 31.0 m 8/8; independent recheck 0 violations. 146 tests.
This commit is contained in:
2026-11-20 16:30:47 +07:00
parent 07bffab7fa
commit 94475098a2
17 changed files with 695 additions and 64 deletions

View File

@@ -62,7 +62,7 @@ double edgeFactor(const std::vector<Point2>& points, const uint8_t* master, cons
/** @brief Traversal factors of all compiled edges from its stored sample cells.
* @param factors Output, resized to graph.edges.size(). */
void compiledEdgeFactors(const CompiledGraph& graph, const uint8_t* master, std::vector<double>* factors);
void compiledEdgeFactors(const CompiledGraph& graph, const uint8_t* master, std::vector<double>* factors, bool allow_unknown = false);
} // namespace lane_route_core

View File

@@ -26,6 +26,9 @@ bool polylineOk(const GridRef& grid, const std::vector<Point2>& points, double d
/** @brief Rectangle against lethal and unknown cell squares. Leaving the grid or a blocked centre cell also counts. */
bool footprintCollides(const GridRef& grid, double x, double y, double yaw, double half_x, double half_y);
/** @brief Whether the rectangle overlaps a cell of exactly the given cost. */
bool footprintOverlapsCost(const GridRef& grid, double x, double y, double yaw, double half_x, double half_y, uint8_t cost);
/** @brief Traversal factor of a master costmap value. Inflation stays 1: the graph's clearance term covers it. */
double costFactor(uint8_t value);
@@ -84,8 +87,7 @@ struct GapCheck
* until the path first reaches it, the gap may not drop more than 1 mm below that end pose. */
GapCheck checkFootprintGap(const Path& path, const GridRef& grid, double minimum_m, double half_x, double half_y,
const std::atomic<bool>* cancel = nullptr);
/** @param count_unknown Also measure the gap to unknown cells. Both planner tiers pass true (graph tier since R2.8, user ruling
* 10/11: an unknown cell is an obstacle for the 30 mm gap); false is kept for callers that only care about lethal cells. */
/** @param count_unknown Measure the gap to unknown cells unless grid.allow_unknown is true. */
GapCheck checkFootprintGap(const Path& path, const GridRef& grid, double minimum_m, double half_x, double half_y,
const std::atomic<bool>* cancel, const std::chrono::steady_clock::time_point* deadline,
bool count_unknown = false);

View File

@@ -72,6 +72,8 @@ struct PlanInfo
double rung_used_deg = -1.0; ///< Direction limit that produced the path, -1 on failure.
std::vector<std::string> rung_reasons;
int retries = 0; ///< Route retries over all passes and rungs.
int query_nodes_added = 0; ///< Query-only nodes in the most recent graph pass.
int query_edges_added = 0; ///< Query-only edges in the most recent graph pass.
int gap_failures = 0; ///< Candidate paths below the footprint gap.
bool soft_cost_ignored = false; ///< The path came from the pass that ignores soft cost values.
std::string live_ridge; ///< "", "used", "failed" or "skipped_size": retry on a ridge from the live grid.

View File

@@ -59,8 +59,14 @@ struct GridRef
const uint8_t* cost = nullptr; ///< Master costmap values, see the constants above.
const uint16_t* clearance_mm = nullptr; ///< [mm] Distance to the nearest lethal cell, rounded down.
const uint8_t* direction = nullptr; ///< May be null. 0 unconstrained, 1..8 direction index + 1, CCW from +X.
bool allow_unknown = false; ///< Treat unknown cells as free for planner checks.
};
inline bool blockedCost(uint8_t value, const GridRef& grid, uint8_t threshold = kInscribedCost)
{
return value >= threshold && !(grid.allow_unknown && value == kNoInformation);
}
/** @brief Undirected ridge segment from the coarse graph. */
struct CoarseEdge
{
@@ -100,6 +106,7 @@ struct RidgeBackend
/** @brief Planner parameters. Lengths [m], angles [deg]. Defaults match the approved SEHC simulation margins. */
struct PlannerConfig
{
bool allow_unknown = false; ///< Permit planning through unknown cells when true.
double half_x_m = 0.30; ///< Footprint rectangle half length.
double half_y_m = 0.30; ///< Footprint rectangle half width.
double clearance_hard_m = 0.335; ///< Centre clearance on every graph line.

View File

@@ -70,12 +70,12 @@ void forEachSample(const std::vector<Point2>& points, const GridRef& grid, bool
class FactorSum
{
public:
void add(int32_t cell, double weight, const uint8_t* master)
void add(int32_t cell, double weight, const uint8_t* master, bool allow_unknown)
{
const uint8_t value = cell >= 0 ? master[cell] : kNoInformation;
cost_ += weight * costFactor(value);
length_ += weight;
blocked_ = blocked_ || value >= kInscribedCost;
blocked_ = blocked_ || cell < 0 || (value >= kInscribedCost && !(allow_unknown && value == kNoInformation));
}
double factor() const
{
@@ -94,25 +94,27 @@ private:
double edgeFactor(const std::vector<Point2>& points, const uint8_t* master, const GridRef& grid)
{
FactorSum sum;
forEachSample(points, grid, false, [&](int32_t cell, double weight, double) { sum.add(cell, weight, master); });
forEachSample(points, grid, false, [&](int32_t cell, double weight, double) { sum.add(cell, weight, master, grid.allow_unknown); });
return sum.factor();
}
void compiledEdgeFactors(const CompiledGraph& graph, const uint8_t* master, std::vector<double>* factors)
void compiledEdgeFactors(const CompiledGraph& graph, const uint8_t* master, std::vector<double>* factors, bool allow_unknown)
{
factors->resize(graph.edges.size());
for (std::size_t i = 0; i < graph.edges.size(); ++i)
{
FactorSum sum;
for (int32_t k = graph.sample_offsets[i]; k < graph.sample_offsets[i + 1]; ++k)
sum.add(graph.sample_cells[static_cast<std::size_t>(k)], graph.sample_weights[static_cast<std::size_t>(k)], master);
sum.add(graph.sample_cells[static_cast<std::size_t>(k)], graph.sample_weights[static_cast<std::size_t>(k)], master, allow_unknown);
(*factors)[i] = sum.factor();
}
}
CompiledGraph compileGraph(const CoarseGraph& coarse, const GridRef& grid, const uint8_t* master, double deviation_deg,
CompiledGraph compileGraph(const CoarseGraph& coarse, const GridRef& grid_input, const uint8_t* master, double deviation_deg,
const PlannerConfig& config, const RidgeBackend& backend, const std::atomic<bool>* cancel)
{
GridRef grid = grid_input;
grid.allow_unknown = config.allow_unknown;
const auto cancelled = [cancel]() { return cancel && cancel->load(std::memory_order_relaxed); };
if (cancelled()) return {};
const int hard_mm = clearanceThresholdMm(config.clearance_hard_m);
@@ -259,7 +261,7 @@ CompiledGraph compileGraph(const CoarseGraph& coarse, const GridRef& grid, const
for (std::size_t i = 0; i < cell_count; ++i)
{
if ((i & 4095u) == 0 && cancelled()) return {};
mask[i] = master[i] == kPreferredSpace && grid.cost[i] < kInscribedCost ? 1 : 0;
mask[i] = master[i] == kPreferredSpace && !blockedCost(grid.cost[i], grid) ? 1 : 0;
}
std::vector<Point2> preferred_nodes;
std::vector<CoarseEdge> preferred_edges;
@@ -270,6 +272,70 @@ CompiledGraph compileGraph(const CoarseGraph& coarse, const GridRef& grid, const
graph.nodes.insert(graph.nodes.end(), preferred_nodes.begin(), preferred_nodes.end());
for (const CoarseEdge& edge : preferred_edges)
add_both_ways(base + edge.from, base + edge.to, edge.points, EdgeKind::kPreferredRidge);
// A strip can end beside the middle of another strip; their endpoints alone do not expose that junction.
struct PreferredBridge { double distance; std::size_t edge, segment; Point2 point; };
for (std::size_t local = 0; local < preferred_nodes.size(); ++local)
{
if (cancelled()) return {};
const Point2 here = preferred_nodes[local];
std::vector<PreferredBridge> candidates;
for (std::size_t e = 0; e < preferred_edges.size(); ++e)
{
const CoarseEdge& edge = preferred_edges[e];
if (edge.from == static_cast<int32_t>(local) || edge.to == static_cast<int32_t>(local)) continue;
double best = kPreferredAttachRadiusM;
std::size_t segment = 0;
Point2 foot{};
for (std::size_t i = 1; i < edge.points.size(); ++i)
{
const Point2& a = edge.points[i-1];
const Point2& b = edge.points[i];
const double dx = b.x - a.x, dy = b.y - a.y, squared = dx * dx + dy * dy;
if (squared < 1e-12) continue;
const double t = std::clamp(((here.x - a.x) * dx + (here.y - a.y) * dy) / squared, 0.0, 1.0);
const Point2 point{a.x + t * dx, a.y + t * dy};
const double distance = distanceOf(here, point);
if (distance < best) { best = distance; segment = i; foot = point; }
}
if (segment != 0 && best >= kMinLinkM && best <= 3.0 &&
distanceOf(foot, edge.points.front()) >= kMinLinkM && distanceOf(foot, edge.points.back()) >= kMinLinkM)
candidates.push_back({best, e, segment, foot});
}
std::sort(candidates.begin(), candidates.end(), [](const PreferredBridge& a, const PreferredBridge& b) {
return a.distance != b.distance ? a.distance < b.distance : a.edge < b.edge;
});
if (candidates.size() > 4) candidates.resize(4);
for (const PreferredBridge& bridge : candidates)
{
const bool forward = line_ok(here, bridge.point), reverse = line_ok(bridge.point, here);
if (!forward && !reverse) continue;
const CoarseEdge& edge = preferred_edges[bridge.edge];
const int32_t split = add_node(bridge.point);
std::vector<Point2> first(edge.points.begin(), edge.points.begin() + static_cast<std::ptrdiff_t>(bridge.segment));
std::vector<Point2> second{bridge.point};
if (distanceOf(first.back(), bridge.point) > 1e-8) first.push_back(bridge.point);
second.insert(second.end(), edge.points.begin() + static_cast<std::ptrdiff_t>(bridge.segment), edge.points.end());
if (distanceOf(second[0], second[1]) < 1e-8) second.erase(second.begin() + 1);
if (first.size() >= 2) add_both_ways(base + edge.from, split, first, EdgeKind::kPreferredRidge);
if (second.size() >= 2) add_both_ways(split, base + edge.to, second, EdgeKind::kPreferredRidge);
if (forward) graph.edges.push_back({base + static_cast<int32_t>(local), split, {here, bridge.point}, EdgeKind::kPreferredAttach, bridge.distance});
if (reverse) graph.edges.push_back({split, base + static_cast<int32_t>(local), {bridge.point, here}, EdgeKind::kPreferredAttach, bridge.distance});
}
}
for (std::size_t local = 0; local < preferred_nodes.size(); ++local)
{
if (cancelled()) return {};
const Point2 here = preferred_nodes[local];
for (const auto& found : nearestNodes(preferred_nodes, static_cast<int32_t>(preferred_nodes.size()), here,
std::min<int32_t>(8, preferred_nodes.size()), 3.0))
{
if (found.second == static_cast<int32_t>(local) || found.first < kMinLinkM) continue;
const Point2 there = preferred_nodes[static_cast<std::size_t>(found.second)];
if (line_ok(here, there))
graph.edges.push_back({base + static_cast<int32_t>(local), base + found.second,
{here, there}, EdgeKind::kPreferredAttach, found.first});
}
}
if (base > 0)
{
for (std::size_t local = 0; local < preferred_nodes.size(); ++local)

View File

@@ -187,7 +187,7 @@ bool lineOk(const GridRef& grid, const Point2& a, const Point2& b, double deviat
int32_t cell = 0;
if (!cellOf(grid, a.x + dx * t, a.y + dy * t, &cell))
return false;
if (grid.cost[cell] >= kInscribedCost || grid.clearance_mm[cell] < min_clearance_mm)
if (blockedCost(grid.cost[cell], grid) || grid.clearance_mm[cell] < min_clearance_mm)
return false;
if (grid.direction != nullptr)
{
@@ -217,7 +217,9 @@ bool polylineOk(const GridRef& grid, const std::vector<Point2>& points, double d
return true;
}
bool footprintCollides(const GridRef& grid, double x, double y, double yaw, double half_x, double half_y)
namespace
{
bool footprintCheck(const GridRef& grid, double x, double y, double yaw, double half_x, double half_y, int exact_cost)
{
const double c = std::cos(yaw);
const double s = std::sin(yaw);
@@ -231,18 +233,20 @@ bool footprintCollides(const GridRef& grid, double x, double y, double yaw, doub
const double high_x = std::floor((x + reach_x - grid.origin_x) / resolution);
const double low_y = std::floor((y - reach_y - grid.origin_y) / resolution);
const double high_y = std::floor((y + reach_y - grid.origin_y) / resolution);
if (low_x < 0.0 || low_y < 0.0 || high_x >= grid.width || high_y >= grid.height)
if (exact_cost < 0 && (low_x < 0.0 || low_y < 0.0 || high_x >= grid.width || high_y >= grid.height))
return true;
int32_t centre = 0;
if (!cellOf(grid, x, y, &centre) || grid.cost[centre] >= kInscribedCost)
if (exact_cost < 0 && (!cellOf(grid, x, y, &centre) || blockedCost(grid.cost[centre], grid)))
return true;
if (high_x < 0.0 || high_y < 0.0 || low_x >= grid.width || low_y >= grid.height)
return false;
const double projected = half_cell * (abs_c + abs_s);
for (int32_t iy = static_cast<int32_t>(low_y); iy <= static_cast<int32_t>(high_y); ++iy)
for (int32_t iy = static_cast<int32_t>(std::max(0.0, low_y)); iy <= static_cast<int32_t>(std::min(double(grid.height - 1), high_y)); ++iy)
{
const uint8_t* row = grid.cost + static_cast<std::ptrdiff_t>(iy) * grid.width;
for (int32_t ix = static_cast<int32_t>(low_x); ix <= static_cast<int32_t>(high_x); ++ix)
for (int32_t ix = static_cast<int32_t>(std::max(0.0, low_x)); ix <= static_cast<int32_t>(std::min(double(grid.width - 1), high_x)); ++ix)
{
if (row[ix] < kLethalCost)
if (exact_cost < 0 ? !blockedCost(row[ix], grid, kLethalCost) : row[ix] != exact_cost)
continue;
const double dx = grid.origin_x + (ix + 0.5) * resolution - x;
const double dy = grid.origin_y + (iy + 0.5) * resolution - y;
@@ -253,6 +257,17 @@ bool footprintCollides(const GridRef& grid, double x, double y, double yaw, doub
}
return false;
}
} // namespace
bool footprintCollides(const GridRef& grid, double x, double y, double yaw, double half_x, double half_y)
{
return footprintCheck(grid, x, y, yaw, half_x, half_y, -1);
}
bool footprintOverlapsCost(const GridRef& grid, double x, double y, double yaw, double half_x, double half_y, uint8_t cost)
{
return footprintCheck(grid, x, y, yaw, half_x, half_y, cost);
}
double costFactor(uint8_t value)
{
@@ -282,7 +297,7 @@ double lineCost(const Point2& a, const Point2& b, const uint8_t* master, const G
{
const double t = (i + 0.5) / samples;
int32_t cell = 0;
if (!cellOf(grid, a.x + dx * t, a.y + dy * t, &cell) || master[cell] >= kInscribedCost)
if (!cellOf(grid, a.x + dx * t, a.y + dy * t, &cell) || blockedCost(master[cell], grid))
return kInfinity;
sum += costFactor(master[cell]);
}
@@ -414,7 +429,7 @@ bool enclosedByObstacles(const GridRef& grid, const Point2& start, const Point2&
int32_t from = 0, to = 0;
if (!cellOf(grid, start.x, start.y, &from) || !cellOf(grid, goal.x, goal.y, &to))
return false;
if (grid.cost[from] >= kInscribedCost || grid.cost[to] >= kInscribedCost)
if (blockedCost(grid.cost[from], grid) || blockedCost(grid.cost[to], grid))
return false;
if (from == to)
return false;
@@ -433,7 +448,7 @@ bool enclosedByObstacles(const GridRef& grid, const Point2& start, const Point2&
for (int32_t x = std::max(cx - 1, 0); x <= std::min(cx + 1, grid.width - 1); ++x)
{
const int32_t other = y * grid.width + x;
if (visited[static_cast<std::size_t>(other)] != 0 || grid.cost[other] >= kInscribedCost)
if (visited[static_cast<std::size_t>(other)] != 0 || blockedCost(grid.cost[other], grid))
continue;
if (other == to)
return false;
@@ -452,7 +467,7 @@ bool detail::shortestStandableReference(const GridRef& grid, const Point2& start
int32_t from = 0, to = 0;
if (!cellOf(grid, start.x, start.y, &from) || !cellOf(grid, goal.x, goal.y, &to))
return false;
if (grid.cost[from] >= kInscribedCost || grid.cost[to] >= kInscribedCost)
if (blockedCost(grid.cost[from], grid) || blockedCost(grid.cost[to], grid))
return false;
const int32_t width = grid.width;
const double resolution = grid.resolution;
@@ -721,7 +736,7 @@ GapCheck checkFootprintGap(const Path& path, const GridRef& grid, double minimum
const double centre_y = grid.origin_y + (iy + 0.5) * resolution;
for (int32_t ix = x0; ix <= x1; ++ix)
{
if (row[ix] != kLethalCost && !(count_unknown && row[ix] == kNoInformation))
if (row[ix] != kLethalCost && !(count_unknown && !grid.allow_unknown && row[ix] == kNoInformation))
continue;
const double centre_x = grid.origin_x + (ix + 0.5) * resolution;
const double dx = centre_x - pose.x;

View File

@@ -186,7 +186,7 @@ bool LatticeCSpace::buildBlockedPrefix()
uint32_t row = 0;
for (std::size_t x = 0; x < width; ++x)
{
if (g.cost[y * width + x] >= kLethalCost) ++row;
if (blockedCost(g.cost[y * width + x], g, kLethalCost)) ++row;
blocked_prefix_[(y + 1) * stride + x + 1] = blocked_prefix_[y * stride + x + 1] + row;
}
}
@@ -213,7 +213,7 @@ bool LatticeCSpace::poseFree(double x, double y, double yaw, double sweep_margin
if (!(fx >= 0.0 && fy >= 0.0 && fx < g.width && fy < g.height)) return false;
const int32_t ix = static_cast<int32_t>(fx), iy = static_cast<int32_t>(fy);
const std::size_t cell = static_cast<std::size_t>(iy) * static_cast<std::size_t>(g.width) + static_cast<std::size_t>(ix);
if (g.cost[cell] >= kInscribedCost ||
if (blockedCost(g.cost[cell], g) ||
((g.direction == nullptr || g.direction[cell] == 0) && g.clearance_mm[cell] < clearanceThresholdMm(c.clearance_min_m)))
return false;
const Pose2& start = context_.request.start;
@@ -332,7 +332,7 @@ bool LatticeCSpace::segmentLegal(const PathPoint& a, const PathPoint& b)
if (!hitsCell(x0, y0, x1, y1, x, y, padding)) continue;
const std::size_t cell = static_cast<std::size_t>(y) * g.width + x;
const uint8_t code = g.direction == nullptr ? 0 : g.direction[cell];
if (g.cost[cell] >= kInscribedCost || (code == 0 &&
if (blockedCost(g.cost[cell], g) || (code == 0 &&
g.clearance_mm[cell] < clearanceThresholdMm(context_.config.clearance_min_m))) return false;
if (code != 0)
{

View File

@@ -314,7 +314,7 @@ private:
{
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;
if (blockedCost(g.cost[cell], g)) 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)

View File

@@ -337,9 +337,11 @@ PathCheck verifyPath(const Path& path, const GridRef& grid, double deviation_deg
return verifyPath(path, grid, deviation_deg, config, cancel, nullptr);
}
PathCheck verifyPath(const Path& path, const GridRef& grid, double deviation_deg, const PlannerConfig& config,
PathCheck verifyPath(const Path& path, const GridRef& grid_input, double deviation_deg, const PlannerConfig& config,
const std::atomic<bool>* cancel, const std::chrono::steady_clock::time_point* deadline)
{
GridRef grid = grid_input;
grid.allow_unknown = config.allow_unknown;
PathCheck check;
if (path.size() < 2)
return check;

View File

@@ -40,16 +40,19 @@ RawChain routeRawChain(const QueryGraph& query, const std::vector<int32_t>& rout
{
const GraphEdge& edge = query.edge(route[edge_index]);
const bool lock = isLocked(edge.kind);
for (const Point2& point : edge.points)
for (std::size_t point_index = 0; point_index < edge.points.size(); ++point_index)
{
const Point2& point = edge.points[point_index];
const bool preferred_end = edge.kind == EdgeKind::kPreferredRidge &&
(point_index == 0 || point_index + 1 == edge.points.size());
if (!raw.vertices.empty() && distanceOf(raw.vertices.back(), point) < 1e-7)
{
if (lock)
if (lock || preferred_end)
raw.locked.back() = 1;
continue;
}
raw.vertices.push_back(point);
raw.locked.push_back(lock ? 1 : 0);
raw.locked.push_back(lock || preferred_end ? 1 : 0);
}
if (edge_index + 1 < route.size())
raw.boundaries.emplace_back(raw.vertices.size() - 1, edge_index);
@@ -184,7 +187,7 @@ bool kinkLegal(const Point2& vertex, double from, double to, const QueryContext&
const double fy = std::floor((vertex.y - grid.origin_y) / grid.resolution);
if (fx < 0.0 || fy < 0.0 || fx >= grid.width || fy >= grid.height)
return false;
if (grid.cost[static_cast<std::size_t>(fy) * grid.width + static_cast<std::size_t>(fx)] >= kInscribedCost)
if (blockedCost(grid.cost[static_cast<std::size_t>(fy) * grid.width + static_cast<std::size_t>(fx)], grid))
return false;
const double delta = wrapAngle(to - from);
const int samples = std::max(1, static_cast<int>(std::ceil(std::abs(delta) / 0.03)));
@@ -209,7 +212,7 @@ bool curveLegal(const Path& curve, const QueryContext& context)
if (fx < 0.0 || fy < 0.0 || fx >= grid.width || fy >= grid.height)
return false;
cells[i] = static_cast<int32_t>(fy) * grid.width + static_cast<int32_t>(fx);
if (grid.cost[cells[i]] >= kInscribedCost)
if (blockedCost(grid.cost[cells[i]], grid))
return false;
}
for (std::size_t i = 0; i < curve.size(); ++i)
@@ -497,7 +500,9 @@ std::vector<Point2> mergeSwings(const std::vector<Point2>& vertices, const Query
if (turn(merged, j) * turn(merged, j + 1) >= 0.0)
continue;
std::vector<Point2> candidate;
const bool crossing = repairCorner(merged, static_cast<int>(j), context, &candidate) &&
const bool crossing = protected_points.count({merged[j].x, merged[j].y}) == 0 &&
protected_points.count({merged[j+1].x, merged[j+1].y}) == 0 &&
repairCorner(merged, static_cast<int>(j), context, &candidate) &&
verticesLength(candidate) <= verticesLength(merged) + 1e-6;
if (!crossing && !skipSwingVertices(merged, j, context, protected_points, tiers[1], &candidate))
continue;
@@ -728,6 +733,11 @@ Candidate constructCandidate(const std::vector<int32_t>& route, const QueryGraph
if (isLocked(edge.kind))
for (const Point2& point : edge.points)
protected_points.insert({ point.x, point.y });
if (edge.kind == EdgeKind::kPreferredRidge)
{
protected_points.insert({edge.points.front().x, edge.points.front().y});
protected_points.insert({edge.points.back().x, edge.points.back().y});
}
}
std::vector<Point2> greedy;
Candidate result = constructGreedyCandidate(route, query, context, master, start, goal, shortcut_minimum_m, protected_points, &greedy);

View File

@@ -32,6 +32,122 @@ struct TemporaryLane
Point2 entry, exit;
};
struct EdgeProjection
{
int32_t edge;
double along;
double distance;
bool start;
};
/** Add bounded query-only portions of nearby directed edges, preserving their polyline geometry. */
void addEdgeSplits(QueryGraph* query, const QueryContext& context, const Point2& start, const Point2& goal,
int32_t start_node, int32_t goal_node)
{
const auto& edges = query->base().edges;
std::map<int32_t, std::vector<EdgeProjection>> selected;
for (bool is_start : {true, false})
{
const Point2 here = is_start ? start : goal;
std::vector<EdgeProjection> nearest;
std::vector<EdgeProjection> preferred;
for (int32_t id = 0; id < query->baseEdges(); ++id)
{
if (context.expired()) return;
const auto& points = edges[static_cast<std::size_t>(id)].points;
double traversed = 0.0, best = kInfinity, along = 0.0;
for (std::size_t i = 1; i < points.size(); ++i)
{
const double dx = points[i].x - points[i-1].x, dy = points[i].y - points[i-1].y;
const double length = std::hypot(dx, dy);
if (length < 1e-9) continue;
const double t = std::clamp(((here.x - points[i-1].x) * dx + (here.y - points[i-1].y) * dy) / (length * length), 0.0, 1.0);
const double d = std::hypot(here.x - points[i-1].x - t * dx, here.y - points[i-1].y - t * dy);
if (d < best) { best = d; along = traversed + t * length; }
traversed += length;
}
if (best <= kSplitRadiusM && traversed > 1e-6)
nearest.push_back({id, along, best, is_start});
if (edges[static_cast<std::size_t>(id)].kind == EdgeKind::kPreferredRidge &&
best <= kPreferredSplitRadiusM && traversed > 1e-6)
preferred.push_back({id, along, best, is_start});
}
std::sort(nearest.begin(), nearest.end(), [](const EdgeProjection& a, const EdgeProjection& b) {
return a.distance != b.distance ? a.distance < b.distance : a.edge < b.edge;
});
if (nearest.size() > static_cast<std::size_t>(kSplitEdgeLimit)) nearest.resize(kSplitEdgeLimit);
std::sort(preferred.begin(), preferred.end(), [](const EdgeProjection& a, const EdgeProjection& b) {
return a.distance != b.distance ? a.distance < b.distance : a.edge < b.edge;
});
if (preferred.size() > static_cast<std::size_t>(kPreferredSplitEdgeLimit)) preferred.resize(kPreferredSplitEdgeLimit);
for (const auto& candidate : nearest) selected[candidate.edge].push_back(candidate);
for (const auto& candidate : preferred)
if (std::none_of(nearest.begin(), nearest.end(), [&](const EdgeProjection& other) { return other.edge == candidate.edge; }))
selected[candidate.edge].push_back(candidate);
}
for (const auto& entry : selected)
{
const int32_t parent = entry.first;
const GraphEdge& edge = edges[static_cast<std::size_t>(parent)];
std::vector<double> offsets(edge.points.size(), 0.0);
for (std::size_t i = 1; i < edge.points.size(); ++i)
offsets[i] = offsets[i-1] + distanceOf(edge.points[i-1], edge.points[i]);
const double total = offsets.back();
struct Split { double along; bool start; bool goal; };
std::vector<Split> splits;
for (const auto& projection : entry.second)
for (double shift : {-kSplitOffsetM, 0.0, kSplitOffsetM})
{
const double along = std::clamp(projection.along + shift, 0.0, total);
if (along <= 1e-6 || along >= total - 1e-6) continue;
splits.push_back({along, projection.start, !projection.start});
}
std::sort(splits.begin(), splits.end(), [](const Split& a, const Split& b) { return a.along < b.along; });
std::vector<Split> unique;
for (const auto& split : splits)
{
if (!unique.empty() && split.along - unique.back().along < 1e-6)
{
unique.back().start |= split.start;
unique.back().goal |= split.goal;
}
else unique.push_back(split);
}
if (unique.empty()) continue;
const auto point_at = [&](double along) {
const auto upper = std::upper_bound(offsets.begin(), offsets.end(), along);
const std::size_t i = std::min<std::size_t>(edge.points.size() - 1, upper - offsets.begin());
if (i == 0) return edge.points.front();
const double span = offsets[i] - offsets[i-1];
const double t = span > 0.0 ? (along - offsets[i-1]) / span : 0.0;
return Point2{edge.points[i-1].x + t * (edge.points[i].x - edge.points[i-1].x),
edge.points[i-1].y + t * (edge.points[i].y - edge.points[i-1].y)};
};
int32_t previous = edge.from;
double before = 0.0;
for (std::size_t i = 0; i <= unique.size(); ++i)
{
const double after = i == unique.size() ? total : unique[i].along;
const Point2 point = point_at(after);
const int32_t next = i == unique.size() ? edge.to : query->addNode(point);
std::vector<Point2> part{point_at(before)};
for (std::size_t j = 1; j + 1 < edge.points.size(); ++j)
if (offsets[j] > before + 1e-8 && offsets[j] < after - 1e-8) part.push_back(edge.points[j]);
part.push_back(point);
query->addEdge(previous, next, std::move(part), edge.kind, edge.cost * (after - before) / total, parent);
if (i < unique.size())
{
if (unique[i].start && distanceOf(start, point) > 1e-6 && context.lineLegal(start, point))
query->addEdge(start_node, next, {start, point}, EdgeKind::kAttach, distanceOf(start, point));
if (unique[i].goal && distanceOf(point, goal) > 1e-6 && context.lineLegal(point, goal))
query->addEdge(next, goal_node, {point, goal}, EdgeKind::kAttach, distanceOf(point, goal));
}
previous = next;
before = after;
}
}
}
/** 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)
{
@@ -82,7 +198,7 @@ std::vector<TemporaryLane> temporaryLanes(const Point2& start, const Point2& goa
/** 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)
int32_t* goal_node, bool split_edges)
{
const CompiledGraph& base = query->base();
const int32_t base_nodes = query->baseNodes();
@@ -91,6 +207,8 @@ void addQueryEdges(QueryGraph* query, const QueryContext& context, const Point2&
*start_node = s;
*goal_node = g;
if (split_edges) addEdgeSplits(query, context, start, goal, s, g);
for (bool is_start : { true, false })
{
const int32_t id = is_start ? s : g;
@@ -263,7 +381,7 @@ bool searchRoute(const QueryGraph& query, int32_t start, int32_t goal, const std
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)
if (edge.to == top.node || blocked_pairs.count({ query.parentEdge(top.previous), query.parentEdge(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));
@@ -274,7 +392,10 @@ bool searchRoute(const QueryGraph& query, int32_t start, int32_t goal, const std
if (edge.zone_deviation_cost != 0.0) traversal += edge.zone_deviation_cost;
if (!std::isfinite(traversal))
return;
const double next = top.score + traversal + kTurnWeight * turn;
// A preference may be worth entering even when its short entry and exit add turns.
const bool preferred_turn = edge.kind == EdgeKind::kPreferredRidge ||
(top.previous >= 0 && query.edge(top.previous).kind == EdgeKind::kPreferredRidge);
const double next = top.score + traversal + (preferred_turn ? 0.0 : 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)

View File

@@ -45,7 +45,8 @@ double segmentDistanceSquared(const Point2& p, const Point2& a, const Point2& b)
/** Route graph, then the same without soft cost values. Hard rules hold in both passes. */
bool planCore(const CompiledGraph& graph, const Pose2& start, const Pose2& goal, const GridRef& grid, const std::vector<WorldBox>* changed,
TimePoint deadline, bool allow_soft_fallback, const GridRef& verify_grid, const PlannerConfig& config, Path* path,
PathCheck* check, PlanInfo* info, const std::atomic<bool>* cancel, GraphTrace* trace, const char* trace_source)
PathCheck* check, PlanInfo* info, const std::atomic<bool>* cancel, GraphTrace* trace, const char* trace_source,
bool split_edges = true)
{
QueryContext context{ grid, verify_grid, config, graph.deviation_deg, deadline, clearanceThresholdMm(config.clearance_hard_m),
clearanceThresholdMm(config.clearance_min_m), clearanceThresholdMm(config.clearance_preferred_m),
@@ -61,13 +62,15 @@ bool planCore(const CompiledGraph& graph, const Pose2& start, const Pose2& goal,
QueryGraph query(graph, grid, config.zone_deviation_weight);
int32_t s = 0, g = 0;
TimePoint timer = Clock::now();
addQueryEdges(&query, context, start_point, goal_point, &s, &g);
addQueryEdges(&query, context, start_point, goal_point, &s, &g, split_edges);
info->query_nodes_added = query.nodeCount() - query.baseNodes();
info->query_edges_added = query.edgeCount() - query.baseEdges();
info->search_ms += msSince(timer);
const uint8_t* master = grid.cost;
std::vector<uint8_t> neutral;
std::vector<double> factors;
compiledEdgeFactors(graph, master, &factors);
compiledEdgeFactors(graph, master, &factors, grid.allow_unknown);
for (const GraphEdge& edge : query.extraEdges())
factors.push_back(edgeFactor(edge.points, master, grid));
@@ -141,7 +144,7 @@ bool planCore(const CompiledGraph& graph, const Pose2& start, const Pose2& goal,
if (value == kCriticalSpace || value == kPreferredSpace || value == kUnpreferredSpace)
value = kFreeSpace;
master = neutral.data();
compiledEdgeFactors(graph, master, &factors);
compiledEdgeFactors(graph, master, &factors, grid.allow_unknown);
for (const GraphEdge& edge : query.extraEdges())
factors.push_back(edgeFactor(edge.points, master, grid));
if (trace_run != nullptr) trace_run->neutral_factors = factors;
@@ -405,7 +408,8 @@ bool planCore(const CompiledGraph& graph, const Pose2& start, const Pose2& goal,
trace_reason(reason);
break;
}
blocked_pairs.insert(pairs.begin(), pairs.end());
for (const auto& pair : pairs)
blocked_pairs.emplace(query.parentEdge(pair.first), query.parentEdge(pair.second));
if (trace_attempt != nullptr) trace_attempt->blocked_pairs_added = pairs;
++info->retries;
reason = why;
@@ -424,6 +428,11 @@ bool planRung(const CompiledGraph& graph, const RouteRequest& request, const Gri
if (planCore(graph, request.start, request.goal, live, changed, deadline, true, live, config, path, check, info, request.cancel,
trace, "compiled"))
return true;
if ((!request.cancel || !request.cancel->load(std::memory_order_relaxed)) && Clock::now() < deadline &&
info->reason != "no_route_enclosed" && info->reason != "timeout" &&
planCore(graph, request.start, request.goal, live, changed, deadline, true, live, config, path, check, info, request.cancel,
trace, "compiled_without_splits", false))
return true;
if ((request.cancel && request.cancel->load(std::memory_order_relaxed)) || changed == nullptr || !backend.build_coarse || info->reason == "no_route_enclosed" || info->reason == "timeout")
return false;
@@ -472,6 +481,7 @@ bool planRung(const CompiledGraph& graph, const RouteRequest& request, const Gri
window.cost = window_cost.data();
window.clearance_mm = window_clearance.data();
window.direction = live.direction != nullptr ? window_direction.data() : nullptr;
window.allow_unknown = live.allow_unknown;
bool ok = false;
PlanInfo live_info;

View File

@@ -59,9 +59,11 @@ PlanResult planRoute(const GraphProvider& graphs, const RouteRequest& request, c
return planRoute(graphs, request, live, config, backend, nullptr);
}
PlanResult planRoute(const GraphProvider& graphs, const RouteRequest& request, const GridRef& live, const PlannerConfig& config,
PlanResult planRoute(const GraphProvider& graphs, const RouteRequest& request, const GridRef& live_input, const PlannerConfig& config,
const RidgeBackend& backend, GraphTrace* trace)
{
GridRef live = live_input;
live.allow_unknown = config.allow_unknown;
PlanResult result;
const TimePoint began = Clock::now();
result.info.detour_upgrade_outcome = config.detour_upgrade_enabled ? "not_triggered" : "off";
@@ -106,15 +108,34 @@ PlanResult planRoute(const GraphProvider& graphs, const RouteRequest& request, c
return finish();
}
if (live.cost == nullptr || live.clearance_mm == nullptr || live.width <= 0 || live.height <= 0 || !(live.resolution > 0.0) ||
!std::isfinite(live.resolution) || !std::isfinite(live.origin_x) || !std::isfinite(live.origin_y) ||
(!graphs && !config.lattice_enabled) || !std::isfinite(request.start.x) || !std::isfinite(request.start.y) || !std::isfinite(request.goal.x) ||
!std::isfinite(request.goal.y) || (config.lattice_enabled && (!std::isfinite(live.resolution) ||
!std::isfinite(live.origin_x) || !std::isfinite(live.origin_y))) || (request.start.has_yaw && !std::isfinite(request.start.yaw)) ||
!std::isfinite(request.goal.y) || (request.start.has_yaw && !std::isfinite(request.start.yaw)) ||
(request.goal.has_yaw && !std::isfinite(request.goal.yaw)))
{
result.info.reason = "invalid_request";
return finish();
}
const auto goal_overlaps = [&](uint8_t cost) {
if (request.goal.has_yaw)
return footprintOverlapsCost(live, request.goal.x, request.goal.y, request.goal.yaw, config.half_x_m, config.half_y_m, cost);
const double x = std::floor((request.goal.x - live.origin_x) / live.resolution);
const double y = std::floor((request.goal.y - live.origin_y) / live.resolution);
return x >= 0.0 && y >= 0.0 && x < live.width && y < live.height &&
live.cost[static_cast<std::size_t>(y) * live.width + static_cast<std::size_t>(x)] == cost;
};
if (goal_overlaps(kLethalCost))
{
result.info.reason = "goal_in_obstacle";
return finish();
}
if (!config.allow_unknown && goal_overlaps(kNoInformation))
{
result.info.reason = "goal_in_unknown";
return finish();
}
const TimePoint deadline = began + std::chrono::duration_cast<Clock::duration>(std::chrono::duration<double>(config.time_limit_s));
// Stricter limits first. With no zones, or a strict configured limit, one rung is all there is.
@@ -329,7 +350,7 @@ std::vector<WorldBox> changedBoxes(const uint8_t* compiled_cost, const GridRef&
{
// Lethal and unknown only. The compiled grid comes from the static layer, so the inflated ring the master
// holds around every static obstacle would otherwise count as a change, and so would any soft value.
const auto state = [](uint8_t value) { return value < kLethalCost ? 0 : value - kLethalCost + 1; };
const auto state = [&](uint8_t value) { return value < kLethalCost || (live.allow_unknown && value == kNoInformation) ? 0 : value - kLethalCost + 1; };
const std::size_t cell_count = static_cast<std::size_t>(live.width) * static_cast<std::size_t>(live.height);
std::vector<uint8_t> local_scratch;
std::vector<uint8_t>& differs = scratch ? *scratch : local_scratch;
@@ -388,6 +409,74 @@ void patchClearance(const uint8_t* compiled_cost, const uint16_t* compiled_clear
std::vector<uint16_t>* clearance_mm, const std::atomic<bool>* cancel)
{
const std::size_t cell_count = static_cast<std::size_t>(live.width) * static_cast<std::size_t>(live.height);
bool removed_lethal = false;
if (live.allow_unknown)
for (std::size_t i = 0; i < cell_count; ++i)
{
if ((i & 4095u) == 0 && cancel && cancel->load(std::memory_order_relaxed)) return;
if (compiled_cost[i] == kLethalCost && live.cost[i] != kLethalCost) { removed_lethal = true; break; }
}
if (removed_lethal)
{
// Removing an obstacle can increase clearance; a local minimum-only patch cannot undo it.
const double inf = 1e20;
std::vector<double> vertical(cell_count, inf);
for (int32_t x = 0; x < live.width; ++x)
{
if (cancel && cancel->load(std::memory_order_relaxed)) return;
int32_t last = -1;
for (int32_t y = 0; y < live.height; ++y)
{
const std::size_t i = static_cast<std::size_t>(y) * live.width + x;
if (live.cost[i] == kLethalCost) last = y;
if (last >= 0) { const double d = y - last; vertical[i] = d * d; }
}
last = live.height;
for (int32_t y = live.height - 1; y >= 0; --y)
{
const std::size_t i = static_cast<std::size_t>(y) * live.width + x;
if (live.cost[i] == kLethalCost) last = y;
if (last < live.height) { const double d = last - y; vertical[i] = std::min(vertical[i], d * d); }
}
}
clearance_mm->assign(cell_count, 65535);
std::vector<int32_t> sites(static_cast<std::size_t>(live.width));
std::vector<double> bounds(static_cast<std::size_t>(live.width) + 1);
for (int32_t y = 0; y < live.height; ++y)
{
if (cancel && cancel->load(std::memory_order_relaxed)) return;
const std::size_t row = static_cast<std::size_t>(y) * live.width;
int32_t k = -1;
for (int32_t x = 0; x < live.width; ++x)
{
const double value = vertical[row + x];
if (value == inf) continue;
double crossing = -inf;
while (k >= 0)
{
const int32_t q = sites[static_cast<std::size_t>(k)];
crossing = ((value + double(x) * x) - (vertical[row + q] + double(q) * q)) / (2.0 * (x - q));
if (crossing > bounds[static_cast<std::size_t>(k)]) break;
--k;
}
++k;
sites[static_cast<std::size_t>(k)] = x;
bounds[static_cast<std::size_t>(k)] = k == 0 ? -inf : crossing;
bounds[static_cast<std::size_t>(k + 1)] = inf;
}
if (k < 0) continue;
int32_t current = 0;
for (int32_t x = 0; x < live.width; ++x)
{
while (current < k && bounds[static_cast<std::size_t>(current + 1)] < x) ++current;
const int32_t q = sites[static_cast<std::size_t>(current)];
const double dx = x - q;
const double mm = std::floor(std::sqrt(vertical[row + q] + dx * dx) * live.resolution * 1000.0);
(*clearance_mm)[row + x] = static_cast<uint16_t>(std::min(65535.0, mm));
}
}
return;
}
clearance_mm->assign(compiled_clearance_mm, compiled_clearance_mm + cell_count);
const int32_t radius_cells = static_cast<int32_t>(std::ceil(radius_m / live.resolution));
for (int32_t y = 0; y < live.height; ++y)
@@ -396,13 +485,14 @@ void patchClearance(const uint8_t* compiled_cost, const uint16_t* compiled_clear
for (int32_t x = 0; x < live.width; ++x)
{
const int32_t cell = y * live.width + x;
if (live.cost[cell] != kLethalCost || compiled_cost[cell] == kLethalCost)
if (!blockedCost(live.cost[cell], live, kLethalCost) || compiled_cost[cell] == kLethalCost ||
(compiled_cost[cell] == kNoInformation && live.cost[cell] == kNoInformation))
continue;
(*clearance_mm)[static_cast<std::size_t>(cell)] = 0;
// Only cells on the rim of a new region set the distance for anything outside it.
const bool inner = x > 0 && y > 0 && x + 1 < live.width && y + 1 < live.height && live.cost[cell - 1] == kLethalCost &&
live.cost[cell + 1] == kLethalCost && live.cost[cell - live.width] == kLethalCost &&
live.cost[cell + live.width] == kLethalCost;
const bool inner = x > 0 && y > 0 && x + 1 < live.width && y + 1 < live.height && blockedCost(live.cost[cell - 1], live, kLethalCost) &&
blockedCost(live.cost[cell + 1], live, kLethalCost) && blockedCost(live.cost[cell - live.width], live, kLethalCost) &&
blockedCost(live.cost[cell + live.width], live, kLethalCost);
if (inner)
continue;
for (int32_t ny = std::max(0, y - radius_cells); ny <= std::min(live.height - 1, y + radius_cells); ++ny)

View File

@@ -73,6 +73,11 @@ private:
constexpr int32_t kStartLinks = 600; // Candidates tried around start and goal.
constexpr double kStartRadiusM = 15.0;
constexpr int32_t kSplitEdgeLimit = 6; // Directed edges per endpoint, at most three split locations each.
constexpr double kSplitRadiusM = 3.0; // [m] Maximum distance from endpoint to edge.
constexpr int32_t kPreferredSplitEdgeLimit = 4; // Preserve lane candidates when nearby Voronoi edges dominate.
constexpr double kPreferredSplitRadiusM = 8.0; // [m] Reach a lane from a nearby off-lane endpoint.
constexpr double kSplitOffsetM = 1.5; // [m] Turn room before and after the projection.
constexpr int kAttachLimit = 120;
constexpr int32_t kTemporaryLinks = 80;
constexpr double kTemporaryRadiusM = 8.0;
@@ -113,7 +118,7 @@ public:
extra_outgoing_.emplace_back();
return nodeCount() - 1;
}
void addEdge(int32_t from, int32_t to, std::vector<Point2> points, EdgeKind kind, double cost)
void addEdge(int32_t from, int32_t to, std::vector<Point2> points, EdgeKind kind, double cost, int32_t parent = -1)
{
extra_outgoing_[static_cast<std::size_t>(from)].push_back(edgeCount());
double deviation_cost = 0.0;
@@ -121,6 +126,14 @@ public:
for (std::size_t i = 1; i < points.size(); ++i)
deviation_cost += zone_weight_ * lineZoneDeviation(points[i-1], points[i], grid_).integral_deg_m / 45.0;
extra_edges_.push_back({ from, to, std::move(points), kind, cost, deviation_cost });
parents_.push_back(parent);
}
int32_t parentEdge(int32_t edge) const
{
if (edge < base_edges_ || edge < 0) return edge;
const int32_t parent = parents_[static_cast<std::size_t>(edge - base_edges_)];
return parent < 0 ? edge : parent;
}
template <typename Visit>
@@ -138,6 +151,7 @@ private:
int32_t base_nodes_, base_edges_;
std::vector<Point2> extra_nodes_;
std::vector<GraphEdge> extra_edges_;
std::vector<int32_t> parents_;
std::vector<std::vector<int32_t>> extra_outgoing_;
const GridRef& grid_;
double zone_weight_;
@@ -186,7 +200,7 @@ struct Candidate
};
void addQueryEdges(QueryGraph* query, const QueryContext& context, const Point2& start, const Point2& goal, int32_t* start_node,
int32_t* goal_node);
int32_t* goal_node, bool split_edges = true);
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);

View File

@@ -37,7 +37,7 @@ bool Standability::tileHasBlocked(int32_t tx, int32_t ty) const
{
if (stopped()) return true;
for (int32_t x = x0; x < x1; ++x)
if (grid_.cost[static_cast<std::size_t>(y) * grid_.width + x] >= kLethalCost) return true;
if (blockedCost(grid_.cost[static_cast<std::size_t>(y) * grid_.width + x], grid_, kLethalCost)) return true;
}
return false;
}
@@ -52,7 +52,7 @@ bool Standability::fits(std::size_t cell)
Tile& tile = tiles_[tile_id];
uint8_t& value = tile.cells[static_cast<std::size_t>(y % 32) * 32 + x % 32];
if (value != 0) return value == 1;
if (grid_.cost[cell] >= kInscribedCost)
if (blockedCost(grid_.cost[cell], grid_))
{
value = 2;
if (rejected_) ++*rejected_;
@@ -96,7 +96,7 @@ bool Standability::fits(std::size_t cell)
for (int32_t ix = std::max(0, x - cells); ix <= std::min(grid_.width - 1, x + cells); ++ix)
{
const double distance = std::hypot(ix - x, iy - y) * grid_.resolution;
if (distance < inner && grid_.cost[static_cast<std::size_t>(iy) * grid_.width + ix] == kLethalCost)
if (distance < inner && blockedCost(grid_.cost[static_cast<std::size_t>(iy) * grid_.width + ix], grid_, kLethalCost))
{
value = 2;
if (rejected_) ++*rejected_;

View File

@@ -21,6 +21,7 @@
#include <lane_route_core/costmap_backend.h>
#include "../src/lattice_internal.h"
#include "../src/route_planner_internal.h"
#include "../src/standability.h"
#include "../src/footprint_zones.h"
@@ -683,17 +684,16 @@ TEST_F(PlanRouteTest, GraphFootprintGapCountsUnknownCells)
ASSERT_TRUE(checkFootprintGap(direct, grid, config_.footprint_min_gap_m, config_.half_x_m, config_.half_y_m).valid);
ASSERT_FALSE(checkFootprintGap(direct, grid, config_.footprint_min_gap_m, config_.half_x_m, config_.half_y_m, nullptr,
nullptr, true).valid);
// Graph only: the candidate along the direct line is rejected. Its shortcut raise uses the lethal clearance field, so the
// graph cannot move the line away from unknown cells by itself; it fails instead of returning the 20 mm path.
// The live clearance patch includes unknown cells, so the graph can move away while retaining the gap rule.
const PlanResult graph_only = planWithObstacle(request, live);
EXPECT_FALSE(graph_only.ok);
EXPECT_EQ(graph_only.info.reason, "footprint_gap_below_minimum");
// With the fallback the lattice, which already counted unknown cells, returns a path that keeps the gap.
expectLegal(graph_only, request, config_);
EXPECT_TRUE(checkFootprintGap(graph_only.path, grid, config_.footprint_min_gap_m, config_.half_x_m, config_.half_y_m, nullptr,
nullptr, true).valid);
// Enabling the fallback preserves the same gap rule.
config_.lattice_enabled = true;
config_.lattice_preferred_gap_m = 0.0;
const PlanResult result = planWithObstacle(request, live);
expectLegal(result, request, config_);
EXPECT_EQ(result.info.tier_used, "lattice");
EXPECT_TRUE(checkFootprintGap(result.path, grid, config_.footprint_min_gap_m, config_.half_x_m, config_.half_y_m, nullptr,
nullptr, true).valid);
}
@@ -1333,6 +1333,296 @@ TEST(Lattice, FreeGoalAcceptsCurvedArrivalPastCorner)
EXPECT_NEAR(wrapAngle(result.path.back().yaw - kPi / 2.0), 0.0, 1e-5);
}
TEST(Lattice, BlockedGoalFailsBeforeSearching)
{
LatticeTestGrid map(160, 160);
PlannerConfig config = latticeConfig();
RouteRequest request = latticeRequest(pose(1.0, 3.0, 0.0), pose(5.0, 3.0, 0.0));
const std::size_t cell = 60 * map.width + 105;
for (const auto& obstacle : {std::make_pair(kLethalCost, "goal_in_obstacle"),
std::make_pair(kNoInformation, "goal_in_unknown")})
{
map.cost[cell] = obstacle.first;
const PlanResult result = map.plan(request, config);
EXPECT_FALSE(result.ok);
EXPECT_EQ(result.info.reason, obstacle.second);
EXPECT_EQ(result.info.lattice_states_expanded, 0u);
EXPECT_LT(result.info.query_ms, 100.0);
request.goal.has_yaw = false;
EXPECT_NE(map.plan(request, config).info.reason, obstacle.second);
request.goal.has_yaw = true;
map.cost[cell] = kFreeSpace;
}
}
TEST(Lattice, AllowUnknownControlsGoalAndTraversal)
{
LatticeTestGrid map(160, 120);
for (int y = 0; y < map.height; ++y)
for (int x = 55; x < map.width; ++x)
map.cost[static_cast<std::size_t>(y) * map.width + x] = kNoInformation;
PlannerConfig config = latticeConfig();
RouteRequest request = latticeRequest(pose(1.0, 3.0, 0.0), pose(6.0, 3.0, 0.0));
const PlanResult rejected = map.plan(request, config);
EXPECT_EQ(rejected.info.reason, "goal_in_unknown");
EXPECT_EQ(rejected.info.lattice_states_expanded, 0u);
config.allow_unknown = true;
const PlanResult accepted = map.plan(request, config);
ASSERT_TRUE(accepted.ok) << accepted.info.reason;
EXPECT_GT(accepted.path.back().x, 5.9);
}
TEST(UnknownGrid, LiveChangesAndClearanceFollowPolicy)
{
LatticeTestGrid map(40, 40);
std::vector<uint8_t> base = map.cost;
map.cost[20 * map.width + 20] = kNoInformation;
GridRef grid = map.view();
EXPECT_FALSE(changedBoxes(base.data(), grid).empty());
std::vector<uint16_t> patched;
patchClearance(base.data(), map.clearance.data(), grid, 0.2, &patched);
EXPECT_EQ(patched[20 * map.width + 20], 0);
grid.allow_unknown = true;
EXPECT_TRUE(changedBoxes(base.data(), grid).empty());
patchClearance(base.data(), map.clearance.data(), grid, 0.2, &patched);
EXPECT_EQ(patched[20 * map.width + 20], map.clearance[20 * map.width + 20]);
base[20 * map.width + 20] = kNoInformation;
map.cost[20 * map.width + 20] = kLethalCost;
patchClearance(base.data(), map.clearance.data(), grid, 0.2, &patched);
EXPECT_EQ(patched[20 * map.width + 20], 0);
}
TEST(UnknownGrid, RemovedLethalNoLongerRestrictsClearance)
{
LatticeTestGrid map(30, 30);
std::vector<uint8_t> base = map.cost;
base[10 * map.width + 10] = kLethalCost;
base[10 * map.width + 20] = kLethalCost;
map.cost = base;
map.cost[10 * map.width + 10] = kNoInformation;
std::fill(map.clearance.begin(), map.clearance.end(), 0);
GridRef grid = map.view();
grid.allow_unknown = true;
std::vector<uint16_t> patched;
patchClearance(base.data(), map.clearance.data(), grid, 1.5, &patched);
for (int y = 0; y < map.height; ++y)
for (int x = 0; x < map.width; ++x)
EXPECT_EQ(patched[static_cast<std::size_t>(y) * map.width + x],
static_cast<uint16_t>(std::floor(std::hypot(x - 20, y - 10) * kResolution * 1000.0)));
map.cost[10 * map.width + 20] = kFreeSpace;
patchClearance(base.data(), map.clearance.data(), grid, 1.5, &patched);
EXPECT_TRUE(std::all_of(patched.begin(), patched.end(), [](uint16_t value) { return value == 65535; }));
}
TEST(QueryEdgeSplits, ConnectsBothEndpointsToTheMiddleOfPreferredEdge)
{
LatticeTestGrid map(400, 140);
for (int y = 57; y <= 63; ++y)
for (int x = 10; x < 390; ++x)
map.cost[static_cast<std::size_t>(y) * map.width + x] = kPreferredSpace;
const GridRef grid = map.view();
auto graph = std::make_shared<CompiledGraph>();
graph->deviation_deg = 90.0;
graph->nodes = {{1.0, 3.025}, {19.0, 3.025}};
graph->edges = {{0, 1, {graph->nodes[0], graph->nodes[1]}, EdgeKind::kPreferredRidge, 18.0}};
graph->outgoing = {{0}, {}};
graph->sample_offsets = {0, 1};
graph->sample_cells = {60 * map.width + 200};
graph->sample_weights = {18.0};
PlannerConfig config = latticeConfig();
config.lattice_enabled = false;
config.detour_upgrade_enabled = false;
config.min_turn_radius_m = 0.4;
config.corner_radii_m = {0.4};
config.regular_turn_radius_m = 0.4;
config.deviation_ladder_deg.clear();
RouteRequest request{pose(4.0, 2.425, 0.0), pose(16.0, 2.425, 0.0), {}};
request.start.has_yaw = false;
request.goal.has_yaw = false;
GraphTrace trace;
const PlanResult result = planRoute([&](double) { return graph; }, request, grid, config, {}, &trace);
ASSERT_TRUE(result.ok) << result.info.reason;
double lane_length = 0.0, length = 0.0;
for (std::size_t i = 1; i < result.path.size(); ++i)
{
const auto& a = result.path[i-1];
const auto& b = result.path[i];
const double d = std::hypot(b.x - a.x, b.y - a.y);
length += d;
if (a.y >= 2.85 && a.y <= 3.2) lane_length += d;
}
EXPECT_GT(lane_length, length * 0.6);
ASSERT_FALSE(trace.runs.empty());
EXPECT_GT(trace.runs.front().nodes.size(), graph->nodes.size() + 2);
}
TEST(QueryEdgeSplits, ReachesLongVoronoiEdgeWithoutGoingToItsEnds)
{
LatticeTestGrid map(1400, 160);
for (int y = 30; y < 80; ++y)
for (int x = 635; x < 645; ++x)
map.cost[static_cast<std::size_t>(y) * map.width + x] = kLethalCost;
robot_costmap_2d::ReferenceGridView reference;
reference.cost = map.cost.data();
reference.geometry = geometryOf(map.view());
map.clearance = robot_costmap_2d::computeVoronoiSkeleton(reference, ridgeParams(defaultConfig())).clearance_mm;
const GridRef grid = map.view();
auto graph = std::make_shared<CompiledGraph>();
graph->deviation_deg = 90.0;
graph->nodes = {{1.0, 5.0}, {69.0, 5.0}};
graph->edges = {{0, 1, {graph->nodes[0], graph->nodes[1]}, EdgeKind::kVoronoi, 68.0}};
graph->outgoing = {{0}, {}};
graph->sample_offsets = {0, 1};
graph->sample_cells = {100 * map.width + 700};
graph->sample_weights = {68.0};
PlannerConfig config = defaultConfig();
config.detour_upgrade_enabled = false;
config.min_turn_radius_m = config.regular_turn_radius_m = 0.4;
config.corner_radii_m = {0.4};
config.deviation_ladder_deg.clear();
RouteRequest request{pose(25.0, 3.0, 0.0), pose(42.0, 3.0, 0.0), {}};
request.start.has_yaw = request.goal.has_yaw = false;
const PlanResult result = planRoute([&](double) { return graph; }, request, grid, config, {});
ASSERT_TRUE(result.ok) << result.info.reason;
EXPECT_LT(result.info.path_length_m, 25.0);
}
TEST(QueryEdgeSplits, KeepsNarrowPreferredLaneAfterSmoothing)
{
LatticeTestGrid map(400, 160);
for (int y = 60; y <= 61; ++y)
for (int x = 20; x < 380; ++x)
map.cost[static_cast<std::size_t>(y) * map.width + x] = kPreferredSpace;
const GridRef grid = map.view();
auto graph = std::make_shared<CompiledGraph>();
graph->deviation_deg = 90.0;
graph->nodes = {{1.0, 3.025}, {19.0, 3.025}};
graph->edges = {{0, 1, {graph->nodes[0], graph->nodes[1]}, EdgeKind::kPreferredRidge, 18.0}};
graph->outgoing = {{0}, {}};
graph->sample_offsets = {0, 1};
graph->sample_cells = {60 * map.width + 200};
graph->sample_weights = {18.0};
PlannerConfig config = defaultConfig();
config.detour_upgrade_enabled = false;
config.min_turn_radius_m = config.regular_turn_radius_m = 0.4;
config.corner_radii_m = {0.4};
config.deviation_ladder_deg.clear();
RouteRequest request{pose(4.0, 5.5, 0.0), pose(16.0, 2.90, 0.0), {}};
request.start.has_yaw = request.goal.has_yaw = false;
const PlanResult result = planRoute([&](double) { return graph; }, request, grid, config, {});
ASSERT_TRUE(result.ok) << result.info.reason;
double preferred = 0.0;
for (std::size_t i = 1; i < result.path.size(); ++i)
{
const auto& a = result.path[i-1];
const auto& b = result.path[i];
if ((a.y + b.y) * 0.5 >= 3.0 && (a.y + b.y) * 0.5 < 3.1)
preferred += std::hypot(b.x - a.x, b.y - a.y);
}
EXPECT_GT(preferred, 6.0);
}
TEST(QueryEdgeSplits, ReachesPreferredLaneFromGoalBeyondThreeMetres)
{
LatticeTestGrid map(400, 200);
for (int y = 60; y <= 63; ++y)
for (int x = 20; x < 380; ++x)
map.cost[static_cast<std::size_t>(y) * map.width + x] = kPreferredSpace;
const GridRef grid = map.view();
auto graph = std::make_shared<CompiledGraph>();
graph->deviation_deg = 90.0;
graph->nodes = {{1.0, 3.025}, {19.0, 3.025}};
graph->edges = {{0, 1, {graph->nodes[0], graph->nodes[1]}, EdgeKind::kPreferredRidge, 18.0}};
graph->outgoing = {{0}, {}};
graph->sample_offsets = {0, 1};
graph->sample_cells = {60 * map.width + 200};
graph->sample_weights = {18.0};
PlannerConfig config = defaultConfig();
config.detour_upgrade_enabled = false;
config.min_turn_radius_m = config.regular_turn_radius_m = 0.4;
config.corner_radii_m = {0.4};
config.deviation_ladder_deg.clear();
RouteRequest request{pose(4.0, 2.5, 0.0), pose(16.0, 7.0, 0.0), {}};
request.start.has_yaw = request.goal.has_yaw = false;
const PlanResult result = planRoute([&](double) { return graph; }, request, grid, config, {});
ASSERT_TRUE(result.ok) << result.info.reason;
double preferred = 0.0;
for (std::size_t i = 1; i < result.path.size(); ++i)
{
const auto& a = result.path[i-1];
const auto& b = result.path[i];
if ((a.y + b.y) * 0.5 >= 3.0 && (a.y + b.y) * 0.5 < 3.2)
preferred += std::hypot(b.x - a.x, b.y - a.y);
}
EXPECT_GT(preferred, 5.0);
}
TEST(QueryEdgeSplits, ConnectsNearbyPreferredLaneEnds)
{
LatticeTestGrid map(200, 120);
map.cost[60 * map.width + 20] = kPreferredSpace;
const GridRef grid = map.view();
RidgeBackend backend;
backend.region_centre_edges = [](const std::vector<uint8_t>&, const GridRef&, std::vector<Point2>* nodes,
std::vector<CoarseEdge>* edges, const std::atomic<bool>*) {
*nodes = {{1.0, 3.0}, {3.0, 3.0}, {4.0, 3.0}, {7.0, 3.0}};
*edges = {{0, 1, {(*nodes)[0], (*nodes)[1]}}, {2, 3, {(*nodes)[2], (*nodes)[3]}}};
};
PlannerConfig config = defaultConfig();
const CompiledGraph graph = compileGraph({}, grid, grid.cost, 90.0, config, backend);
EXPECT_TRUE(std::any_of(graph.edges.begin(), graph.edges.end(), [](const GraphEdge& edge) {
return edge.kind == EdgeKind::kPreferredAttach && edge.from == 1 && edge.to == 2;
}));
}
TEST(QueryEdgeSplits, ConnectsPreferredEndToAnotherLaneInterior)
{
LatticeTestGrid map(200, 120);
map.cost[60 * map.width + 20] = kPreferredSpace;
const GridRef grid = map.view();
RidgeBackend backend;
backend.region_centre_edges = [](const std::vector<uint8_t>&, const GridRef&, std::vector<Point2>* nodes,
std::vector<CoarseEdge>* edges, const std::atomic<bool>*) {
*nodes = {{1.0, 3.0}, {8.0, 3.0}, {4.0, 4.0}, {4.0, 5.0}};
*edges = {{0, 1, {(*nodes)[0], (*nodes)[1]}}, {2, 3, {(*nodes)[2], (*nodes)[3]}}};
};
PlannerConfig config = defaultConfig();
const CompiledGraph graph = compileGraph({}, grid, grid.cost, 90.0, config, backend);
bool attached = false, toward_left = false, toward_right = false;
for (const GraphEdge& edge : graph.edges)
{
const Point2& target = graph.nodes[static_cast<std::size_t>(edge.to)];
if (edge.kind == EdgeKind::kPreferredAttach && edge.from == 2 && distanceOf(target, {4.0, 3.0}) < 1e-6) attached = true;
const Point2& source = graph.nodes[static_cast<std::size_t>(edge.from)];
if (edge.kind == EdgeKind::kPreferredRidge && distanceOf(source, {4.0, 3.0}) < 1e-6)
{
toward_left |= edge.to == 0;
toward_right |= edge.to == 1;
}
}
EXPECT_TRUE(attached);
EXPECT_TRUE(toward_left);
EXPECT_TRUE(toward_right);
}
TEST(QueryEdgeSplits, PreferredEntryTurnDoesNotEraseCostSaving)
{
LatticeTestGrid map(250, 120);
const GridRef grid = map.view();
CompiledGraph graph;
graph.nodes = {{1.0, 2.0}, {2.0, 3.0}, {10.0, 3.0}, {11.0, 2.0}};
graph.edges = {{0, 3, {graph.nodes[0], graph.nodes[3]}, EdgeKind::kDirect, 10.0},
{0, 1, {graph.nodes[0], graph.nodes[1]}, EdgeKind::kAttach, 1.7},
{1, 2, {graph.nodes[1], graph.nodes[2]}, EdgeKind::kPreferredRidge, 15.0},
{2, 3, {graph.nodes[2], graph.nodes[3]}, EdgeKind::kAttach, 1.7}};
graph.outgoing = {{0, 1}, {2}, {3}, {}};
detail::QueryGraph query(graph, grid, 0.0);
std::vector<int32_t> route;
ASSERT_TRUE(detail::searchRoute(query, 0, 3, std::vector<uint8_t>(4, 0), {}, 20.0, 0.4,
{1.0, 1.0, 0.4, 1.0}, &route, nullptr));
EXPECT_EQ(route, (std::vector<int32_t>{1, 2, 3}));
}
TEST(Lattice, FixedGoalUsesCurvedArrivalThenCheckedSpin)
{
LatticeTestGrid map(120, 120);

View File

@@ -226,7 +226,7 @@ std::shared_ptr<MapData> loadMap(const std::string& path, const robot_costmap_2d
return map;
}
GridRef gridOf(const MapData& map, const std::vector<uint8_t>& cost, const uint16_t* clearance, int variant)
GridRef gridOf(const MapData& map, const std::vector<uint8_t>& cost, const uint16_t* clearance, int variant, bool allow_unknown)
{
GridRef grid;
grid.width = map.width;
@@ -237,6 +237,7 @@ GridRef gridOf(const MapData& map, const std::vector<uint8_t>& cost, const uint1
grid.cost = cost.data();
grid.clearance_mm = clearance;
grid.direction = map.directions[static_cast<std::size_t>(variant)].data();
grid.allow_unknown = allow_unknown;
return grid;
}
@@ -293,6 +294,7 @@ void applyOverrides(PlannerConfig* config)
{ "lattice_smooth_max_checks", &config->lattice_smooth_max_checks },
};
const std::map<std::string, bool*> bools{
{ "allow_unknown", &config->allow_unknown },
{ "detour_upgrade_enabled", &config->detour_upgrade_enabled },
{ "lattice_smooth_enabled", &config->lattice_smooth_enabled },
{ "lattice_tight_arcs", &config->lattice_tight_arcs },
@@ -441,9 +443,9 @@ int main(int argc, char** argv)
live_cost[static_cast<std::size_t>(y * map->width + x)] = kLethalCost;
}
const GridRef compile_grid = gridOf(*map, map->static_cost, map->clearance_mm.data(), variant);
const GridRef compile_grid = gridOf(*map, map->static_cost, map->clearance_mm.data(), variant, config.allow_unknown);
const Clock::time_point update_began = Clock::now();
const GridRef unpatched = gridOf(*map, live_cost, map->clearance_mm.data(), variant);
const GridRef unpatched = gridOf(*map, live_cost, map->clearance_mm.data(), variant, config.allow_unknown);
request.changed_boxes = changedBoxes(map->static_cost.data(), unpatched);
std::vector<uint16_t> patched;
const uint16_t* live_clearance = map->clearance_mm.data();
@@ -453,7 +455,7 @@ int main(int argc, char** argv)
live_clearance = patched.data();
}
const double update_ms = msSince(update_began);
const GridRef live_grid = gridOf(*map, live_cost, live_clearance, variant);
const GridRef live_grid = gridOf(*map, live_cost, live_clearance, variant, config.allow_unknown);
double coarse_ms = 0.0;
const CoarseGraph* coarse = nullptr;