diff --git a/include/lane_route_core/path_verifier.h b/include/lane_route_core/path_verifier.h index 2f8ac29..d1bc575 100644 --- a/include/lane_route_core/path_verifier.h +++ b/include/lane_route_core/path_verifier.h @@ -13,7 +13,7 @@ namespace lane_route_core struct PathCheck { bool valid = false; - int zone_violations = 0; ///< Segment and cell pairs against the direction limit. + int zone_violations = 0; ///< Centre segments and sampled footprint cells against the direction limit. int footprint_collisions = 0; ///< Sampled poses hitting lethal or unknown cells, at most 1 cm and 0.03 rad apart. int self_crossings = 0; ///< Crossings between non-neighbouring parts of the path. int kinks = 0; ///< In-place turns away from both ends, plus bends over 0.1 m above the curve and corner limits. @@ -26,7 +26,8 @@ struct PathCheck * @param path Output poses. * @param grid Live grid. * @param deviation_deg Direction limit [deg]. - * @param config Footprint and tightest allowed radius. */ + * @param config Footprint, radius and query-wide direction limit. Footprint direction checks sample at most 0.04 m and + * 0.03 rad apart, allow transitions near centre entries and preserve continuous contact at parked endpoints. */ PathCheck verifyPath(const Path& path, const GridRef& grid, double deviation_deg, const PlannerConfig& config, const std::atomic* cancel = nullptr); diff --git a/include/lane_route_core/route_planner.h b/include/lane_route_core/route_planner.h index 92e708a..2aa4286 100644 --- a/include/lane_route_core/route_planner.h +++ b/include/lane_route_core/route_planner.h @@ -5,6 +5,7 @@ #include #include #include +#include #include #include @@ -14,6 +15,44 @@ namespace lane_route_core { +/** Optional offline trace. Each run is one graph core pass, including a live-ridge retry when present. */ +struct GraphTraceAttempt +{ + int pass = 0; ///< 0: master costs, 1: neutral soft costs. + int attempt = 0; + std::vector route; ///< Edge ids in the containing GraphTraceRun. + std::string reason; + int32_t rejected_edge = -1; + std::vector> blocked_pairs_added; + double candidate_length_m = 0.0; + double reference_length_m = 0.0; + int zone_violations = -1; + int footprint_collisions = -1; +}; + +struct GraphTraceRun +{ + double deviation_deg = 0.0; + double min_turn_radius_m = 0.0; + double max_kink_deg = 0.0; + double voronoi_weight = 1.0; + std::vector corner_radii_m; + std::string source; ///< "compiled" or "live_ridge". + int32_t base_nodes = 0, base_edges = 0; + int32_t start_node = -1, goal_node = -1; + std::vector nodes; + std::vector edges; + std::vector factors; + std::vector neutral_factors; + std::vector initially_blocked_edges; + std::vector attempts; +}; + +struct GraphTrace +{ + std::vector runs; +}; + /** @brief One planning request. */ struct RouteRequest { @@ -111,6 +150,10 @@ using GraphProvider = std::function(double PlanResult planRoute(const GraphProvider& graphs, const RouteRequest& request, const GridRef& live, const PlannerConfig& config, const RidgeBackend& backend); +/** Offline diagnostic overload. A non-null caller-owned trace records graphs and attempts for this request. */ +PlanResult planRoute(const GraphProvider& graphs, const RouteRequest& request, const GridRef& live, + const PlannerConfig& config, const RidgeBackend& backend, GraphTrace* trace); + /** @brief Regions where lethal or unknown cells differ between the compiled grid and the live grid. Inflation does not count. * @param compiled_cost Compile grid, same layout as `live`. * @return One box per 4-connected region of changed cells. */ diff --git a/include/lane_route_core/types.h b/include/lane_route_core/types.h index a8a5f7c..609705d 100644 --- a/include/lane_route_core/types.h +++ b/include/lane_route_core/types.h @@ -119,6 +119,7 @@ struct PlannerConfig /// the footprint can rotate at the vertex without touching an obstacle. 0 disables sharp corners. double max_kink_deg = 45.0; double footprint_min_gap_m = 0.03; ///< Smallest footprint to lethal gap on the whole path. + double zone_transition_m = 1.0; ///< [m] Path distance to a centre pose in the same zone; 0 disables transition allowance. std::vector footprint_gap_shortcut_raise_m{ 0.05, 0.10 }; ///< Empty: check only. double max_deviation_deg = 90.0; ///< Configured direction limit, the last ladder rung. std::vector deviation_ladder_deg{ 0.01 }; ///< Stricter rungs tried first. diff --git a/src/footprint_zones.h b/src/footprint_zones.h new file mode 100644 index 0000000..8c499aa --- /dev/null +++ b/src/footprint_zones.h @@ -0,0 +1,234 @@ +#ifndef LANE_ROUTE_CORE_FOOTPRINT_ZONES_H_ +#define LANE_ROUTE_CORE_FOOTPRINT_ZONES_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace lane_route_core +{ +namespace detail +{ + +struct FootprintZoneCell +{ + int32_t index; + uint8_t code; +}; + +// Rectangle/square separating-axis test. Cell-edge contact counts, as in the footprint collision check. +inline bool footprintIntersectsZoneCell(const GridRef& grid, double x, double y, double yaw, + double half_x, double half_y, int32_t ix, int32_t iy) +{ + const double c = std::cos(yaw), s = std::sin(yaw); + const double ac = std::abs(c), as = std::abs(s); + const double half_cell = grid.resolution * 0.5; + const double dx = grid.origin_x + (ix + 0.5) * grid.resolution - x; + const double dy = grid.origin_y + (iy + 0.5) * grid.resolution - y; + const double projected = half_cell * (ac + as); + constexpr double kEpsilon = 1e-10; + return std::abs(dx) <= half_x * ac + half_y * as + half_cell + kEpsilon && + std::abs(dy) <= half_x * as + half_y * ac + half_cell + kEpsilon && + std::abs(c * dx + s * dy) <= half_x + projected + kEpsilon && + std::abs(-s * dx + c * dy) <= half_y + projected + kEpsilon; +} + +// Visit only direction cells in the rectangle's axis-aligned bounding box; the grid, rather than map polygons, +// defines overlapping zones. Callers can use a tile mask first to avoid this scan away from incompatible zones. +template +inline void visitFootprintZoneCells(const GridRef& grid, double x, double y, double yaw, + double half_x, double half_y, Visitor visitor) +{ + if (grid.direction == nullptr || grid.width <= 0 || grid.height <= 0 || grid.resolution <= 0.0) + return; + const double c = std::cos(yaw), s = std::sin(yaw); + const double ac = std::abs(c), as = std::abs(s); + const double rx = half_x * ac + half_y * as, ry = half_x * as + half_y * ac; + const double half_cell = grid.resolution * 0.5; + const double projected = half_cell * (ac + as); + constexpr double kEpsilon = 1e-10; + constexpr double kCellEpsilon = 1e-9; + const double xmin = std::floor((x - rx - grid.origin_x) / grid.resolution - kCellEpsilon); + const double xmax = std::floor((x + rx - grid.origin_x) / grid.resolution + kCellEpsilon); + const double ymin = std::floor((y - ry - grid.origin_y) / grid.resolution - kCellEpsilon); + const double ymax = std::floor((y + ry - grid.origin_y) / grid.resolution + kCellEpsilon); + if (xmax < 0.0 || ymax < 0.0 || xmin >= grid.width || ymin >= grid.height) + return; + const int32_t x0 = static_cast(std::max(0.0, xmin)); + const int32_t x1 = static_cast(std::min(static_cast(grid.width - 1), xmax)); + const int32_t y0 = static_cast(std::max(0.0, ymin)); + const int32_t y1 = static_cast(std::min(static_cast(grid.height - 1), ymax)); + for (int32_t iy = y0; iy <= y1; ++iy) + for (int32_t ix = x0; ix <= x1; ++ix) + { + const int32_t index = iy * grid.width + ix; + const uint8_t code = grid.direction[index]; + if (code == 0) continue; + const double dx = grid.origin_x + (ix + 0.5) * grid.resolution - x; + const double dy = grid.origin_y + (iy + 0.5) * grid.resolution - y; + if (std::abs(dx) <= rx + half_cell + kEpsilon && std::abs(dy) <= ry + half_cell + kEpsilon && + std::abs(c * dx + s * dy) <= half_x + projected + kEpsilon && + std::abs(-s * dx + c * dy) <= half_y + projected + kEpsilon) + visitor(FootprintZoneCell{index, code}); + } +} + +inline bool headingAllowedInZone(double yaw, uint8_t code, double deviation_deg) +{ + if (code == 0) + return true; + const double delta = std::abs(std::remainder(yaw - (static_cast(code) - 1) * kPi / 4.0, 2.0 * kPi)); + return delta * 180.0 / kPi <= deviation_deg + 1e-9; +} + +// One byte of direction bits per touched 32x32 tile. Most poses only inspect one or two tile masks; a rectangle/cell +// scan is needed only when a nearby tile contains an incompatible direction. The index lives for one grid snapshot. +class FootprintZoneIndex +{ +public: + explicit FootprintZoneIndex(const GridRef& grid, std::pmr::memory_resource* memory = std::pmr::get_default_resource(), + const std::atomic* cancel = nullptr, + const std::chrono::steady_clock::time_point* deadline = nullptr) + : grid_(grid), masks_(memory), regions_(memory), memory_(memory), cancel_(cancel), deadline_(deadline) {} + + // Match the reference graph's 8-connected equal-code regions. The grid has no polygon IDs, so two touching zones + // with the same code are indistinguishable. Only regions needed for endpoint or wrong-overlap checks are flood-filled. + // Labels use 4 KiB per visited tile; the temporary stack is charged to the lattice memory resource. + uint32_t component(int32_t cell) + { + if (failed_ || grid_.direction == nullptr || cell < 0 || grid_.width <= 0 || grid_.height <= 0 || + static_cast(cell) >= static_cast(grid_.width) * grid_.height) return 0; + const uint8_t code = grid_.direction[cell]; + if (code == 0) return 0; + const uint32_t known = knownComponent(cell); + if (known != 0) return known; + const uint32_t id = static_cast(cell) + 1u; + labelCell(cell, id); + std::pmr::vector stack(memory_); + stack.push_back(cell); + std::size_t visited = 0; + while (!stack.empty()) + { + if ((++visited & 1023u) == 0 && stopped()) { failed_ = true; return 0; } + const int32_t here = stack.back(); stack.pop_back(); + const int32_t x = here % grid_.width, y = here / grid_.width; + for (int32_t ny = std::max(0, y - 1); ny <= std::min(grid_.height - 1, y + 1); ++ny) + for (int32_t nx = std::max(0, x - 1); nx <= std::min(grid_.width - 1, x + 1); ++nx) + { + const int32_t next = ny * grid_.width + nx; + if (grid_.direction[next] != code || knownComponent(next) != 0) continue; + labelCell(next, id); + stack.push_back(next); + } + } + if (stopped()) { failed_ = true; return 0; } + return id; + } + + uint32_t knownComponent(int32_t cell) const + { + const int32_t x = cell % grid_.width, y = cell / grid_.width; + const auto found = regions_.find(tileKey(x / 32, y / 32)); + return found == regions_.end() ? 0u : found->second.labels[static_cast(y % 32) * 32 + x % 32]; + } + + bool failed() const { return failed_; } + + bool mayViolate(double x, double y, double yaw, double half_x, double half_y, double deviation_deg) + { + if (grid_.direction == nullptr) return false; + const double ac = std::abs(std::cos(yaw)), as = std::abs(std::sin(yaw)); + const double rx = half_x * ac + half_y * as, ry = half_x * as + half_y * ac; + const auto tileOf = [&](double coordinate, double origin, int32_t limit) { + const double cell = std::floor((coordinate - origin) / grid_.resolution); + return static_cast(std::max(0.0, std::min(static_cast(limit - 1), cell))) / 32; + }; + const int32_t x0 = tileOf(x - rx - 1e-9, grid_.origin_x, grid_.width); + const int32_t x1 = tileOf(x + rx + 1e-9, grid_.origin_x, grid_.width); + const int32_t y0 = tileOf(y - ry - 1e-9, grid_.origin_y, grid_.height); + const int32_t y1 = tileOf(y + ry + 1e-9, grid_.origin_y, grid_.height); + uint8_t directions = 0; + for (int32_t ty = y0; ty <= y1; ++ty) + for (int32_t tx = x0; tx <= x1; ++tx) + { + if (stopped()) { failed_ = true; return true; } + directions |= tileMask(tx, ty); + } + for (int bit = 0; bit < 8; ++bit) + if ((directions & (1u << bit)) && !headingAllowedInZone(yaw, static_cast(bit + 1), deviation_deg)) + return true; + return false; + } + + // A legal transition must have a centre in this region within L of path length, and thus within L in x and y. + // This deliberately accepts any same-code cell in every intersecting tile, even a different component, an obstacle, + // or a cell outside the square. It is only a necessary-condition filter; the path verifier decides the real rule. + bool nearbyDirection(double x, double y, uint8_t code, double distance_m) + { + if (grid_.direction == nullptr || code == 0 || distance_m <= 0.0) return false; + const auto tileOf = [&](double coordinate, double origin, int32_t limit) { + const double cell = std::floor((coordinate - origin) / grid_.resolution); + return static_cast(std::max(0.0, std::min(static_cast(limit - 1), cell))) / 32; + }; + const int32_t x0 = tileOf(x - distance_m - 1e-9, grid_.origin_x, grid_.width); + const int32_t x1 = tileOf(x + distance_m + 1e-9, grid_.origin_x, grid_.width); + const int32_t y0 = tileOf(y - distance_m - 1e-9, grid_.origin_y, grid_.height); + const int32_t y1 = tileOf(y + distance_m + 1e-9, grid_.origin_y, grid_.height); + const uint8_t wanted = static_cast(1u << ((code - 1) % 8)); + for (int32_t ty = y0; ty <= y1; ++ty) + for (int32_t tx = x0; tx <= x1; ++tx) + { + if (stopped()) { failed_ = true; return false; } + if ((tileMask(tx, ty) & wanted) != 0) return true; + } + return false; + } + +private: + struct RegionTile { std::array labels{}; }; + int64_t tileKey(int32_t x, int32_t y) const + { return static_cast(y) * ((static_cast(grid_.width) + 31) / 32) + x; } + uint8_t tileMask(int32_t tx, int32_t ty) + { + const int64_t key = tileKey(tx, ty); + const auto found = masks_.find(key); + if (found != masks_.end()) return found->second; + uint8_t mask = 0; + for (int32_t iy = ty * 32; iy < std::min(grid_.height, (ty + 1) * 32); ++iy) + for (int32_t ix = tx * 32; ix < std::min(grid_.width, (tx + 1) * 32); ++ix) + { + const uint8_t code = grid_.direction[static_cast(iy) * grid_.width + ix]; + if (code != 0) mask |= static_cast(1u << ((code - 1) % 8)); + } + masks_.emplace(key, mask); + return mask; + } + void labelCell(int32_t cell, uint32_t id) + { + const int32_t x = cell % grid_.width, y = cell / grid_.width; + regions_[tileKey(x / 32, y / 32)].labels[static_cast(y % 32) * 32 + x % 32] = id; + } + bool stopped() const + { return (cancel_ && cancel_->load(std::memory_order_relaxed)) || + (deadline_ && std::chrono::steady_clock::now() >= *deadline_); } + const GridRef& grid_; + std::pmr::unordered_map masks_; + std::pmr::unordered_map regions_; + std::pmr::memory_resource* memory_; + const std::atomic* cancel_; + const std::chrono::steady_clock::time_point* deadline_; + bool failed_ = false; +}; + +} // namespace detail +} // namespace lane_route_core +#endif // LANE_ROUTE_CORE_FOOTPRINT_ZONES_H_ diff --git a/src/graph_compiler.cpp b/src/graph_compiler.cpp index 8a69550..59f8253 100644 --- a/src/graph_compiler.cpp +++ b/src/graph_compiler.cpp @@ -19,9 +19,13 @@ constexpr int kLeadSteps = 10; // Straight lead of at most 2.5 m constexpr double kMinCompiledLaneM = 0.3; constexpr double kLaneOffsetPenalty = 2.8; // Per metre off the zone's main lane, so routes stay on it when they can. constexpr double kShortLeads[4] = { 0.25, 0.5, 1.0, 1.5 }; -constexpr double kJunctionRadiusM = 6.0; -constexpr int32_t kJunctionCandidates = 50; -constexpr int kJunctionLinks = 12; +// Lane-end links reach as far as the query-time links of a temporary lane (kTemporaryRadiusM, kTemporaryLinks). With +// 6 m and 12 tries a lane end next to a block of parallel lane ends spent every try on them: on SEHC the west ends of +// zone_7 never reached the zone_1/zone_3 lanes 7 m away across open floor (no ridge there), so a start outside the zone +// detoured 116 m through zone_2 and zone_1 where a start inside it went straight in 79 m (sim 10/11). +constexpr double kJunctionRadiusM = 8.0; +constexpr int32_t kJunctionCandidates = 80; +constexpr int kJunctionLinks = 24; // Counts created links only. constexpr double kPreferredAttachRadiusM = 6.0; constexpr int32_t kPreferredAttachCandidates = 30; constexpr double kMinLinkM = 0.05; @@ -230,11 +234,18 @@ CompiledGraph compileGraph(const CoarseGraph& coarse, const GridRef& grid, const if (v == u || found.first < kMinLinkM) continue; const Point2 there = graph.nodes[static_cast(v)]; + bool linked = false; if (line_ok(here, there)) + { graph.edges.push_back({ u, v, { here, there }, EdgeKind::kJunction, found.first }); + linked = true; + } if (line_ok(there, here)) + { graph.edges.push_back({ v, u, { there, here }, EdgeKind::kJunction, found.first }); - if (++accepted >= kJunctionLinks) + linked = true; + } + if (linked && ++accepted >= kJunctionLinks) break; } } diff --git a/src/grid_checks.cpp b/src/grid_checks.cpp index c591590..26fae6c 100644 --- a/src/grid_checks.cpp +++ b/src/grid_checks.cpp @@ -93,6 +93,8 @@ std::string PlannerConfig::validate() const error << "corner_radii_m must be finite and not below min_turn_radius_m"; else if (!not_negative(footprint_min_gap_m)) error << "footprint_min_gap_m must be finite and >= 0"; + else if (!not_negative(zone_transition_m)) + error << "zone_transition_m must be finite and >= 0"; else if (std::any_of(footprint_gap_shortcut_raise_m.begin(), footprint_gap_shortcut_raise_m.end(), [&](double v) { return !positive(v); })) error << "footprint_gap_shortcut_raise_m values must be finite and > 0"; else if (!std::isfinite(max_deviation_deg) || max_deviation_deg < 0.0 || max_deviation_deg >= 180.0) diff --git a/src/lattice_cspace.cpp b/src/lattice_cspace.cpp index cc3a01c..e757d10 100644 --- a/src/lattice_cspace.cpp +++ b/src/lattice_cspace.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include @@ -45,10 +46,111 @@ bool hitsCell(double x0, double y0, double x1, double y1, int32_t x, int32_t y, } // namespace LatticeCSpace::LatticeCSpace(LatticeContext& context) - : context_(context), tiles_(&context.memory), blocked_prefix_(&context.memory), gap_margin_(context.config.footprint_min_gap_m) + : context_(context), zone_index_(context.grid, &context.memory, context.request.cancel, &context.deadline), + endpoint_zone_regions_(&context.memory), + tiles_(&context.memory), blocked_prefix_(&context.memory), gap_margin_(context.config.footprint_min_gap_m) { start_floor_ = endFloor(context.request.start); goal_floor_ = endFloor(context.request.goal); + for (const Pose2* end : { &context.request.start, &context.request.goal }) + { + // A free end heading is chosen later. Its circumradius square conservatively includes every possible end overlap; + // the final check computes allowances from the actual selected yaw and rejects any extra region. + const double radius = std::hypot(context.config.half_x_m, context.config.half_y_m); + const double hx = end->has_yaw ? context.config.half_x_m : radius; + const double hy = end->has_yaw ? context.config.half_y_m : radius; + visitFootprintZoneCells(context.grid, end->x, end->y, end->has_yaw ? end->yaw : 0.0, hx, hy, + [&](const FootprintZoneCell& cell) { + if (!end->has_yaw || !headingAllowedInZone(end->yaw, cell.code, context.config.max_deviation_deg)) + { + const uint32_t region = zone_index_.component(cell.index); + if (region != 0) endpoint_zone_regions_.push_back(region); + } + }); + } + std::sort(endpoint_zone_regions_.begin(), endpoint_zone_regions_.end()); + endpoint_zone_regions_.erase(std::unique(endpoint_zone_regions_.begin(), endpoint_zone_regions_.end()), endpoint_zone_regions_.end()); +} + +bool LatticeCSpace::zonePoseFree(double x, double y, double yaw, double sweep_margin, double yaw_sweep, bool near_end) +{ + if (zone_index_.failed()) return false; + if (context_.grid.direction == nullptr) return true; + // This is a necessary-condition filter at the actual pose, not a swept-footprint rejection: an expanded rectangle + // could reject a legal transition. The whole-path verifier decides same-region membership and path-distance timing. + const double pad = near_end ? 0.0 : std::max(0.0, sweep_margin); + const double limit = context_.config.max_deviation_deg; + const double hx = context_.config.half_x_m, hy = context_.config.half_y_m; + const bool may_violate = zone_index_.mayViolate(x, y, yaw, hx, hy, limit); + if (zone_index_.failed()) return false; + if (!may_violate) return true; + if (!near_end) + { + // Cache only proofs of safety: inflate by the entire cell/heading quantisation and allow every yaw in the bin. + // An inconclusive entry is rechecked at the actual pose; endpoint exemptions are never cached as globally safe. + const GridRef& g = context_.grid; + const int32_t ix = static_cast(std::floor((x - g.origin_x) / g.resolution)); + const int32_t iy = static_cast(std::floor((y - g.origin_y) / g.resolution)); + const int bins = context_.config.lattice_heading_bins; + const uint64_t key = (static_cast(static_cast(iy / 32)) << 32) | static_cast(ix / 32); + auto inserted = tiles_.try_emplace(key, &context_.memory, static_cast(32) * 32 * bins); + if (inserted.second) ++context_.info.lattice_tiles_built; + Tile& tile = inserted.first->second; + if (tile.zone_samples.empty()) tile.zone_samples.resize((static_cast(32) * 32 * bins + 3) / 4, 0); + double positive_yaw = std::fmod(yaw, 2.0 * kPi); + if (positive_yaw < 0.0) positive_yaw += 2.0 * kPi; + const int heading = static_cast(std::floor(positive_yaw * bins / (2.0 * kPi) + 0.5)) % bins; + const std::size_t local = (static_cast(iy % 32) * 32 + static_cast(ix % 32)) * bins + heading; + uint8_t& packed = tile.zone_samples[local / 4]; + const unsigned shift = static_cast((local % 4) * 2); + uint8_t cached = static_cast((packed >> shift) & 3u); + const double cx = g.origin_x + (ix + 0.5) * g.resolution; + const double cy = g.origin_y + (iy + 0.5) * g.resolution; + const double bin_yaw = heading * 2.0 * kPi / bins; + const double radius = std::hypot(context_.config.half_x_m, context_.config.half_y_m); + const double quantization = g.resolution / std::sqrt(2.0) + 2.0 * radius * std::sin(kPi / (2.0 * bins)); + const double bin_limit = limit - 180.0 / bins; + if (cached == 0) + { + bool safe = true; + visitFootprintZoneCells(g, cx, cy, bin_yaw, context_.config.half_x_m + quantization, + context_.config.half_y_m + quantization, [&](const FootprintZoneCell& cell) { + if (!headingAllowedInZone(bin_yaw, cell.code, bin_limit)) safe = false; + }); + cached = safe ? 1 : 2; + packed = static_cast(packed | (cached << shift)); + } + const double yaw_error = std::abs(wrapAngle(yaw - bin_yaw)); + const double error = std::hypot(x - cx, y - cy) + 2.0 * radius * std::sin(yaw_error / 2.0); + if (cached == 1 && error + pad <= quantization && yaw_error + yaw_sweep <= kPi / bins) return true; + } + // The lattice keeps the strict per-pose rule: a wrong-way overlap is legal only in an endpoint region. The path rule + // allows an overlap within zone_transition_m of a centre entry, but a single pose cannot know whether the centre will + // enter: an optimistic filter let every pose that turns toward a zone through, the search reached the goal along the + // zone edge, verification rejected it and the search repeated until the budget ran out (test + // DirectionZoneRequiresDetour: 3 s timeout, 21 ms with the strict filter). Lattice paths therefore always satisfy the + // path rule; the graph tier, which checks whole candidates, keeps the transition allowance. + // With transition = 0 the code below reduces to: required_turn must be zero, i.e. the heading is within the limit. + const double transition = 0.0; + const bool endpoint_spin_possible = transition > 0.0 && + (std::hypot(x - context_.request.start.x, y - context_.request.start.y) <= transition + 1e-9 || + std::hypot(x - context_.request.goal.x, y - context_.request.goal.y) <= transition + 1e-9); + const int32_t centre_x = static_cast(std::floor((x - context_.grid.origin_x) / context_.grid.resolution)); + const int32_t centre_y = static_cast(std::floor((y - context_.grid.origin_y) / context_.grid.resolution)); + const uint8_t centre_code = context_.grid.direction[static_cast(centre_y) * context_.grid.width + centre_x]; + bool legal = true; + visitFootprintZoneCells(context_.grid, x, y, yaw, hx, hy, [&](const FootprintZoneCell& cell) { + if (headingAllowedInZone(yaw, cell.code, limit) || + std::binary_search(endpoint_zone_regions_.begin(), endpoint_zone_regions_.end(), + zone_index_.knownComponent(cell.index))) return; + if (transition > 0.0 && centre_code == cell.code) return; // Possibly a different component; final verification decides. + const double angle = (static_cast(cell.code) - 1) * kPi / 4.0; + const double required_turn = std::max(0.0, std::abs(wrapAngle(yaw - angle)) - limit * kPi / 180.0 - 0.03); + const bool can_turn = endpoint_spin_possible || + (2.0 / kPi) * context_.config.min_turn_radius_m * required_turn <= transition + 1e-9; + if (!can_turn || !zone_index_.nearbyDirection(x, y, cell.code, transition)) legal = false; + }); + return legal; } void LatticeCSpace::setGapMargin(double margin) @@ -110,7 +212,7 @@ uint32_t LatticeCSpace::blockedCount(int32_t x0, int32_t y0, int32_t x1, int32_t return at(x1, y1) - at(x0, y1) - at(x1, y0) + at(x0, y0); } -bool LatticeCSpace::poseFree(double x, double y, double yaw, double sweep_margin, double centre_sweep) +bool LatticeCSpace::poseFree(double x, double y, double yaw, double sweep_margin, double centre_sweep, double yaw_sweep) { if (context_.expired()) return false; if (context_.smooth_checks) ++*context_.smooth_checks; @@ -130,6 +232,7 @@ bool LatticeCSpace::poseFree(double x, double y, double yaw, double sweep_margin const double relax = c.lattice_end_relax_radius_m; const bool near_start = std::hypot(x - start.x, y - start.y) + centre_sweep <= relax; const bool near_goal = std::hypot(x - goal.x, y - goal.y) + centre_sweep <= relax; + if (!zonePoseFree(x, y, yaw, sweep_margin, yaw_sweep, near_start || near_goal)) return false; // Away from the ends: full gap plus the sweep bound, conservative. Near an end: the floor of that end without the sweep bound, // because the final check is the authority there and adding the sweep could lock in a robot parked closer than gap plus sweep. double margin = gap_margin_ + std::max(0.0, sweep_margin); @@ -258,7 +361,8 @@ bool LatticeCSpace::segmentLegal(const PathPoint& a, const PathPoint& b) for (int i = 0; i < count; ++i) { const double t = (static_cast(i) + 0.5) / count; - if (!poseFree(a.x + t * dx, a.y + t * dy, a.yaw + t * yaw_delta, sweep, centre_sweep)) return false; + if (!poseFree(a.x + t * dx, a.y + t * dy, a.yaw + t * yaw_delta, sweep, centre_sweep, + std::abs(yaw_delta) / (2.0 * count))) return false; } return true; } diff --git a/src/lattice_internal.h b/src/lattice_internal.h index 03dd336..0b9b383 100644 --- a/src/lattice_internal.h +++ b/src/lattice_internal.h @@ -12,6 +12,7 @@ #include #include "route_planner_internal.h" +#include "footprint_zones.h" namespace lane_route_core { @@ -124,17 +125,22 @@ public: explicit LatticeCSpace(LatticeContext& context); void setGapMargin(double margin); double gapMargin() const { return gap_margin_; } - bool poseFree(double x, double y, double yaw, double sweep_margin = 0.0, double centre_sweep = 0.0); + bool poseFree(double x, double y, double yaw, double sweep_margin = 0.0, double centre_sweep = 0.0, + double yaw_sweep = 0.0); bool segmentLegal(const PathPoint& a, const PathPoint& b); bool spinLegal(double x, double y, double from, double to); private: struct Tile { - Tile(std::pmr::memory_resource* resource, std::size_t size) : samples(resource) { samples.resize((size + 3) / 4, 0); } + Tile(std::pmr::memory_resource* resource, std::size_t size) : samples(resource), zone_samples(resource) + { samples.resize((size + 3) / 4, 0); } std::pmr::vector samples; + std::pmr::vector zone_samples; // Lazy 2-bit conservative footprint-zone checks per cell/heading. }; LatticeContext& context_; + FootprintZoneIndex zone_index_; + std::pmr::vector endpoint_zone_regions_; std::pmr::unordered_map tiles_; std::pmr::vector blocked_prefix_; bool prefix_ready_ = false; @@ -143,6 +149,7 @@ private: double gap_margin_; // [m] Away from endpoints; changing it invalidates tile samples. double endFloor(const Pose2& pose) const; bool buildBlockedPrefix(); + bool zonePoseFree(double x, double y, double yaw, double sweep_margin, double yaw_sweep, bool near_end); uint32_t blockedCount(int32_t x0, int32_t y0, int32_t x1, int32_t y1) const; }; diff --git a/src/path_verifier.cpp b/src/path_verifier.cpp index 0d76b10..95272be 100644 --- a/src/path_verifier.cpp +++ b/src/path_verifier.cpp @@ -3,6 +3,11 @@ #include #include #include +#include +#include +#include + +#include "footprint_zones.h" #include @@ -72,6 +77,118 @@ int zoneViolations(const PathPoint& a, const PathPoint& b, const GridRef& grid, return count; } +struct ZoneEndCell +{ + uint32_t region; + bool active = true; + std::size_t suffix_begin = 0; +}; + +std::vector wrongEndCells(const PathPoint& pose, const GridRef& grid, double deviation_deg, + const PlannerConfig& config, detail::FootprintZoneIndex& index) +{ + std::vector cells; + detail::visitFootprintZoneCells(grid, pose.x, pose.y, pose.yaw, config.half_x_m, config.half_y_m, + [&](const detail::FootprintZoneCell& cell) { + if (!detail::headingAllowedInZone(pose.yaw, cell.code, deviation_deg)) + { + const uint32_t region = index.component(cell.index); + if (region != 0 && std::none_of(cells.begin(), cells.end(), + [&](const ZoneEndCell& existing) { return existing.region == region; })) cells.push_back({region}); + } + }); + return cells; +} + +bool touchesZoneRegion(const PathPoint& pose, uint32_t region, const GridRef& grid, const PlannerConfig& config, + const detail::FootprintZoneIndex& index) +{ + bool touches = false; + detail::visitFootprintZoneCells(grid, pose.x, pose.y, pose.yaw, config.half_x_m, config.half_y_m, + [&](const detail::FootprintZoneCell& cell) { if (index.knownComponent(cell.index) == region) touches = true; }); + return touches; +} + +// Collect wrong-way overlaps by connected region, then compare path distance with sampled centre entries into that +// same region. Endpoint allowances are contiguous; transition allowances can occur before or after a centre entry. +int footprintZoneViolations(const Path& samples, const GridRef& grid, double deviation_deg, const PlannerConfig& config, + std::vector start_cells, std::vector goal_cells, + detail::FootprintZoneIndex& index, const std::atomic* cancel, + const std::chrono::steady_clock::time_point* deadline) +{ + if (grid.direction == nullptr || samples.empty()) return 0; + const auto stopped = [&]() { + return (cancel && cancel->load(std::memory_order_relaxed)) || + (deadline && std::chrono::steady_clock::now() >= *deadline); + }; + for (ZoneEndCell& cell : goal_cells) + { + std::size_t i = samples.size() - 1; + while (i > 0 && touchesZoneRegion(samples[i - 1], cell.region, grid, config, index)) + { + if (stopped()) return -1; + --i; + } + cell.suffix_begin = i; + } + struct Pending { std::size_t sample; uint32_t region; }; + std::vector pending; + std::vector along(samples.size(), 0.0); + for (std::size_t i = 0; i < samples.size(); ++i) + { + if (stopped()) return -1; + const PathPoint& pose = samples[i]; + if (i != 0) along[i] = along[i - 1] + std::hypot(pose.x - samples[i - 1].x, pose.y - samples[i - 1].y); + for (ZoneEndCell& cell : start_cells) + if (cell.active && !touchesZoneRegion(pose, cell.region, grid, config, index)) cell.active = false; + if (!index.mayViolate(pose.x, pose.y, pose.yaw, config.half_x_m, config.half_y_m, deviation_deg)) continue; + std::vector rejected_regions; + detail::visitFootprintZoneCells(grid, pose.x, pose.y, pose.yaw, config.half_x_m, config.half_y_m, + [&](const detail::FootprintZoneCell& cell) { + if (detail::headingAllowedInZone(pose.yaw, cell.code, deviation_deg)) return; + uint32_t region = index.knownComponent(cell.index); + if (region == 0) region = index.component(cell.index); + if (region == 0) return; + const bool allowed_start = std::any_of(start_cells.begin(), start_cells.end(), + [&](const ZoneEndCell& allowed) { return allowed.active && allowed.region == region; }); + const bool allowed_goal = std::any_of(goal_cells.begin(), goal_cells.end(), + [&](const ZoneEndCell& allowed) { return i >= allowed.suffix_begin && allowed.region == region; }); + if (!allowed_start && !allowed_goal && + std::find(rejected_regions.begin(), rejected_regions.end(), region) == rejected_regions.end()) + rejected_regions.push_back(region); + }); + if (index.failed()) return -1; + for (uint32_t region : rejected_regions) pending.push_back({i, region}); + } + if (pending.empty()) return 0; + if (config.zone_transition_m <= 0.0) return static_cast(pending.size()); + + // Components that appear here were already flood-filled above; no whole-map label array is needed. Arc distances + // are monotone, so each violation needs one binary search in the centre-entry distances of its own region. + std::unordered_map> centre_distances; + for (const Pending& entry : pending) centre_distances.try_emplace(entry.region); + for (std::size_t i = 0; i < samples.size(); ++i) + { + if (stopped()) return -1; + const double fx = std::floor((samples[i].x - grid.origin_x) / grid.resolution); + const double fy = std::floor((samples[i].y - grid.origin_y) / grid.resolution); + if (fx < 0.0 || fy < 0.0 || fx >= grid.width || fy >= grid.height) continue; + const int32_t cell = static_cast(fy) * grid.width + static_cast(fx); + const uint32_t region = index.knownComponent(cell); + const auto found = centre_distances.find(region); + if (found != centre_distances.end()) found->second.push_back(along[i]); + } + int violations = 0; + for (const Pending& entry : pending) + { + const auto& distances = centre_distances.find(entry.region)->second; + const double here = along[entry.sample]; + const auto found = std::lower_bound(distances.begin(), distances.end(), here - config.zone_transition_m); + if (found == distances.end() || *found > here + config.zone_transition_m) ++violations; + } + return violations; +} + bool kinkMetrics(const Path& path, double bend_limit_deg, int* kinks, double* max_bend_deg, const std::atomic* cancel, const std::chrono::steady_clock::time_point* deadline) { @@ -215,6 +332,17 @@ PathCheck verifyPath(const Path& path, const GridRef& grid, double deviation_deg if (!std::isfinite(point.x) || !std::isfinite(point.y) || !std::isfinite(point.yaw)) return check; + std::vector start_zone_cells, goal_zone_cells; + detail::FootprintZoneIndex zone_index(grid, std::pmr::get_default_resource(), cancel, deadline); + Path zone_samples; + if (grid.direction != nullptr) + { + start_zone_cells = wrongEndCells(path.front(), grid, config.max_deviation_deg, config, zone_index); + goal_zone_cells = wrongEndCells(path.back(), grid, config.max_deviation_deg, config, zone_index); + if (zone_index.failed()) return check; + zone_samples.reserve(path.size()); + } + // The bend limit follows the tightest legal curve (a 0.4 m floor turns 14.3 deg over 0.1 m), and a sharp corner may bend up // to max_kink_deg; the curvature test below still tells a sharp corner from a too-tight curve. const double kink_rad = config.max_kink_deg * kPi / 180.0; @@ -247,13 +375,36 @@ PathCheck verifyPath(const Path& path, const GridRef& grid, double deviation_deg } check.zone_violations += zoneViolations(a, b, grid, deviation_deg); const int samples = std::max({ 1, static_cast(std::ceil(distance / 0.01)), static_cast(std::ceil(std::abs(turn) / 0.03)) }); + if (corner && grid.direction != nullptr) + { + const int spin_samples = std::max(1, static_cast(std::ceil(std::abs(turn) / 0.03))); + for (int j = 1; j <= spin_samples; ++j) + zone_samples.push_back({a.x, a.y, a.yaw + turn * j / spin_samples, 0.0}); + } + if (grid.direction != nullptr) + { + // Match the footprint-gap sampling contract. The actual swept boundary between samples is not reconstructed. + const int zone_steps = std::max({ 1, static_cast(std::ceil(distance / 0.04)), + static_cast(std::ceil(std::abs(turn) / 0.03)) }); + for (int j = i == 0 ? 0 : 1; j <= zone_steps; ++j) + { + const double t = static_cast(j) / zone_steps; + zone_samples.push_back({a.x + t * dx, a.y + t * dy, corner ? b.yaw : a.yaw + t * turn, 0.0}); + } + } for (int j = 0; j <= samples; ++j) { const double t = static_cast(j) / samples; - if (footprintCollides(grid, a.x + t * dx, a.y + t * dy, a.yaw + t * turn, config.half_x_m, config.half_y_m)) + const double x = a.x + t * dx, y = a.y + t * dy, yaw = a.yaw + t * turn; + if (footprintCollides(grid, x, y, yaw, config.half_x_m, config.half_y_m)) ++check.footprint_collisions; } } + const int body_zone_violations = footprintZoneViolations(zone_samples, grid, config.max_deviation_deg, config, + std::move(start_zone_cells), std::move(goal_zone_cells), + zone_index, cancel, deadline); + if (body_zone_violations < 0) return check; + check.zone_violations += body_zone_violations; check.self_crossings = selfCrossings(path, cancel, deadline); if (check.self_crossings < 0) return check; check.valid = check.zone_violations == 0 && check.footprint_collisions == 0 && check.kinks == 0 && diff --git a/src/route_graph_path.cpp b/src/route_graph_path.cpp index 0f59a3a..ec9d7de 100644 --- a/src/route_graph_path.cpp +++ b/src/route_graph_path.cpp @@ -184,8 +184,11 @@ bool kinkLegal(const Point2& vertex, double from, double to, const QueryContext& const double delta = wrapAngle(to - from); const int samples = std::max(1, static_cast(std::ceil(std::abs(delta) / 0.03))); for (int i = 0; i <= samples; ++i) - if (footprintCollides(grid, vertex.x, vertex.y, from + delta * i / samples, context.config.half_x_m, context.config.half_y_m)) + { + const double yaw = from + delta * i / samples; + if (footprintCollides(grid, vertex.x, vertex.y, yaw, context.config.half_x_m, context.config.half_y_m)) return false; + } return true; } @@ -524,7 +527,7 @@ Candidate constructGreedyCandidate(const std::vector& route, const Quer BuildFailure failure; std::vector radii; if (buildPath(merged, start, goal, context, &path, &failure, &radii) && - verifyPath(path, context->verify_grid, context->deviation_deg, context->config, context->cancel).valid && + verifyPath(path, context->verify_grid, context->deviation_deg, context->config, context->cancel, &context->deadline).valid && freeClearanceOk(path, context->verify_grid, context->min_mm)) { result.ok = true; @@ -598,7 +601,7 @@ bool candidateLegal(const Path& path, const QueryContext& context, const Pose2& { const GridRef& grid = context.verify_grid; const PlannerConfig& config = context.config; - if (!verifyPath(path, grid, context.deviation_deg, config, context.cancel).valid || !endpointOk(path, start, goal) || + if (!verifyPath(path, grid, context.deviation_deg, config, context.cancel, &context.deadline).valid || !endpointOk(path, start, goal) || !freeClearanceOk(path, grid, context.min_mm) || blockedEndpointTurn(path, grid, config.half_x_m, config.half_y_m) != nullptr || !checkFootprintGap(path, grid, config.footprint_min_gap_m, config.half_x_m, config.half_y_m, context.cancel, nullptr, true).valid) return false; diff --git a/src/route_graph_tier.cpp b/src/route_graph_tier.cpp index c1eeaf4..7d859db 100644 --- a/src/route_graph_tier.cpp +++ b/src/route_graph_tier.cpp @@ -37,7 +37,7 @@ bool hasSoftCost(const uint8_t* master, std::size_t count) /** 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* changed, TimePoint deadline, bool allow_soft_fallback, const GridRef& verify_grid, const PlannerConfig& config, Path* path, - PathCheck* check, PlanInfo* info, const std::atomic* cancel) + PathCheck* check, PlanInfo* info, const std::atomic* cancel, GraphTrace* trace, const char* trace_source) { 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), @@ -92,6 +92,30 @@ bool planCore(const CompiledGraph& graph, const Pose2& start, const Pose2& goal, } } + GraphTraceRun* trace_run = nullptr; + if (trace != nullptr) + { + trace->runs.emplace_back(); + trace_run = &trace->runs.back(); + trace_run->deviation_deg = dev; + trace_run->min_turn_radius_m = config.min_turn_radius_m; + trace_run->max_kink_deg = config.max_kink_deg; + trace_run->voronoi_weight = kVoronoiWeight; + trace_run->corner_radii_m = config.corner_radii_m; + trace_run->source = trace_source; + trace_run->base_nodes = query.baseNodes(); + trace_run->base_edges = query.baseEdges(); + trace_run->start_node = s; + trace_run->goal_node = g; + trace_run->nodes.reserve(static_cast(query.nodeCount())); + trace_run->edges.reserve(static_cast(query.edgeCount())); + for (int32_t i = 0; i < query.nodeCount(); ++i) trace_run->nodes.push_back(query.node(i)); + for (int32_t i = 0; i < query.edgeCount(); ++i) trace_run->edges.push_back(query.edge(i)); + trace_run->factors = factors; + for (int32_t i = 0; i < query.edgeCount(); ++i) + if (blocked[static_cast(i)] != 0) trace_run->initially_blocked_edges.push_back(i); + } + std::string reason; std::vector route; for (int pass = 0; pass < 2; ++pass) @@ -116,28 +140,48 @@ bool planCore(const CompiledGraph& graph, const Pose2& start, const Pose2& goal, compiledEdgeFactors(graph, master, &factors); for (const GraphEdge& edge : query.extraEdges()) factors.push_back(edgeFactor(edge.points, master, grid)); + if (trace_run != nullptr) trace_run->neutral_factors = factors; reason.clear(); } std::set> blocked_pairs; for (int attempt = 0; attempt < config.max_route_attempts; ++attempt) { + GraphTraceAttempt* trace_attempt = nullptr; + if (trace_run != nullptr) + { + trace_run->attempts.emplace_back(); + trace_attempt = &trace_run->attempts.back(); + trace_attempt->pass = pass; + trace_attempt->attempt = attempt; + } + const auto trace_reason = [&](const auto& value) { + if (trace_attempt != nullptr) + { + trace_attempt->reason = value; + if (trace_attempt->reason.empty()) trace_attempt->reason = "unspecified_rejection"; + } + }; if (context.expired()) { reason = "timeout"; + if (trace_attempt != nullptr) + trace_reason(context.cancel && context.cancel->load(std::memory_order_relaxed) ? "cancelled" : reason); break; } timer = Clock::now(); const bool found = searchRoute(query, s, g, blocked, blocked_pairs, max_straight_m, config.min_turn_radius_m, factors, &route, context.cancel); info->search_ms += msSince(timer); + if (trace_attempt != nullptr && found) trace_attempt->route = route; if (!found) { - if (context.cancel && context.cancel->load(std::memory_order_relaxed)) break; + if (context.cancel && context.cancel->load(std::memory_order_relaxed)) { trace_reason("cancelled"); break; } // The graph is not complete, so only a component test on the grid may call this no-route. if (enclosedByObstacles(grid, start_point, goal_point, context.cancel)) reason = "no_route_enclosed"; else if (attempt == 0) reason = "graph_disconnected"; + if (trace_attempt != nullptr) trace_reason(reason.empty() ? "search_exhausted" : "search_exhausted: " + reason); break; } @@ -153,9 +197,11 @@ bool planCore(const CompiledGraph& graph, const Pose2& start, const Pose2& goal, } if (bad >= 0) { + if (trace_attempt != nullptr) trace_attempt->rejected_edge = bad; blocked[static_cast(bad)] = 1; ++info->retries; reason = "edge_blocked"; + trace_reason(reason); continue; } @@ -165,6 +211,7 @@ bool planCore(const CompiledGraph& graph, const Pose2& start, const Pose2& goal, if (context.expired()) { reason = "timeout"; + trace_reason(reason); break; } @@ -173,8 +220,14 @@ bool planCore(const CompiledGraph& graph, const Pose2& start, const Pose2& goal, const Point2 corner = candidate.why.corner; if (candidate.ok) { + if (trace_attempt != nullptr) trace_attempt->candidate_length_m = pathLength(candidate.path); timer = Clock::now(); - PathCheck path_check = verifyPath(candidate.path, verify_grid, dev, config, context.cancel); + PathCheck path_check = verifyPath(candidate.path, verify_grid, dev, config, context.cancel, &deadline); + if (trace_attempt != nullptr) + { + trace_attempt->zone_violations = path_check.zone_violations; + trace_attempt->footprint_collisions = path_check.footprint_collisions; + } bool ends_ok = endpointOk(candidate.path, start, goal); bool clear_ok = freeClearanceOk(candidate.path, verify_grid, context.min_mm); const char* turn_blocked = blockedEndpointTurn(candidate.path, verify_grid, config.half_x_m, config.half_y_m); @@ -182,6 +235,7 @@ bool planCore(const CompiledGraph& graph, const Pose2& start, const Pose2& goal, if (turn_blocked != nullptr) { reason = turn_blocked; + trace_reason(reason); break; } @@ -210,7 +264,7 @@ bool planCore(const CompiledGraph& graph, const Pose2& start, const Pose2& goal, if (!alternative.ok) continue; timer = Clock::now(); - const PathCheck alternative_check = verifyPath(alternative.path, verify_grid, dev, config, context.cancel); + const PathCheck alternative_check = verifyPath(alternative.path, verify_grid, dev, config, context.cancel, &deadline); const bool usable = alternative_check.valid && endpointOk(alternative.path, start, goal) && freeClearanceOk(alternative.path, verify_grid, context.min_mm) && blockedEndpointTurn(alternative.path, verify_grid, config.half_x_m, config.half_y_m) == nullptr; @@ -238,7 +292,13 @@ bool planCore(const CompiledGraph& graph, const Pose2& start, const Pose2& goal, reference_checked = true; } candidate = std::move(alternative); + if (trace_attempt != nullptr) trace_attempt->candidate_length_m = length; path_check = alternative_check; + if (trace_attempt != nullptr) + { + trace_attempt->zone_violations = path_check.zone_violations; + trace_attempt->footprint_collisions = path_check.footprint_collisions; + } gap = alternative_gap; ends_ok = true; clear_ok = true; @@ -248,6 +308,7 @@ bool planCore(const CompiledGraph& graph, const Pose2& start, const Pose2& goal, if (context.expired()) { reason = "timeout"; + trace_reason(reason); break; } } @@ -263,11 +324,13 @@ bool planCore(const CompiledGraph& graph, const Pose2& start, const Pose2& goal, double reference = 0.0; const bool known = cachedStandableReference(verify_grid, start_point, goal_point, dev, bound, &reference, standability, reference_memo, context.cancel, &deadline); + if (trace_attempt != nullptr && known) trace_attempt->reference_length_m = reference; info->verify_ms += msSince(timer); if (known && length > config.route_too_long_ratio * reference + config.route_too_long_margin_m) { info->graph_reference_length_m = reference; reason = "route_too_long"; + trace_reason(reason); break; } } @@ -282,6 +345,7 @@ bool planCore(const CompiledGraph& graph, const Pose2& start, const Pose2& goal, info->gap_shortcut_raise_m = raise_used; info->min_gap_m = gap.min_gap_m; info->gap_exemption_used = gap.exemption_used; + trace_reason("verified"); return true; } why = gap_checked && !gap.valid ? "footprint_gap_below_minimum" : @@ -292,6 +356,7 @@ bool planCore(const CompiledGraph& graph, const Pose2& start, const Pose2& goal, if (candidate.vertices.empty()) { reason = why; + trace_reason(reason); break; } std::vector> pairs; @@ -324,11 +389,14 @@ bool planCore(const CompiledGraph& graph, const Pose2& start, const Pose2& goal, if (pairs.empty()) { reason = why; + trace_reason(reason); break; } blocked_pairs.insert(pairs.begin(), pairs.end()); + if (trace_attempt != nullptr) trace_attempt->blocked_pairs_added = pairs; ++info->retries; reason = why; + trace_reason(reason); } } info->reason = reason.empty() ? "fallback" : reason; @@ -337,10 +405,11 @@ bool planCore(const CompiledGraph& graph, const Pose2& start, const Pose2& goal, /** One rung: the normal core, then a ridge rebuilt from the live grid around start and goal when the map changed. */ bool planRung(const CompiledGraph& graph, const RouteRequest& request, const GridRef& live, TimePoint deadline, const PlannerConfig& config, - const RidgeBackend& backend, Path* path, PathCheck* check, PlanInfo* info) + const RidgeBackend& backend, Path* path, PathCheck* check, PlanInfo* info, GraphTrace* trace) { const std::vector* changed = request.changed_boxes.empty() ? nullptr : &request.changed_boxes; - if (planCore(graph, request.start, request.goal, live, changed, deadline, true, live, config, path, check, info, request.cancel)) + 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)) || changed == nullptr || !backend.build_coarse || info->reason == "no_route_enclosed" || info->reason == "timeout") return false; @@ -398,7 +467,8 @@ bool planRung(const CompiledGraph& graph, const RouteRequest& request, const Gri { const CompiledGraph live_graph = compileGraph(coarse, window, window.cost, graph.deviation_deg, config, backend, request.cancel); if (Clock::now() < deadline) - ok = planCore(live_graph, request.start, request.goal, window, nullptr, deadline, false, live, config, path, check, &live_info, request.cancel); + ok = planCore(live_graph, request.start, request.goal, window, nullptr, deadline, false, live, config, path, check, + &live_info, request.cancel, trace, "live_ridge"); } info->retries += live_info.retries; info->gap_failures += live_info.gap_failures; @@ -431,7 +501,7 @@ bool planRung(const CompiledGraph& graph, const RouteRequest& request, const Gri bool planGraphTier(const GraphTierInput& input, GraphTierOutput output) { return planRung(input.graph, input.request, input.live, input.deadline, input.config, input.backend, - &output.path, &output.check, &output.info); + &output.path, &output.check, &output.info, input.trace); } } // namespace detail diff --git a/src/route_planner.cpp b/src/route_planner.cpp index 9a9509c..6c480e7 100644 --- a/src/route_planner.cpp +++ b/src/route_planner.cpp @@ -44,6 +44,12 @@ double polylineLength(const Path& path) PlanResult planRoute(const GraphProvider& graphs, const RouteRequest& request, const GridRef& live, const PlannerConfig& config, const RidgeBackend& backend) +{ + return planRoute(graphs, request, live, config, backend, nullptr); +} + +PlanResult planRoute(const GraphProvider& graphs, const RouteRequest& request, const GridRef& live, const PlannerConfig& config, + const RidgeBackend& backend, GraphTrace* trace) { PlanResult result; const TimePoint began = Clock::now(); @@ -156,7 +162,7 @@ PlanResult planRoute(const GraphProvider& graphs, const RouteRequest& request, c else { result.info.live_ridge.clear(); - graph_ok = detail::planGraphTier({ *graph, request, live, deadline, tight_corners ? regular : config, backend }, + graph_ok = detail::planGraphTier({ *graph, request, live, deadline, tight_corners ? regular : config, backend, trace }, { result.path, result.check, result.info }); const bool detour = graph_ok && polylineLength(result.path) > config.suspicious_ratio * chord + config.suspicious_margin_m; const bool stopped = (request.cancel && request.cancel->load(std::memory_order_relaxed)) || Clock::now() >= deadline || @@ -167,7 +173,7 @@ PlanResult planRoute(const GraphProvider& graphs, const RouteRequest& request, c PathCheck tight_check; PlanInfo tight_info = result.info; tight_info.live_ridge.clear(); - const bool tight_ok = detail::planGraphTier({ *graph, request, live, deadline, config, backend }, + const bool tight_ok = detail::planGraphTier({ *graph, request, live, deadline, config, backend, trace }, { tight_path, tight_check, tight_info }); // A tight corner must buy a clearly shorter path; otherwise the large-radius shape stays. if (tight_ok && (!graph_ok || polylineLength(tight_path) < (1.0 - kTightMinSaving) * polylineLength(result.path))) diff --git a/src/route_planner_internal.h b/src/route_planner_internal.h index 2c64a4e..8adae2e 100644 --- a/src/route_planner_internal.h +++ b/src/route_planner_internal.h @@ -161,6 +161,7 @@ struct GraphTierInput TimePoint deadline; const PlannerConfig& config; const RidgeBackend& backend; + GraphTrace* trace = nullptr; }; struct GraphTierOutput diff --git a/test/lane_route_core_test.cpp b/test/lane_route_core_test.cpp index b060e59..6fd0f31 100644 --- a/test/lane_route_core_test.cpp +++ b/test/lane_route_core_test.cpp @@ -22,6 +22,7 @@ #include "../src/lattice_internal.h" #include "../src/standability.h" +#include "../src/footprint_zones.h" using namespace lane_route_core; @@ -1544,6 +1545,11 @@ TEST(Lattice, SameStartAndGoal) TEST(Lattice, InvalidParametersAreRejected) { PlannerConfig config = latticeConfig(); + config.zone_transition_m = -0.01; + EXPECT_FALSE(config.validate().empty()); + config.zone_transition_m = 0.0; + EXPECT_TRUE(config.validate().empty()); + config = latticeConfig(); config.lattice_heading_bins = 71; EXPECT_FALSE(config.validate().empty()); config = latticeConfig(); @@ -2443,3 +2449,285 @@ TEST(Standability, UnknownCellsAreCheckedDespiteHighLethalClearance) EXPECT_EQ(tests, 1u); EXPECT_EQ(rejected, 1u); } + +TEST(FootprintZones, OppositeZoneAcrossNarrowGapIsRejected) +{ + LatticeTestGrid map(500, 220); + GridRef grid = map.view(); + grid.resolution = 0.01; + for (int x = 180; x < 310; ++x) + { + for (int y = 0; y < 85; ++y) map.direction[static_cast(y) * map.width + x] = 1; + for (int y = 116; y < map.height; ++y) map.direction[static_cast(y) * map.width + x] = 5; + } + PlannerConfig config = latticeConfig(); + config.half_x_m = 0.511; config.half_y_m = 0.1955; + const Path path{{4.0, 1.0, kPi, 0.0}, {1.0, 1.0, kPi, 0.0}}; + const PathCheck check = verifyPath(path, grid, 0.01, config); + EXPECT_FALSE(check.valid); + EXPECT_GT(check.zone_violations, 0); + RouteRequest request = latticeRequest(pose(4.0, 1.0, kPi), pose(1.0, 1.0, kPi)); + PlanInfo info; + const auto deadline = detail::Clock::now() + std::chrono::seconds(10); + detail::LatticeMemory memory(16 * 1024 * 1024); + detail::LatticeContext context{request, grid, config, 0.01, deadline, info, memory}; + detail::LatticeCSpace space(context); + EXPECT_FALSE(space.poseFree(2.5, 1.0, kPi)); + EXPECT_FALSE(space.segmentLegal({2.6, 1.0, kPi, 0.0}, {2.4, 1.0, kPi, 0.0})); +} + +TEST(FootprintZones, OverlapWithCompatibleDirectionIsAllowed) +{ + LatticeTestGrid map(500, 220); + GridRef grid = map.view(); grid.resolution = 0.01; + for (int x = 180; x < 310; ++x) + { + for (int y = 0; y < 85; ++y) map.direction[static_cast(y) * map.width + x] = 5; + for (int y = 116; y < map.height; ++y) map.direction[static_cast(y) * map.width + x] = 5; + } + PlannerConfig config = latticeConfig(); + config.half_x_m = 0.511; config.half_y_m = 0.1955; + const Path path{{4.0, 1.0, kPi, 0.0}, {1.0, 1.0, kPi, 0.0}}; + const PathCheck check = verifyPath(path, grid, 0.01, config); + EXPECT_TRUE(check.valid); + EXPECT_EQ(check.zone_violations, 0); + RouteRequest request = latticeRequest(pose(4.0, 1.0, kPi), pose(1.0, 1.0, kPi)); + PlanInfo info; + const auto deadline = detail::Clock::now() + std::chrono::seconds(10); + detail::LatticeMemory memory(16 * 1024 * 1024); + detail::LatticeContext context{request, grid, config, 0.01, deadline, info, memory}; + detail::LatticeCSpace space(context); + EXPECT_TRUE(space.poseFree(2.5, 1.0, kPi)); +} + +TEST(FootprintZones, InitialOverlapMayBeLeftButNotReentered) +{ + LatticeTestGrid map(500, 220); + GridRef grid = map.view(); grid.resolution = 0.01; + for (int x = 245; x < 250; ++x) + for (int y = 80; y < 85; ++y) map.direction[static_cast(y) * map.width + x] = 1; + PlannerConfig config = latticeConfig(); + config.half_x_m = 0.511; config.half_y_m = 0.1955; + const Path leaves{{2.0, 1.0, kPi, 0.0}, {1.0, 1.0, kPi, 0.0}}; + const PathCheck good = verifyPath(leaves, grid, 0.01, config); + EXPECT_TRUE(good.valid); + const Path approaches{{3.1, 1.0, kPi, 0.0}, {2.0, 1.0, kPi, 0.0}}; + EXPECT_TRUE(verifyPath(approaches, grid, 0.01, config).valid); + const Path reenters{{2.0, 1.0, kPi, 0.0}, {1.0, 1.0, kPi, 0.0}, {3.1, 1.0, kPi, 0.0}}; + const PathCheck bad = verifyPath(reenters, grid, 0.01, config); + EXPECT_FALSE(bad.valid); + EXPECT_GT(bad.zone_violations, 0); +} + +TEST(FootprintZones, EndpointSpinCannotEnterANewIncompatibleZoneCell) +{ + LatticeTestGrid map(500, 220); + GridRef grid = map.view(); grid.resolution = 0.01; + map.direction[static_cast(100) * map.width + 200] = 5; + PlannerConfig config = latticeConfig(); + config.half_x_m = 0.20; config.half_y_m = 0.10; + const Path spin{{2.005, 1.005, 0.0, 0.0}, {2.005, 1.005, kPi, 0.0}}; + EXPECT_TRUE(verifyPath(spin, grid, 0.01, config).valid); + // The rotated rectangle reaches this cell, though neither end pose does. + map.direction[static_cast(114) * map.width + 214] = 5; + const PathCheck check = verifyPath(spin, grid, 0.01, config); + EXPECT_FALSE(check.valid); + EXPECT_GT(check.zone_violations, 0); +} + +TEST(FootprintZones, EndpointAllowanceFollowsTheConnectedZone) +{ + LatticeTestGrid map(500, 220); + GridRef grid = map.view(); grid.resolution = 0.01; + for (int x = 120; x < 250; ++x) + for (int y = 80; y < 85; ++y) map.direction[static_cast(y) * map.width + x] = 1; + PlannerConfig config = latticeConfig(); + config.half_x_m = 0.511; config.half_y_m = 0.1955; + const Path leaves{{2.0, 1.0, kPi, 0.0}, {0.6, 1.0, kPi, 0.0}}; + EXPECT_TRUE(verifyPath(leaves, grid, 0.01, config).valid); + RouteRequest request = latticeRequest(pose(2.0, 1.0, kPi), pose(0.6, 1.0, kPi)); + PlanInfo info; + const auto deadline = detail::Clock::now() + std::chrono::seconds(10); + detail::LatticeMemory memory(16 * 1024 * 1024); + detail::LatticeContext context{request, grid, config, 0.01, deadline, info, memory}; + detail::LatticeCSpace space(context); + EXPECT_TRUE(space.poseFree(1.5, 1.0, kPi)); + request.start.has_yaw = false; + PlanInfo free_yaw_info; + detail::LatticeMemory free_yaw_memory(16 * 1024 * 1024); + detail::LatticeContext free_yaw_context{request, grid, config, 0.01, deadline, free_yaw_info, free_yaw_memory}; + detail::LatticeCSpace free_yaw_space(free_yaw_context); + EXPECT_TRUE(free_yaw_space.poseFree(1.5, 1.0, kPi)); +} + +TEST(FootprintZones, EndpointAllowanceDoesNotCoverAnotherSameDirectionRegion) +{ + LatticeTestGrid map(500, 220); + GridRef grid = map.view(); grid.resolution = 0.01; + for (int y = 80; y < 85; ++y) + { + for (int x = 245; x < 250; ++x) map.direction[static_cast(y) * map.width + x] = 1; + for (int x = 120; x < 130; ++x) map.direction[static_cast(y) * map.width + x] = 1; + } + PlannerConfig config = latticeConfig(); + config.half_x_m = 0.511; config.half_y_m = 0.1955; + const Path path{{2.0, 1.0, kPi, 0.0}, {0.6, 1.0, kPi, 0.0}}; + const PathCheck check = verifyPath(path, grid, 0.01, config); + EXPECT_FALSE(check.valid); + EXPECT_GT(check.zone_violations, 0); +} + +TEST(GraphTrace, CapturesQueryEdgesAndDijkstraAttempt) +{ + PlannerConfig config = defaultConfig(); + const RidgeBackend backend = makeRidgeBackend(config); + TestMap map(200, 60); + map.finish(config); + const GraphProvider provider = map.provider(config, backend); + RouteRequest request; + request.start = pose(1.0, 1.5, 0.0); + request.goal = pose(8.0, 1.5, 0.0); + GraphTrace trace; + const PlanResult result = planRoute(provider, request, map.compileGrid(), config, backend, &trace); + ASSERT_TRUE(result.ok) << result.info.reason; + ASSERT_FALSE(trace.runs.empty()); + const GraphTraceRun& run = trace.runs.front(); + EXPECT_EQ(run.source, "compiled"); + ASSERT_GT(run.nodes.size(), static_cast(run.goal_node)); + EXPECT_EQ(run.factors.size(), run.edges.size()); + EXPECT_GT(run.edges.size(), static_cast(run.base_edges)); + ASSERT_FALSE(run.attempts.empty()); + bool saw_verified_route = false; + for (const GraphTraceAttempt& attempt : run.attempts) + { + for (int32_t edge : attempt.route) + { + EXPECT_GE(edge, 0); + EXPECT_LT(static_cast(edge), run.edges.size()); + } + saw_verified_route = saw_verified_route || (attempt.reason == "verified" && !attempt.route.empty()); + } + EXPECT_TRUE(saw_verified_route); + const PlanResult without_trace = planRoute(provider, request, map.compileGrid(), config, backend); + ASSERT_TRUE(without_trace.ok) << without_trace.info.reason; + ASSERT_EQ(without_trace.path.size(), result.path.size()); + for (std::size_t i = 0; i < result.path.size(); ++i) + { + EXPECT_DOUBLE_EQ(without_trace.path[i].x, result.path[i].x); + EXPECT_DOUBLE_EQ(without_trace.path[i].y, result.path[i].y); + EXPECT_DOUBLE_EQ(without_trace.path[i].yaw, result.path[i].yaw); + } +} + +TEST(FootprintZones, RegionsMatchEightConnectedReferenceGraphZones) +{ + LatticeTestGrid map(20, 20); + map.direction[5 * map.width + 5] = 1; + map.direction[6 * map.width + 6] = 1; + map.direction[10 * map.width + 10] = 1; + map.direction[5 * map.width + 6] = 2; + GridRef grid = map.view(); + detail::FootprintZoneIndex index(grid); + const uint32_t first = index.component(5 * map.width + 5); + ASSERT_NE(first, 0u); + EXPECT_EQ(index.component(6 * map.width + 6), first); + EXPECT_NE(index.component(10 * map.width + 10), first); + EXPECT_NE(index.component(5 * map.width + 6), first); +} + +TEST(FootprintZones, SideEntryUsesPathDistanceAndZeroDisablesTransition) +{ + LatticeTestGrid map(600, 600); + GridRef grid = map.view(); grid.resolution = 0.01; + for (int y = 0; y < map.height; ++y) + for (int x = 250; x < map.width; ++x) map.direction[static_cast(y) * map.width + x] = 1; + PlannerConfig config = latticeConfig(); + config.half_x_m = 0.511; config.half_y_m = 0.1955; config.max_deviation_deg = 10.0; + config.zone_transition_m = 1.0; + Path path; + constexpr double radius = 1.5; + for (int i = 0; i <= 90; ++i) + { + const double t = (kPi / 2.0) * i / 90.0; + path.push_back({1.0 + radius * (1.0 - std::cos(t)), 1.0 + radius * std::sin(t), kPi / 2.0 - t, -1.0 / radius}); + } + for (int i = 1; i <= 50; ++i) path.push_back({2.5 + 2.0 * i / 50.0, 2.5, 0.0, 0.0}); + const PathCheck allowed = verifyPath(path, grid, 10.0, config); + EXPECT_TRUE(allowed.valid) << allowed.zone_violations; + RouteRequest request = latticeRequest(pose(path.front().x, path.front().y, path.front().yaw), + pose(path.back().x, path.back().y, path.back().yaw)); + PlanInfo info; + const auto deadline = detail::Clock::now() + std::chrono::seconds(10); + detail::LatticeMemory memory(16 * 1024 * 1024); + detail::LatticeContext context{request, grid, config, 10.0, deadline, info, memory}; + detail::LatticeCSpace space(context); + // The lattice keeps the strict per-pose rule (see LatticeCSpace::zonePoseFree): this transition pose is legal on the + // whole path above but not as a lattice state, so lattice paths always satisfy the path rule. + EXPECT_FALSE(space.poseFree(path[69].x, path[69].y, path[69].yaw)); + config.zone_transition_m = 0.0; + const PathCheck blocked = verifyPath(path, grid, 10.0, config); + EXPECT_FALSE(blocked.valid); + EXPECT_GT(blocked.zone_violations, 0); +} + +TEST(FootprintZones, LongWrongWayOverlapWithoutCentreEntryIsRejected) +{ + LatticeTestGrid map(600, 220); + GridRef grid = map.view(); grid.resolution = 0.01; + for (int y = 115; y < 130; ++y) + for (int x = 150; x < 450; ++x) map.direction[static_cast(y) * map.width + x] = 5; + PlannerConfig config = latticeConfig(); + config.half_x_m = 0.511; config.half_y_m = 0.1955; + config.max_deviation_deg = 90.0; config.zone_transition_m = 1.0; + const Path path{{0.8, 1.0, 0.0, 0.0}, {5.2, 1.0, 0.0, 0.0}}; + const PathCheck check = verifyPath(path, grid, 90.0, config); + EXPECT_FALSE(check.valid); + EXPECT_GT(check.zone_violations, 0); + RouteRequest request = latticeRequest(pose(0.8, 1.0, 0.0), pose(5.2, 1.0, 0.0)); + PlanInfo info; + const auto deadline = detail::Clock::now() + std::chrono::seconds(10); + detail::LatticeMemory memory(16 * 1024 * 1024); + detail::LatticeContext context{request, grid, config, 90.0, deadline, info, memory}; + detail::LatticeCSpace space(context); + EXPECT_FALSE(space.poseFree(2.5, 1.0, 0.0)); +} + +TEST(FootprintZones, BodyUsesQueryLimitWhileCentreUsesRung) +{ + LatticeTestGrid map(500, 220); + GridRef grid = map.view(); grid.resolution = 0.01; + map.direction[static_cast(120) * map.width + 240] = 1; + PlannerConfig config = latticeConfig(); + config.half_x_m = 0.511; config.half_y_m = 0.1955; config.max_deviation_deg = 45.0; + config.zone_transition_m = 0.0; + RouteRequest request = latticeRequest(pose(1.0, 1.0, 0.0), pose(4.0, 1.0, 0.0)); + const auto deadline = detail::Clock::now() + std::chrono::seconds(10); + PlanInfo allowed_info; + detail::LatticeMemory allowed_memory(16 * 1024 * 1024); + detail::LatticeContext allowed{request, grid, config, 0.01, deadline, allowed_info, allowed_memory}; + detail::LatticeCSpace allowed_space(allowed); + EXPECT_TRUE(allowed_space.poseFree(2.0, 1.0, kPi / 6.0)); + config.max_deviation_deg = 10.0; + PlanInfo blocked_info; + detail::LatticeMemory blocked_memory(16 * 1024 * 1024); + detail::LatticeContext blocked{request, grid, config, 0.01, deadline, blocked_info, blocked_memory}; + detail::LatticeCSpace blocked_space(blocked); + EXPECT_FALSE(blocked_space.poseFree(2.0, 1.0, kPi / 6.0)); +} + +TEST(FootprintZones, FinishedPathUsesQueryLimitRatherThanRung) +{ + LatticeTestGrid map(500, 220); + GridRef grid = map.view(); grid.resolution = 0.01; + for (int y = 115; y < 130; ++y) + for (int x = 180; x < 310; ++x) map.direction[static_cast(y) * map.width + x] = 2; + PlannerConfig config = latticeConfig(); + config.half_x_m = 0.511; config.half_y_m = 0.1955; + config.max_deviation_deg = 45.0; config.zone_transition_m = 0.0; + const Path path{{1.0, 1.0, 0.0, 0.0}, {4.0, 1.0, 0.0, 0.0}}; + EXPECT_TRUE(verifyPath(path, grid, 0.01, config).valid); + config.max_deviation_deg = 10.0; + const PathCheck blocked = verifyPath(path, grid, 0.01, config); + EXPECT_FALSE(blocked.valid); + EXPECT_GT(blocked.zone_violations, 0); +} diff --git a/tools/lane_route_eval.cpp b/tools/lane_route_eval.cpp index b6557d0..1f09324 100644 --- a/tools/lane_route_eval.cpp +++ b/tools/lane_route_eval.cpp @@ -2,13 +2,16 @@ * with the Python prototype. Usage: * lane_route_eval [graph|fallback|lattice] * Each scenes.txt line: id grid_file variant live_file|- has_start_yaw sx sy syaw has_goal_yaw gx gy gyaw box_count {x0 y0 x1 y1} - * Grid files are kept in memory, so scenes that share one map also share its graphs, as on the robot. */ + * Grid files are kept in memory, so scenes that share one map also share its graphs, as on the robot. + * Set LANE_ROUTE_EVAL_DUMP_GRAPH to a directory for per-query graph, Dijkstra attempts and final-path JSON. */ #include #include #include #include #include +#include #include +#include #include #include #include @@ -32,6 +35,122 @@ using Clock = std::chrono::steady_clock; double msSince(Clock::time_point begin) { return std::chrono::duration(Clock::now() - begin).count(); } +void jsonString(std::ostream& out, const std::string& value) +{ + out << '"'; + for (unsigned char c : value) + { + if (c == '"' || c == '\\') out << '\\' << static_cast(c); + else if (c < 0x20) out << "\\u00" << "0123456789abcdef"[c >> 4] << "0123456789abcdef"[c & 15]; + else out << static_cast(c); + } + out << '"'; +} + +const char* edgeKind(EdgeKind kind) +{ + switch (kind) + { + case EdgeKind::kVoronoi: return "kVoronoi"; + case EdgeKind::kLane: return "kLane"; + case EdgeKind::kJunction: return "kJunction"; + case EdgeKind::kPreferredRidge: return "kPreferredRidge"; + case EdgeKind::kPreferredAttach: return "kPreferredAttach"; + case EdgeKind::kAttach: return "kAttach"; + case EdgeKind::kDirect: return "kDirect"; + case EdgeKind::kTemporaryLane: return "kTemporaryLane"; + } + return "unknown"; +} + +void writeFinite(std::ostream& out, double value) +{ + if (std::isfinite(value)) out << value; + else out << "null"; +} + +void writeGraphDump(const std::string& directory, std::size_t ordinal, const std::string& id, double deviation, + const RouteRequest& request, const GraphTrace& trace, const PlanResult& result) +{ + try + { + std::filesystem::create_directories(directory); + std::ostringstream name; + name << "query_" << std::setw(5) << std::setfill('0') << ordinal << ".json"; + std::ofstream out(std::filesystem::path(directory) / name.str()); + if (!out) { std::cerr << "cannot write graph dump " << name.str() << std::endl; return; } + out.precision(17); + out << "{\"scene\":"; jsonString(out, id); + out << ",\"requested_deviation_deg\":"; writeFinite(out, deviation); + out << ",\"start\":["; writeFinite(out, request.start.x); out << ','; writeFinite(out, request.start.y); out << ','; + writeFinite(out, request.start.yaw); out << "],\"goal\":["; writeFinite(out, request.goal.x); out << ','; + writeFinite(out, request.goal.y); out << ','; writeFinite(out, request.goal.yaw); + out << "],\"ok\":" << (result.ok ? "true" : "false") << ",\"reason\":"; jsonString(out, result.info.reason); + out << ",\"graph_reason\":"; jsonString(out, result.info.graph_reason); + out << ",\"runs\":["; + for (std::size_t ri = 0; ri < trace.runs.size(); ++ri) + { + const GraphTraceRun& run = trace.runs[ri]; + if (ri) out << ','; + out << "{\"source\":"; jsonString(out, run.source); + out << ",\"deviation_deg\":" << run.deviation_deg << ",\"min_turn_radius_m\":" << run.min_turn_radius_m + << ",\"max_kink_deg\":" << run.max_kink_deg << ",\"corner_radii_m\":["; + for (std::size_t i = 0; i < run.corner_radii_m.size(); ++i) { if (i) out << ','; out << run.corner_radii_m[i]; } + out << "],\"base_nodes\":" << run.base_nodes << ",\"base_edges\":" << run.base_edges + << ",\"start_node\":" << run.start_node << ",\"goal_node\":" << run.goal_node << ",\"nodes\":["; + for (std::size_t i = 0; i < run.nodes.size(); ++i) + { if (i) out << ','; out << '['; writeFinite(out, run.nodes[i].x); out << ','; writeFinite(out, run.nodes[i].y); out << ']'; } + out << "],\"edges\":["; + for (std::size_t i = 0; i < run.edges.size(); ++i) + { + if (i) out << ','; + const GraphEdge& edge = run.edges[i]; + double length = 0.0; + for (std::size_t j = 1; j < edge.points.size(); ++j) length += distanceOf(edge.points[j - 1], edge.points[j]); + out << "{\"id\":" << i << ",\"from\":" << edge.from << ",\"to\":" << edge.to << ",\"kind\":"; + jsonString(out, edgeKind(edge.kind)); + out << ",\"query_edge\":" << (i >= static_cast(run.base_edges) ? "true" : "false") + << ",\"length_m\":"; writeFinite(out, length); out << ",\"cost\":"; writeFinite(out, edge.cost); + out << ",\"kind_weight\":" << (edge.kind == EdgeKind::kVoronoi ? run.voronoi_weight : 1.0); + out << ",\"factor\":"; if (i < run.factors.size()) writeFinite(out, run.factors[i]); else out << "null"; + out << ",\"neutral_factor\":"; if (i < run.neutral_factors.size()) writeFinite(out, run.neutral_factors[i]); else out << "null"; + out << ",\"polyline\":["; + for (std::size_t j = 0; j < edge.points.size(); ++j) + { if (j) out << ','; out << '['; writeFinite(out, edge.points[j].x); out << ','; writeFinite(out, edge.points[j].y); out << ']'; } + out << "]}"; + } + out << "],\"initially_blocked_edges\":["; + for (std::size_t i = 0; i < run.initially_blocked_edges.size(); ++i) + { if (i) out << ','; out << run.initially_blocked_edges[i]; } + out << "],\"attempts\":["; + for (std::size_t i = 0; i < run.attempts.size(); ++i) + { + if (i) out << ','; + const GraphTraceAttempt& attempt = run.attempts[i]; + out << "{\"pass\":" << attempt.pass << ",\"attempt\":" << attempt.attempt << ",\"reason\":"; + jsonString(out, attempt.reason); + out << ",\"rejected_edge\":" << attempt.rejected_edge << ",\"candidate_length_m\":" << attempt.candidate_length_m + << ",\"reference_length_m\":" << attempt.reference_length_m << ",\"zone_violations\":" << attempt.zone_violations + << ",\"footprint_collisions\":" << attempt.footprint_collisions << ",\"blocked_pairs_added\":["; + for (std::size_t j = 0; j < attempt.blocked_pairs_added.size(); ++j) + { if (j) out << ','; out << '[' << attempt.blocked_pairs_added[j].first << ',' << attempt.blocked_pairs_added[j].second << ']'; } + out << ']'; + out << ",\"route\":["; + for (std::size_t j = 0; j < attempt.route.size(); ++j) { if (j) out << ','; out << attempt.route[j]; } + out << "]}"; + } + out << "]}"; + } + out << "],\"path\":["; + for (std::size_t i = 0; i < result.path.size(); ++i) + { if (i) out << ','; const PathPoint& p = result.path[i]; out << '['; writeFinite(out, p.x); out << ','; writeFinite(out, p.y); + out << ','; writeFinite(out, p.yaw); out << ','; writeFinite(out, p.curvature); out << ']'; } + out << "]}\n"; + if (!out) std::cerr << "failed to finish graph dump " << name.str() << std::endl; + } + catch (const std::exception& ex) { std::cerr << "graph dump: " << ex.what() << std::endl; } +} + std::vector readRuns(std::istream& in, const std::string& name) { std::string key; @@ -127,6 +246,7 @@ void applyOverrides(PlannerConfig* config) return; const std::map doubles{ { "lattice_closed_resolution_m", &config->lattice_closed_resolution_m }, + { "zone_transition_m", &config->zone_transition_m }, { "lattice_preferred_gap_m", &config->lattice_preferred_gap_m }, { "lattice_preferred_time_fraction", &config->lattice_preferred_time_fraction }, { "lattice_heuristic_weight", &config->lattice_heuristic_weight }, @@ -268,6 +388,9 @@ int main(int argc, char** argv) out.precision(17); std::map> maps; + const char* graph_dump_dir = std::getenv("LANE_ROUTE_EVAL_DUMP_GRAPH"); + const bool graph_dump_enabled = graph_dump_dir != nullptr && *graph_dump_dir != '\0'; + std::size_t graph_dump_ordinal = 0; std::string line; while (std::getline(scenes, line)) { @@ -343,6 +466,7 @@ int main(int argc, char** argv) for (double deviation : deviations) { config.max_deviation_deg = deviation; + GraphTrace graph_trace; const GraphProvider provider = [&](double limit) -> std::shared_ptr { if (coarse == nullptr) return {}; auto& slot = live_preferred ? row_graphs[limit] : map->graphs[std::make_pair(variant, limit)]; @@ -351,7 +475,8 @@ int main(int argc, char** argv) compileGraph(*coarse, compile_grid, live_preferred ? live_cost.data() : compile_grid.cost, limit, config, backend)); return slot; }; - const PlanResult result = planRoute(provider, request, live_grid, config, backend); + const PlanResult result = planRoute(provider, request, live_grid, config, backend, graph_dump_enabled ? &graph_trace : nullptr); + if (graph_dump_enabled) writeGraphDump(graph_dump_dir, graph_dump_ordinal++, id, deviation, request, graph_trace, result); const PlanInfo& info = result.info; out << "{\"scene\":\"" << id << "\",\"dev\":" << deviation << ",\"ok\":" << (result.ok ? 1 : 0) << ",\"reason\":\"" << info.reason << "\",\"query_ms\":" << info.query_ms << ",\"compile_ms\":" << info.compile_ms << ",\"coarse_ms\":" << coarse_ms