diff --git a/include/lane_route_core/graph_compiler.h b/include/lane_route_core/graph_compiler.h index 1114913..16d0acc 100644 --- a/include/lane_route_core/graph_compiler.h +++ b/include/lane_route_core/graph_compiler.h @@ -30,6 +30,7 @@ struct GraphEdge std::vector points; ///< [m] from -> to. EdgeKind kind; double cost; ///< Length [m] plus lane offset and low clearance penalties. + double zone_deviation_cost = 0.0; ///< [m] Added independently of costmap and edge-kind factors. }; /** @brief Directed graph for one direction limit, ready for route queries. Immutable after compileGraph. */ diff --git a/include/lane_route_core/grid_checks.h b/include/lane_route_core/grid_checks.h index 4351742..f7d69d5 100644 --- a/include/lane_route_core/grid_checks.h +++ b/include/lane_route_core/grid_checks.h @@ -32,6 +32,16 @@ double costFactor(uint8_t value); /** @brief Length [m] weighted by costFactor. Infinity when a sample is blocked or off the grid. */ double lineCost(const Point2& a, const Point2& b, const uint8_t* master, const GridRef& grid); +/** @brief Centre-path deviation sampled at half-cell spacing. Integral is in deg*m. */ +struct ZoneDeviation +{ + double deviated_length_m = 0.0; + double integral_deg_m = 0.0; +}; +double zoneDeviationDegrees(uint8_t code, double heading); +ZoneDeviation lineZoneDeviation(const Point2& a, const Point2& b, const GridRef& grid); +double pathZoneDeviationIntegral(const Path& path, const GridRef& grid); + /** @brief Dense centre check of the free-space clearance rule. Cells inside a zone are exempt. */ bool freeClearanceOk(const Path& path, const GridRef& grid, int min_clearance_mm); bool freeClearanceOk(const Path& path, const GridRef& grid, int min_clearance_mm, const std::atomic* cancel, diff --git a/include/lane_route_core/path_verifier.h b/include/lane_route_core/path_verifier.h index d1bc575..7e91f80 100644 --- a/include/lane_route_core/path_verifier.h +++ b/include/lane_route_core/path_verifier.h @@ -20,6 +20,8 @@ struct PathCheck int corners = 0; ///< Sharp corners within max_kink_deg: one turning step between two straight steps. double max_curvature = 0.0; ///< [1/m] double max_bend_deg = 0.0; ///< [deg] Largest bend over 0.1 m. + bool has_failure_location = false; ///< A sampled zone or footprint violation was located. + Point2 failure_location{}; ///< [m] Centre pose at the first located violation. }; /** @brief Check a path against the grid, sharing no geometry with the code that built it. diff --git a/include/lane_route_core/route_planner.h b/include/lane_route_core/route_planner.h index 2aa4286..9f43823 100644 --- a/include/lane_route_core/route_planner.h +++ b/include/lane_route_core/route_planner.h @@ -28,6 +28,8 @@ struct GraphTraceAttempt double reference_length_m = 0.0; int zone_violations = -1; int footprint_collisions = -1; + bool has_failure_location = false; + Point2 failure_location{}; }; struct GraphTraceRun @@ -98,8 +100,11 @@ struct PlanInfo uint64_t lattice_standability_rejected = 0; ///< Distinct cells rejected within each field cache. double graph_reference_length_m = 0.0; ///< [m] Most recent reference that caused route_too_long; 0 when absent. uint64_t lattice_states_expanded = 0; + uint64_t lattice_closed_pruned = 0; ///< Continuous states discarded because their position/heading bin was occupied. + uint64_t lattice_refinement_attempts = 0; ///< Searches retried with a finer closed-set grid. uint64_t lattice_pose_checks = 0; uint64_t lattice_field_cells = 0; + uint64_t lattice_heading_field_states = 0; ///< Settled coarse cell/heading states in the alternate guide. uint64_t lattice_tiles_built = 0; uint64_t lattice_peak_bytes = 0; uint64_t lattice_crossing_rejects = 0; ///< Rejected candidates across all rungs. diff --git a/include/lane_route_core/types.h b/include/lane_route_core/types.h index 609705d..961601c 100644 --- a/include/lane_route_core/types.h +++ b/include/lane_route_core/types.h @@ -120,11 +120,12 @@ struct PlannerConfig 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. + double zone_deviation_weight = 2.0; ///< [m/m at 45 deg] Extra cost for travelling across a zone direction; 0 disables it. 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. - double route_too_long_ratio = 1.5; ///< Refuse paths longer than ratio * shortest directed grid route + margin. - double route_too_long_margin_m = 2.0; + double route_too_long_ratio = 1.5; ///< Legacy setting retained for configuration compatibility; no longer rejects verified paths. + double route_too_long_margin_m = 2.0; ///< [m] Legacy setting retained for configuration compatibility. double suspicious_ratio = 1.3; ///< Only paths above ratio * straight distance + margin run that search. double suspicious_margin_m = 2.0; int max_route_attempts = 24; ///< Route retries per pass. Each failed corner bans one edge pair, so reaching a gate can take about 20. @@ -143,7 +144,7 @@ struct PlannerConfig bool lattice_tight_arcs = false; int lattice_heading_bins = 72; ///< Heading divisions per revolution, even. double lattice_closed_resolution_m = 0.10; ///< [m] Maximum x/y search bin size. - double lattice_heuristic_weight = 3.0; ///< Weighted A* heuristic multiplier. 3.0 solved the most regress7 runs within 3 s (kit +10 over 1.5). + double lattice_heuristic_weight = 3.0; ///< Weighted A* multiplier; coarse fields are guidance, not admissible feasibility proofs. double lattice_bucket_width_m = 0.25; ///< [m] FIFO priority bucket width; 0 uses exact heap priority. double lattice_field_clearance_weight_m = 0.25; ///< [m] Reverse-field clearance cost; 0.25 matches lattice_wall_weight_m so the heuristic and the path cost agree. double lattice_wall_weight_m = 0.25; ///< [m] Search clearance cost. diff --git a/src/graph_compiler.cpp b/src/graph_compiler.cpp index 59f8253..913657d 100644 --- a/src/graph_compiler.cpp +++ b/src/graph_compiler.cpp @@ -42,7 +42,7 @@ double polylineLength(const std::vector& points) /** Sample cells of one polyline, spaced at most half a cell. */ template -void forEachSample(const std::vector& points, const GridRef& grid, Visit visit) +void forEachSample(const std::vector& points, const GridRef& grid, bool need_heading, Visit visit) { const double half = grid.resolution * 0.5; for (std::size_t i = 0; i + 1 < points.size(); ++i) @@ -54,13 +54,14 @@ void forEachSample(const std::vector& points, const GridRef& grid, Visit continue; const int samples = std::max(1, static_cast(std::ceil(length / half))); const double weight = length / samples; + const double heading = need_heading ? std::atan2(dy, dx) : 0.0; for (int j = 0; j < samples; ++j) { const double t = (j + 0.5) / samples; const double fx = std::floor((points[i].x + dx * t - grid.origin_x) / grid.resolution); const double fy = std::floor((points[i].y + dy * t - grid.origin_y) / grid.resolution); const bool inside = fx >= 0.0 && fy >= 0.0 && fx < grid.width && fy < grid.height; - visit(inside ? static_cast(fy) * grid.width + static_cast(fx) : -1, weight); + visit(inside ? static_cast(fy) * grid.width + static_cast(fx) : -1, weight, heading); } } } @@ -93,7 +94,7 @@ private: double edgeFactor(const std::vector& points, const uint8_t* master, const GridRef& grid) { FactorSum sum; - forEachSample(points, grid, [&](int32_t cell, double weight) { sum.add(cell, weight, master); }); + forEachSample(points, grid, false, [&](int32_t cell, double weight, double) { sum.add(cell, weight, master); }); return sum.factor(); } @@ -313,9 +314,13 @@ CompiledGraph compileGraph(const CoarseGraph& coarse, const GridRef& grid, const { if (cancelled()) return {}; graph.outgoing[static_cast(graph.edges[i].from)].push_back(static_cast(i)); - forEachSample(graph.edges[i].points, grid, [&](int32_t cell, double weight) { + forEachSample(graph.edges[i].points, grid, config.zone_deviation_weight != 0.0 && grid.direction, + [&](int32_t cell, double weight, double heading) { graph.sample_cells.push_back(cell); graph.sample_weights.push_back(weight); + if (config.zone_deviation_weight != 0.0 && grid.direction && cell >= 0) + graph.edges[i].zone_deviation_cost += config.zone_deviation_weight * weight * + (zoneDeviationDegrees(grid.direction[cell], heading) / 45.0); }); graph.sample_offsets.push_back(static_cast(graph.sample_cells.size())); } diff --git a/src/grid_checks.cpp b/src/grid_checks.cpp index 26fae6c..9efb327 100644 --- a/src/grid_checks.cpp +++ b/src/grid_checks.cpp @@ -95,6 +95,8 @@ std::string PlannerConfig::validate() const 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 (!not_negative(zone_deviation_weight)) + error << "zone_deviation_weight 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) @@ -282,6 +284,40 @@ double lineCost(const Point2& a, const Point2& b, const uint8_t* master, const G return length * (sum / samples); } +double zoneDeviationDegrees(uint8_t code, double heading) +{ + return code >= 1 && code <= 8 ? std::abs(wrapAngle(heading - (code - 1) * kPi / 4.0)) * 180.0 / kPi : 0.0; +} + +ZoneDeviation lineZoneDeviation(const Point2& a, const Point2& b, const GridRef& grid) +{ + ZoneDeviation result; + if (!grid.direction) return result; + const double length = distanceOf(a, b); + if (length < 1e-12) return result; + const int samples = std::max(1, static_cast(std::ceil(length / (grid.resolution * 0.5)))); + const double ds = length / samples; + const double heading = headingOf(a, b); + for (int i = 0; i < samples; ++i) + { + const double t = (i + 0.5) / samples; + int32_t cell = 0; + if (!cellOf(grid, a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t, &cell)) continue; + const double deviation = zoneDeviationDegrees(grid.direction[cell], heading); + result.integral_deg_m += deviation * ds; + if (deviation > 3.0) result.deviated_length_m += ds; + } + return result; +} + +double pathZoneDeviationIntegral(const Path& path, const GridRef& grid) +{ + double sum = 0.0; + for (std::size_t i = 1; i < path.size(); ++i) + sum += lineZoneDeviation({path[i-1].x, path[i-1].y}, {path[i].x, path[i].y}, grid).integral_deg_m; + return sum; +} + bool freeClearanceOk(const Path& path, const GridRef& grid, int min_clearance_mm) { return freeClearanceOk(path, grid, min_clearance_mm, nullptr, nullptr); diff --git a/src/lattice_cspace.cpp b/src/lattice_cspace.cpp index e757d10..8d4a981 100644 --- a/src/lattice_cspace.cpp +++ b/src/lattice_cspace.cpp @@ -124,17 +124,10 @@ bool LatticeCSpace::zonePoseFree(double x, double y, double yaw, double sweep_ma 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); + // A pose alone cannot know whether the path will enter the same region within the allowed path distance. + // Reject only when no cell with that direction is even nearby; the whole-path verifier checks the exact + // connected region and distance. This avoids removing legal side entries from the lattice search. + const double transition = context_.allow_zone_transition ? context_.config.zone_transition_m : 0.0; 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]; @@ -144,11 +137,7 @@ bool LatticeCSpace::zonePoseFree(double x, double y, double yaw, double sweep_ma 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; + if (!zone_index_.nearbyDirection(x, y, cell.code, transition)) legal = false; }); return legal; } diff --git a/src/lattice_heuristic.cpp b/src/lattice_heuristic.cpp index 5ff289e..ed95482 100644 --- a/src/lattice_heuristic.cpp +++ b/src/lattice_heuristic.cpp @@ -31,7 +31,7 @@ bool allows(uint8_t code, double heading, double deviation) } } // namespace -double LatticeField::at(double x, double y, const LatticeContext& context) const +double LatticeField::at(double x, double y, double yaw, const LatticeContext& context) const { const GridRef& g = context.grid; const double maximum = std::numeric_limits::max() / 4.0; @@ -39,6 +39,15 @@ double LatticeField::at(double x, double y, const LatticeContext& context) const const double fx = std::floor((x - g.origin_x) / g.resolution); const double fy = std::floor((y - g.origin_y) / g.resolution); if (values.empty() || fx < 0.0 || fy < 0.0 || fx >= g.width || fy >= g.height) return fallback; + if (!heading_values.empty()) + { + const int32_t hx = static_cast(fx) / heading_factor; + const int32_t hy = static_cast(fy) / heading_factor; + const int heading = (static_cast(std::floor(wrapAngle(yaw) / (kPi / 4.0) + 0.5)) + 8) % 8; + const std::size_t key = (static_cast(hy) * heading_width + hx) * 8 + heading; + if (hx < heading_width && hy < heading_height && heading_settled[key]) + return std::max(fallback, static_cast(heading_values[key])); + } const int32_t field_width = width > 0 ? width : g.width; const std::size_t cell = (static_cast(fy) / static_cast(factor)) * static_cast(field_width) + static_cast(fx) / static_cast(factor); @@ -226,5 +235,83 @@ bool buildLatticeField(LatticeContext& context, LatticeField* field, TimePoint f return true; } +bool buildHeadingField(LatticeContext& context, LatticeCSpace& space, LatticeField* field, TimePoint deadline) +{ + const GridRef& grid = context.grid; + // Bound the heading field by the existing field cell budget. Coarse sampling can overestimate or miss a route, + // so unsettled states fall back to the original field and this guide never rejects a search state. + const int64_t max_cells = std::max(1, context.config.lattice_field_max_cells / 8); + int factor = 1; + const auto count = [&](int f) { + return ((static_cast(grid.width) + f - 1) / f) * ((static_cast(grid.height) + f - 1) / f); + }; + int high = std::max(grid.width, grid.height); + while (factor < high) + { + const int middle = factor + (high - factor) / 2; + if (count(middle) <= max_cells) high = middle; else factor = middle + 1; + } + const int32_t width = static_cast((static_cast(grid.width) + factor - 1) / factor); + const int32_t height = static_cast((static_cast(grid.height) + factor - 1) / factor); + const std::size_t cells = static_cast(width) * height; + if (cells > static_cast(std::numeric_limits::max() / 8)) return false; + field->heading_factor = factor; + field->heading_width = width; + field->heading_height = height; + field->heading_values.assign(cells * 8, std::numeric_limits::infinity()); + field->heading_settled.assign(cells * 8, 0); + const auto cellOfPose = [&](const Pose2& pose) -> int32_t { + const double x = std::floor((pose.x - grid.origin_x) / grid.resolution); + const double y = std::floor((pose.y - grid.origin_y) / grid.resolution); + if (x < 0 || y < 0 || x >= grid.width || y >= grid.height) return -1; + return static_cast(y) / factor * width + static_cast(x) / factor; + }; + const int32_t start = cellOfPose(context.request.start), goal = cellOfPose(context.request.goal); + if (start < 0 || goal < 0) return false; + const double step = grid.resolution * factor; + const auto centre = [&](int32_t cell) -> Point2 { + return {grid.origin_x + (cell % width + 0.5) * step, grid.origin_y + (cell / width + 0.5) * step}; + }; + constexpr int dx[] = {1, 1, 0, -1, -1, -1, 0, 1}; + constexpr int dy[] = {0, 1, 1, 1, 0, -1, -1, -1}; + using Storage = std::pmr::vector; + std::priority_queue> queue{std::greater(), Storage(&context.memory)}; + for (int heading = 0; heading < 8; ++heading) + { + const int32_t state = goal * 8 + heading; + field->heading_values[static_cast(state)] = 0.0f; + queue.push({0.0f, state}); + } + int start_settled = 0; + while (!queue.empty() && !context.cancelled() && Clock::now() < deadline) + { + const FieldEntry top = queue.top(); queue.pop(); + if (field->heading_settled[static_cast(top.cell)] || + top.distance != field->heading_values[static_cast(top.cell)]) continue; + field->heading_settled[static_cast(top.cell)] = 1; + ++context.info.lattice_heading_field_states; + const int32_t cell = top.cell / 8; + const int heading = top.cell % 8; + if (cell == start && ++start_settled == 8) break; + const int32_t px = cell % width - dx[heading], py = cell / width - dy[heading]; + if (px < 0 || py < 0 || px >= width || py >= height) continue; + const int32_t previous = py * width + px; + const Point2 a = centre(previous), b = centre(cell); + const double yaw = heading * kPi / 4.0; + if (!space.segmentLegal({a.x, a.y, yaw, 0.0}, {b.x, b.y, yaw, 0.0})) continue; + const float next = static_cast(top.distance + std::hypot(dx[heading], dy[heading]) * step); + for (int prior = 0; prior < 8; ++prior) + { + const std::size_t key = static_cast(previous) * 8 + prior; + if (field->heading_settled[key] || next >= field->heading_values[key]) continue; + // Rotation is a relaxation used only for guidance; a returned path still has to pass the no-mid-spin verifier. + if (prior != heading && !space.spinLegal(a.x, a.y, prior * kPi / 4.0, yaw)) continue; + field->heading_values[key] = next; + queue.push({next, static_cast(key)}); + } + } + return !context.cancelled(); +} + } // namespace detail } // namespace lane_route_core diff --git a/src/lattice_internal.h b/src/lattice_internal.h index 0b9b383..8343906 100644 --- a/src/lattice_internal.h +++ b/src/lattice_internal.h @@ -58,6 +58,7 @@ struct LatticeContext uint64_t* smooth_checks = nullptr; uint64_t smooth_limit = 0; double gap_scan_margin_m = 0.0; ///< [m] Additional gap reporting range; minimum search keeps the original scan. + bool allow_zone_transition = false; ///< Search retry may admit possible transitions; final verification remains exact. bool cancelled() const { return request.cancel && request.cancel->load(std::memory_order_relaxed); } bool expired() const { return cancelled() || Clock::now() >= deadline || (smooth_checks && *smooth_checks >= smooth_limit); } @@ -155,14 +156,20 @@ private: struct LatticeField { - explicit LatticeField(std::pmr::memory_resource* resource) : values(resource), settled(resource) {} + explicit LatticeField(std::pmr::memory_resource* resource) + : values(resource), settled(resource), heading_values(resource), heading_settled(resource) {} std::pmr::vector values; std::pmr::vector settled; + std::pmr::vector heading_values; + std::pmr::vector heading_settled; int32_t width = 0, height = 0; int factor = 1; + int32_t heading_width = 0, heading_height = 0; + int heading_factor = 1; double frontier = 0.0; bool complete = false; - double at(double x, double y, const LatticeContext& context) const; + double at(double x, double y, double yaw, const LatticeContext& context) const; + double at(double x, double y, const LatticeContext& context) const { return at(x, y, 0.0, context); } }; bool rejectLatticeCrossing(LatticeContext& context, const Path& path); @@ -172,7 +179,10 @@ bool verifyLatticeCandidate(LatticeContext& context, const Path& path, PathCheck /** @param relax_m Standability relax of this field; a negative value takes lattice_field_standability_relax_m. */ bool buildLatticeField(LatticeContext& context, LatticeField* field, TimePoint field_deadline, double extra_clearance_m = 0.0, double relax_m = -1.0); -bool searchLattice(LatticeContext& context, LatticeCSpace& space, const LatticeField& field, Path* path, PathCheck* check); +/** A coarse heading-sector guide. It only orders the search and is not a feasibility proof. */ +bool buildHeadingField(LatticeContext& context, LatticeCSpace& space, LatticeField* field, TimePoint deadline); +bool searchLattice(LatticeContext& context, LatticeCSpace& space, const LatticeField& field, Path* path, PathCheck* check, + double resolution_override_m = 0.0, bool* pruned = nullptr); void smoothLatticePath(LatticeContext& context, LatticeCSpace& space, Path* path, PathCheck* check); bool planLatticeTier(const LatticeTierInput& input, GraphTierOutput output); diff --git a/src/lattice_search.cpp b/src/lattice_search.cpp index e20bee9..9b65082 100644 --- a/src/lattice_search.cpp +++ b/src/lattice_search.cpp @@ -318,8 +318,10 @@ double latticeMotionCost(double length, double clearance, int steer, int last_st (steer != 0 ? config.lattice_steer_cost_m * multiple : 0.0); } -bool searchLattice(LatticeContext& context, LatticeCSpace& space, const LatticeField& field, Path* output, PathCheck* check) +bool searchLattice(LatticeContext& context, LatticeCSpace& space, const LatticeField& field, Path* output, PathCheck* check, + double resolution_override_m, bool* pruned) { + if (pruned) *pruned = false; const PlannerConfig& c = context.config; const GridRef& grid = context.grid; const double angle = 2.0 * kPi / c.lattice_heading_bins; @@ -330,8 +332,8 @@ bool searchLattice(LatticeContext& context, LatticeCSpace& space, const LatticeF const double tight_basic = c.min_turn_radius_m * angle; const bool tight_arcs = c.lattice_tight_arcs && c.min_turn_radius_m < regular_radius - 1e-9; const std::size_t grid_cells = static_cast(grid.width) * static_cast(grid.height); - const double bin_resolution = grid_cells > 2000000u ? c.lattice_closed_resolution_m : - std::min(c.lattice_closed_resolution_m, grid.resolution); + const double bin_resolution = resolution_override_m > 0.0 ? resolution_override_m : + (grid_cells > 2000000u ? c.lattice_closed_resolution_m : std::min(c.lattice_closed_resolution_m, grid.resolution)); if (!std::isfinite(bin_resolution) || bin_resolution <= 0.0 || grid.width * grid.resolution / bin_resolution > std::numeric_limits::max() || grid.height * grid.resolution / bin_resolution > std::numeric_limits::max()) @@ -357,11 +359,16 @@ bool searchLattice(LatticeContext& context, LatticeCSpace& space, const LatticeF // parent's bin. Comparing it with the parent would always drop it, and a lane that only allows basic steps could never be left // (sehc pair_11 at 0 degrees: exhausted after 83 states with 72 headings, solved with 8 to 48). The parent is already expanded, so // the child takes its place in the bin. - if (previous != best.end() && static_cast(previous->second) != node.parent && nodes[previous->second].g <= node.g) return; + if (previous != best.end() && static_cast(previous->second) != node.parent && nodes[previous->second].g <= node.g) + { + ++context.info.lattice_closed_pruned; + if (pruned) *pruned = true; + return; + } const std::size_t id = nodes.size(); nodes.push_back(node); best[key] = id; - const double f = node.g + c.lattice_heuristic_weight * field.at(node.pose.x, node.pose.y, context); + const double f = node.g + c.lattice_heuristic_weight * field.at(node.pose.x, node.pose.y, node.pose.yaw, context); open.push({ latticeBucketPriority(f, c.lattice_bucket_width_m), serial++, id }); }; const Pose2& start = context.request.start; @@ -445,9 +452,16 @@ bool searchLattice(LatticeContext& context, LatticeCSpace& space, const LatticeF std::sort(candidates.begin(), candidates.end(), [](const AnalyticCandidate& a, const AnalyticCandidate& b) { return a.word.length != b.word.length ? a.word.length < b.word.length : a.serial < b.serial; }); + // A first legal analytic shortcut can otherwise bypass the deviation cost of all lattice primitives. + // Compare the alternatives from this state using the same distance and zone term; their geometric + // lengths are sorted, so a longer connector cannot beat a cheaper complete connector. + double best_connector_cost = std::numeric_limits::infinity(); + Path best_connector; + PathCheck best_connector_check; for (const AnalyticCandidate& option : candidates) { - if (context.expired()) return false; + if (context.expired()) break; + if (c.zone_deviation_weight != 0.0 && option.word.length >= best_connector_cost) break; Path connector(1, current.pose); bool legal = true; for (const Motion& motion : option.word.motion) @@ -458,14 +472,19 @@ bool searchLattice(LatticeContext& context, LatticeCSpace& space, const LatticeF std::abs(wrapAngle(connector.back().yaw-option.arrival_yaw)) > 1e-6) continue; if (goal.has_yaw && std::abs(wrapAngle(connector.back().yaw-goal.yaw)) > 1e-12 && !appendSpin(context, space, goal.yaw, &connector)) continue; + double connector_cost = option.word.length; + if (c.zone_deviation_weight != 0.0) + connector_cost += c.zone_deviation_weight * pathZoneDeviationIntegral(connector, grid) / 45.0; + if (connector_cost >= best_connector_cost) continue; // Prefix motions and the start spin were checked when their states were offered. std::pmr::vector chain(&context.memory); for (int64_t id = static_cast(entry.node); id >= 0; id = nodes[static_cast(id)].parent) { - if (context.expired()) return false; + if (context.expired()) break; chain.push_back(static_cast(id)); } + if (context.expired()) break; std::reverse(chain.begin(), chain.end()); Path candidate; const Node& root = nodes[chain.front()]; @@ -481,12 +500,26 @@ bool searchLattice(LatticeContext& context, LatticeCSpace& space, const LatticeF if (!legal || context.expired()) continue; candidate.insert(candidate.end(), connector.begin() + 1, connector.end()); if (candidate.size() == 1) candidate.push_back(candidate.front()); - if (verifyLatticeCandidate(context, candidate, check)) + PathCheck candidate_check; + if (verifyLatticeCandidate(context, candidate, c.zone_deviation_weight == 0.0 ? check : &candidate_check)) { - *output = std::move(candidate); - return true; + if (c.zone_deviation_weight == 0.0) + { + *output = std::move(candidate); + return true; + } + best_connector_cost = connector_cost; + best_connector = std::move(candidate); + best_connector_check = candidate_check; } } + if (!best_connector.empty()) + { + *output = std::move(best_connector); + *check = best_connector_check; + return true; + } + if (context.expired()) return false; } const int multiples[] = { c.lattice_primitive_multiple_1, c.lattice_primitive_multiple_2, c.lattice_primitive_multiple_3 }; for (int multi : multiples) @@ -523,12 +556,15 @@ bool searchLattice(LatticeContext& context, LatticeCSpace& space, const LatticeF const int32_t y = static_cast(std::floor((next.y-grid.origin_y)/grid.resolution)); if (x < 0 || y < 0 || x >= grid.width || y >= grid.height) continue; const double clear = std::max(0.05, grid.clearance_mm[static_cast(y)*grid.width+x]/1000.0); - const double cost = latticeMotionCost(length, clear, steer, current.last_steer, multi, c) + + double cost = latticeMotionCost(length, clear, steer, current.last_steer, multi, c) + (tight ? c.lattice_tight_turn_cost_m * multi : 0.0); + if (c.zone_deviation_weight != 0.0) + cost += c.zone_deviation_weight * pathZoneDeviationIntegral(piece, grid) / 45.0; offer({ next, current.g+cost, static_cast(entry.node), curvature, length, heading, last }); } } - context.info.lattice_reason = "lattice_exhausted"; + // Heading and position bins, primitive choices and the continuous footprint make this a discrete search result. + context.info.lattice_reason = "lattice_approx_exhausted"; return false; } diff --git a/src/lattice_smoother.cpp b/src/lattice_smoother.cpp index 37aa274..d8a24be 100644 --- a/src/lattice_smoother.cpp +++ b/src/lattice_smoother.cpp @@ -342,6 +342,8 @@ private: bool accept(const Path& candidate, bool improve_smoothed = false) { if (context_.expired() || (improve_smoothed && context_.info.lattice_smoothed != 0 && !better(score(candidate), best_))) return false; + if (context_.config.zone_deviation_weight != 0.0 && + pathZoneDeviationIntegral(candidate, context_.grid) > pathZoneDeviationIntegral(*output_, context_.grid) + 1e-8) return false; Path ready(candidate); // Account for the verifier's dense pose samples before starting it; never replace the verified witness on exhaustion. uint64_t estimate = 1; diff --git a/src/lattice_tier.cpp b/src/lattice_tier.cpp index 17392b5..a5751f3 100644 --- a/src/lattice_tier.cpp +++ b/src/lattice_tier.cpp @@ -56,6 +56,26 @@ bool planLatticeTier(const LatticeTierInput& input, GraphTierOutput output) LatticeField field(&memory); LatticeField alternate(&memory); const LatticeField* used = &field; + const auto buildHeadingGuide = [&](LatticeField& target, TimePoint limit) { + const TimePoint began_heading = Clock::now(); + if (began_heading >= limit || context.cancelled()) return; + const TimePoint heading_deadline = began_heading + std::chrono::duration_cast( + (limit - began_heading) * std::min(0.25, input.config.lattice_field_time_fraction)); + StageTimer timer(output.info.lattice_field_ms); + const bool saved_transition = context.allow_zone_transition; + // A strict footprint-zone guide avoids following a wrong-way zone edge indefinitely. It can be + // conservative at a legal entry, so it only orders states; the actual retry keeps transition allowance. + context.allow_zone_transition = false; + try { buildHeadingField(context, space, &target, heading_deadline); } + catch (const std::bad_alloc&) + { + std::pmr::vector values(&memory); + std::pmr::vector settled(&memory); + values.swap(target.heading_values); + settled.swap(target.heading_settled); + } + context.allow_zone_transition = saved_transition; + }; const TimePoint field_deadline = began + std::chrono::duration_cast(slice * input.config.lattice_field_time_fraction); // The second field runs only when it differs from the first one. const double alternate_relax = input.config.lattice_alt_field_relax_m; @@ -86,15 +106,31 @@ bool planLatticeTier(const LatticeTierInput& input, GraphTierOutput output) { output.info.lattice_field_pass = "primary"; context.deadline = switch_at; + bool pruned = false; { StageTimer timer(output.info.lattice_search_ms, &output.info.lattice_verify_ms); - ok = searchLattice(context, space, field, &output.path, &output.check); + ok = searchLattice(context, space, field, &output.path, &output.check, 0.0, &pruned); } context.deadline = input.deadline; - // Only an interrupted search can gain from another heuristic: the field orders the states but does not change which - // are legal, so an exhausted search already proved there is no path. - if (!ok && use_alternate && !context.cancelled() && Clock::now() >= switch_at && Clock::now() < input.deadline && - output.info.lattice_reason != "lattice_exhausted" && output.info.lattice_reason != "lattice_resource_limit") + if (!ok && output.info.lattice_reason == "lattice_approx_exhausted" && !context.cancelled() && + Clock::now() < input.deadline) + { + // Distinct continuous poses share a closed bin, and the fast pass uses a stricter transition filter. + // Retry with the whole-path transition allowance and finer bins when states were merged. + const std::size_t cells = static_cast(input.grid.width) * input.grid.height; + const double first_resolution = cells > 2000000u ? input.config.lattice_closed_resolution_m : + std::min(input.config.lattice_closed_resolution_m, input.grid.resolution); + ++output.info.lattice_refinement_attempts; + context.allow_zone_transition = true; + // The heading guide is a weighted ordering aid; unsettled sectors fall back to the 2D field. + buildHeadingGuide(field, input.deadline); + StageTimer timer(output.info.lattice_search_ms, &output.info.lattice_verify_ms); + ok = searchLattice(context, space, field, &output.path, &output.check, first_resolution * (pruned ? 0.5 : 1.0)); + } + // A different heuristic changes ordering, not the legal transitions. + if (!ok && use_alternate && !context.cancelled() && Clock::now() < input.deadline && + (Clock::now() >= switch_at || output.info.lattice_reason == "lattice_approx_exhausted") && + output.info.lattice_reason != "lattice_resource_limit") { bool alternate_ok = false; { @@ -108,8 +144,23 @@ bool planLatticeTier(const LatticeTierInput& input, GraphTierOutput output) { output.info.lattice_field_pass = "alternate"; used = &alternate; - StageTimer timer(output.info.lattice_search_ms, &output.info.lattice_verify_ms); - ok = searchLattice(context, space, alternate, &output.path, &output.check); + context.allow_zone_transition = true; + buildHeadingGuide(alternate, input.deadline); + bool alternate_pruned = false; + { + StageTimer timer(output.info.lattice_search_ms, &output.info.lattice_verify_ms); + ok = searchLattice(context, space, alternate, &output.path, &output.check, 0.0, &alternate_pruned); + } + if (!ok && alternate_pruned && output.info.lattice_reason == "lattice_approx_exhausted" && + !context.cancelled() && Clock::now() < input.deadline) + { + const std::size_t cells = static_cast(input.grid.width) * input.grid.height; + const double first_resolution = cells > 2000000u ? input.config.lattice_closed_resolution_m : + std::min(input.config.lattice_closed_resolution_m, input.grid.resolution); + ++output.info.lattice_refinement_attempts; + StageTimer timer(output.info.lattice_search_ms, &output.info.lattice_verify_ms); + ok = searchLattice(context, space, alternate, &output.path, &output.check, first_resolution * 0.5); + } } } search_timed_out = !ok && Clock::now() >= input.deadline; @@ -181,6 +232,10 @@ bool planLatticeTier(const LatticeTierInput& input, GraphTierOutput output) std::pmr::vector settled(&memory); values.swap(done->values); settled.swap(done->settled); + std::pmr::vector heading_values(&memory); + std::pmr::vector heading_settled(&memory); + heading_values.swap(done->heading_values); + heading_settled.swap(done->heading_settled); } const TimePoint smooth_began = Clock::now(); context.deadline = input.smooth_deadline; @@ -220,7 +275,7 @@ bool planLatticeTier(const LatticeTierInput& input, GraphTierOutput output) if (cancelled) output.info.lattice_reason = "cancelled"; else if (timed_out) output.info.lattice_reason = "lattice_timeout"; else if (ok) output.info.lattice_reason = "verified"; - else if (output.info.lattice_reason.empty()) output.info.lattice_reason = "lattice_exhausted"; + else if (output.info.lattice_reason.empty()) output.info.lattice_reason = "lattice_approx_exhausted"; if (!ok || cancelled || timed_out) { output.path.clear(); diff --git a/src/path_verifier.cpp b/src/path_verifier.cpp index 95272be..f701fe0 100644 --- a/src/path_verifier.cpp +++ b/src/path_verifier.cpp @@ -114,7 +114,7 @@ bool touchesZoneRegion(const PathPoint& pose, uint32_t region, const GridRef& gr 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) + const std::chrono::steady_clock::time_point* deadline, PathCheck* check) { if (grid.direction == nullptr || samples.empty()) return 0; const auto stopped = [&]() { @@ -161,7 +161,18 @@ int footprintZoneViolations(const Path& samples, const GridRef& grid, double dev 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()); + const auto locate = [&](const Pending& entry) { + if (!check->has_failure_location) + { + check->has_failure_location = true; + check->failure_location = { samples[entry.sample].x, samples[entry.sample].y }; + } + }; + if (config.zone_transition_m <= 0.0) + { + locate(pending.front()); + 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. @@ -184,7 +195,11 @@ int footprintZoneViolations(const Path& samples, const GridRef& grid, double dev 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; + if (found == distances.end() || *found > here + config.zone_transition_m) + { + locate(entry); + ++violations; + } } return violations; } @@ -373,7 +388,13 @@ PathCheck verifyPath(const Path& path, const GridRef& grid, double deviation_deg const double arc = std::abs(turn) < 1e-9 ? distance : distance * std::abs(turn) / (2.0 * std::abs(std::sin(turn / 2.0))); check.max_curvature = std::max(check.max_curvature, std::abs(turn) / arc); } - check.zone_violations += zoneViolations(a, b, grid, deviation_deg); + const int centre_violations = zoneViolations(a, b, grid, deviation_deg); + check.zone_violations += centre_violations; + if (centre_violations && !check.has_failure_location) + { + check.has_failure_location = true; + check.failure_location = { (a.x + b.x) * 0.5, (a.y + b.y) * 0.5 }; + } 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) { @@ -397,12 +418,19 @@ PathCheck verifyPath(const Path& path, const GridRef& grid, double deviation_deg const double t = static_cast(j) / samples; 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; + if (!check.has_failure_location) + { + check.has_failure_location = true; + check.failure_location = {x, y}; + } + } } } 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); + zone_index, cancel, deadline, &check); if (body_zone_violations < 0) return check; check.zone_violations += body_zone_violations; check.self_crossings = selfCrossings(path, cancel, deadline); diff --git a/src/route_graph_path.cpp b/src/route_graph_path.cpp index ec9d7de..a1fb7a9 100644 --- a/src/route_graph_path.cpp +++ b/src/route_graph_path.cpp @@ -1,5 +1,4 @@ #include "route_planner_internal.h" -#include "standability.h" #include #include @@ -107,9 +106,15 @@ bool simplifyRoute(const QueryGraph& query, const std::vector& route, c if (vertices.size() < 2) return false; + const auto cost = [&](const Point2& a, const Point2& b) { + double value = lineCost(a, b, master, context.grid); + if (context.config.zone_deviation_weight != 0.0) + value += context.config.zone_deviation_weight * lineZoneDeviation(a, b, context.grid).integral_deg_m / 45.0; + return value; + }; std::vector prefix(vertices.size(), 0.0); for (std::size_t i = 0; i + 1 < vertices.size(); ++i) - prefix[i + 1] = prefix[i] + lineCost(vertices[i], vertices[i + 1], master, context.grid); + prefix[i + 1] = prefix[i] + cost(vertices[i], vertices[i + 1]); int thresholds[2]; shortcutTiers(context, shortcut_minimum_m, thresholds); @@ -134,7 +139,7 @@ bool simplifyRoute(const QueryGraph& query, const std::vector& route, c for (std::size_t j = boundary; j > i; --j) { if (lineOk(context.grid, vertices[i], vertices[j], context.deviation_deg, threshold) && - lineCost(vertices[i], vertices[j], master, context.grid) <= prefix[j] - prefix[i] + 1e-8) + cost(vertices[i], vertices[j]) <= prefix[j] - prefix[i] + 1e-8) { found = j; break; @@ -605,18 +610,6 @@ bool candidateLegal(const Path& path, const QueryContext& context, const Pose2& !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; - const Point2 start_point{ start.x, start.y }; - const Point2 goal_point{ goal.x, goal.y }; - const double length = pathLength(path); - if (length > config.suspicious_ratio * distanceOf(start_point, goal_point) + config.suspicious_margin_m) - { - const double bound = (length - config.route_too_long_margin_m) / config.route_too_long_ratio; - double reference = 0.0; - if (cachedStandableReference(grid, start_point, goal_point, context.deviation_deg, bound, &reference, *context.standability, - *context.reference, context.cancel, &context.deadline) && - length > config.route_too_long_ratio * reference + config.route_too_long_margin_m) - return false; - } return true; } @@ -691,7 +684,12 @@ void improveSwings(const std::vector& route, const QueryGraph& query, Q search.line_ok = [context](const Point2& a, const Point2& b, int minimum_mm) { return lineOk(context->grid, a, b, context->deviation_deg, minimum_mm); }; - search.line_cost = [context, master](const Point2& a, const Point2& b) { return lineCost(a, b, master, context->grid); }; + search.line_cost = [context, master](const Point2& a, const Point2& b) { + double cost = lineCost(a, b, master, context->grid); + if (context->config.zone_deviation_weight != 0.0) + cost += context->config.zone_deviation_weight * lineZoneDeviation(a, b, context->grid).integral_deg_m / 45.0; + return cost; + }; shortcutTiers(*context, shortcut_minimum_m, search.tiers_mm); search.deadline = search_deadline; search.cancel = context->cancel; @@ -706,7 +704,9 @@ void improveSwings(const std::vector& route, const QueryGraph& query, Q context->deadline = search_deadline; Candidate trial = buildSwingChain(chosen, context, start, goal, protected_points, shortcut_minimum_m); - const bool usable = trial.ok && !context->expired() && candidateLegal(trial.path, *context, start, goal); + const bool usable = trial.ok && !context->expired() && candidateLegal(trial.path, *context, start, goal) && + (context->config.zone_deviation_weight == 0.0 || + pathZoneDeviationIntegral(trial.path, context->grid) <= pathZoneDeviationIntegral(result->path, context->grid) + 1e-8); context->deadline = deadline; if (!usable || !preferLessTurning(trial.path, result->path)) return; diff --git a/src/route_graph_search.cpp b/src/route_graph_search.cpp index 7334371..9f3614d 100644 --- a/src/route_graph_search.cpp +++ b/src/route_graph_search.cpp @@ -270,7 +270,8 @@ bool searchRoute(const QueryGraph& query, int32_t start, int32_t goal, const std if (top.previous >= 0 && turnProvablyImpossible(query.edge(top.previous), edge, max_straight_m, min_radius_m)) return; const double weight = edge.kind == EdgeKind::kVoronoi ? kVoronoiWeight : 1.0; - const double traversal = edge.cost * weight * factors[static_cast(index)]; + double traversal = edge.cost * weight * factors[static_cast(index)]; + 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; diff --git a/src/route_graph_tier.cpp b/src/route_graph_tier.cpp index 7d859db..bdfa850 100644 --- a/src/route_graph_tier.cpp +++ b/src/route_graph_tier.cpp @@ -1,5 +1,4 @@ #include "route_planner_internal.h" -#include "standability.h" #include #include @@ -34,6 +33,15 @@ bool hasSoftCost(const uint8_t* master, std::size_t count) return false; } +double segmentDistanceSquared(const Point2& p, const Point2& a, const Point2& b) +{ + const double dx = b.x - a.x, dy = b.y - a.y; + const double squared = dx * dx + dy * dy; + const double t = squared > 0.0 ? std::clamp(((p.x - a.x) * dx + (p.y - a.y) * dy) / squared, 0.0, 1.0) : 0.0; + const double x = a.x + t * dx - p.x, y = a.y + t * dy - p.y; + return x * x + y * y; +} + /** 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, @@ -44,18 +52,13 @@ bool planCore(const CompiledGraph& graph, const Pose2& start, const Pose2& goal, clearanceThresholdMm(config.collision_check_distance_m), {} }; context.info = info; context.cancel = cancel; - Standability standability(verify_grid, config, std::pmr::get_default_resource(), &info->graph_standability_tests, - &info->graph_standability_rejected, cancel, &deadline); - context.standability = &standability; - ReferenceMemo reference_memo; - context.reference = &reference_memo; const Point2 start_point{ start.x, start.y }; const Point2 goal_point{ goal.x, goal.y }; const double dev = graph.deviation_deg; const std::size_t cell_count = static_cast(grid.width) * static_cast(grid.height); const double max_straight_m = std::hypot(static_cast(grid.height), static_cast(grid.width)) * grid.resolution; - QueryGraph query(graph); + 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); @@ -118,6 +121,7 @@ bool planCore(const CompiledGraph& graph, const Pose2& start, const Pose2& goal, std::string reason; std::vector route; + CandidateHistory candidates_seen; for (int pass = 0; pass < 2; ++pass) { const bool neutral_pass = pass == 1; @@ -218,15 +222,30 @@ bool planCore(const CompiledGraph& graph, const Pose2& start, const Pose2& goal, std::string why = candidate.why.reason; bool has_corner = candidate.why.has_corner; const Point2 corner = candidate.why.corner; - if (candidate.ok) + bool has_failure_location = false; + Point2 failure_location{}; + const bool duplicate = candidate.ok && candidates_seen.seenOrRemember(candidate.path); + if (duplicate) + { + const auto previous = candidates_seen.failure(candidate.path); + why = previous.reason.empty() ? "independent_verification_failed" : previous.reason; + has_failure_location = previous.located; + failure_location = previous.location; + has_corner = false; + } + if (candidate.ok && !duplicate) { 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, &deadline); + has_failure_location = path_check.has_failure_location; + failure_location = path_check.failure_location; if (trace_attempt != nullptr) { trace_attempt->zone_violations = path_check.zone_violations; trace_attempt->footprint_collisions = path_check.footprint_collisions; + trace_attempt->has_failure_location = has_failure_location; + trace_attempt->failure_location = failure_location; } bool ends_ok = endpointOk(candidate.path, start, goal); bool clear_ok = freeClearanceOk(candidate.path, verify_grid, context.min_mm); @@ -240,7 +259,6 @@ bool planCore(const CompiledGraph& graph, const Pose2& start, const Pose2& goal, } bool gap_checked = false; - bool reference_checked = false; double raise_used = 0.0; GapCheck gap; if (path_check.valid && ends_ok && clear_ok) @@ -261,7 +279,7 @@ bool planCore(const CompiledGraph& graph, const Pose2& start, const Pose2& goal, timer = Clock::now(); Candidate alternative = constructCandidate(route, query, &context, master, start, goal, config.clearance_min_m + extra); info->build_ms += msSince(timer); - if (!alternative.ok) + if (!alternative.ok || candidates_seen.seenOrRemember(alternative.path)) continue; timer = Clock::now(); const PathCheck alternative_check = verifyPath(alternative.path, verify_grid, dev, config, context.cancel, &deadline); @@ -281,16 +299,6 @@ bool planCore(const CompiledGraph& graph, const Pose2& start, const Pose2& goal, continue; } const double length = pathLength(alternative.path); - if (length > config.suspicious_ratio * distanceOf(start_point, goal_point) + config.suspicious_margin_m) - { - const double bound = (length - config.route_too_long_margin_m) / config.route_too_long_ratio; - double reference = 0.0; - if (cachedStandableReference(verify_grid, start_point, goal_point, dev, bound, &reference, standability, reference_memo, - context.cancel, &deadline) && - length > config.route_too_long_ratio * reference + config.route_too_long_margin_m) - continue; - reference_checked = true; - } candidate = std::move(alternative); if (trace_attempt != nullptr) trace_attempt->candidate_length_m = length; path_check = alternative_check; @@ -314,27 +322,8 @@ bool planCore(const CompiledGraph& graph, const Pose2& start, const Pose2& goal, } const bool passed = path_check.valid && ends_ok && clear_ok && gap_checked && gap.valid; - if (passed && !reference_checked) - { - const double length = pathLength(candidate.path); - if (length > config.suspicious_ratio * distanceOf(start_point, goal_point) + config.suspicious_margin_m) - { - timer = Clock::now(); - const double bound = (length - config.route_too_long_margin_m) / config.route_too_long_ratio; - 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; - } - } - } + // The 2D reference does not prove a forward, footprint-zone-legal shortcut exists. + // A ratio against it therefore cannot invalidate a fully verified candidate. if (passed) { *path = std::move(candidate.path); @@ -350,6 +339,7 @@ bool planCore(const CompiledGraph& graph, const Pose2& start, const Pose2& goal, } why = gap_checked && !gap.valid ? "footprint_gap_below_minimum" : path_check.valid && ends_ok && !clear_ok ? "free_clearance_below_minimum" : "independent_verification_failed"; + candidates_seen.setFailure(candidate.path, {why, has_failure_location, failure_location}); has_corner = false; } @@ -362,10 +352,24 @@ bool planCore(const CompiledGraph& graph, const Pose2& start, const Pose2& goal, std::vector> pairs; if (!has_corner) { - // Not proof that either edge is unusable. Try a different pair. + // A shortcut may span several edges. Change the transition nearest the failure without + // declaring either entire edge illegal for other routes. if (route.size() > 1) { - const std::size_t index = std::min(static_cast(attempt), route.size() - 2); + std::size_t index = std::min(static_cast(attempt), route.size() - 2); + if (has_failure_location) + { + double nearest = kInfinity; + for (std::size_t j = 0; j < route.size(); ++j) + { + const auto& points = query.edge(route[j]).points; + for (std::size_t k = 1; k < points.size(); ++k) + { + const double d = segmentDistanceSquared(failure_location, points[k-1], points[k]); + if (d < nearest) { nearest = d; index = std::min(j, route.size() - 2); } + } + } + } pairs.emplace_back(route[index], route[index + 1]); } } @@ -388,6 +392,15 @@ bool planCore(const CompiledGraph& graph, const Pose2& start, const Pose2& goal, } if (pairs.empty()) { + if (!has_corner && route.size() == 1) + { + blocked[static_cast(route.front())] = 1; + if (trace_attempt != nullptr) trace_attempt->rejected_edge = route.front(); + ++info->retries; + reason = why; + trace_reason(reason); + continue; + } reason = why; trace_reason(reason); break; diff --git a/src/route_planner.cpp b/src/route_planner.cpp index 6c480e7..6c6c29c 100644 --- a/src/route_planner.cpp +++ b/src/route_planner.cpp @@ -136,7 +136,11 @@ PlanResult planRoute(const GraphProvider& graphs, const RouteRequest& request, c regular.max_kink_deg = 0.0; // The second pass adds the tight radii and, at its bottom, sharp corners up to max_kink_deg. const bool tight_corners = config.min_turn_radius_m < regular.min_turn_radius_m - 1e-9 || config.max_kink_deg > 0.0; - const PlannerConfig& lattice_config = config.lattice_tight_arcs ? config : regular; + PlannerConfig lattice_config = config.lattice_tight_arcs ? config : regular; + // The lattice is the fallback that must find a legal path when the graph cannot; it plans without the zone + // deviation cost. With the cost (weight 2) its closed-bin pruning followed the cost order into dead ends: + // regress7 kit sim_005_zones 81/100 against 88/100 without it (11/11). The graph tier keeps the preference. + lattice_config.zone_deviation_weight = 0.0; const double chord = std::hypot(request.goal.x - request.start.x, request.goal.y - request.start.y); // R2 smoothing must share this fallback deadline instead of starting a new budget. diff --git a/src/route_planner_internal.h b/src/route_planner_internal.h index 8adae2e..1f53768 100644 --- a/src/route_planner_internal.h +++ b/src/route_planner_internal.h @@ -31,6 +31,46 @@ constexpr double kVoronoiWeight = 1.6; // Free space costs more than an expli constexpr double kSharpness[5] = { 1.0, 2.0, 4.0, 8.0, 16.0 }; constexpr double kSpinStepRad = 0.04; +/** Avoid spending the verification budget twice on the same constructed trajectory. */ +class CandidateHistory +{ +public: + struct Failure { std::string reason; bool located = false; Point2 location{}; }; + bool seenOrRemember(const Path& path) + { + Key key; + return makeKey(path, &key) && !seen_.emplace(std::move(key), Failure{}).second; + } + void setFailure(const Path& path, const Failure& failure) + { + Key key; + if (!makeKey(path, &key)) return; + const auto found = seen_.find(key); + if (found != seen_.end()) found->second = failure; + } + Failure failure(const Path& path) const + { + Key key; + if (!makeKey(path, &key)) return {}; + const auto found = seen_.find(key); + return found == seen_.end() ? Failure{} : found->second; + } +private: + using Key = std::vector>; + bool makeKey(const Path& path, Key* key) const + { + key->reserve(path.size()); + for (const auto& point : path) + { + if (!std::isfinite(point.x) || !std::isfinite(point.y) || !std::isfinite(point.yaw) || !std::isfinite(point.curvature)) + return false; + key->push_back({point.x, point.y, point.yaw, point.curvature}); + } + return true; + } + std::map seen_; +}; + constexpr int32_t kStartLinks = 600; // Candidates tried around start and goal. constexpr double kStartRadiusM = 15.0; constexpr int kAttachLimit = 120; @@ -46,9 +86,9 @@ inline double msSince(TimePoint begin) { return std::chrono::duration(base.nodes.size())), base_edges_(static_cast(base.edges.size())), - extra_outgoing_(base.nodes.size()) + extra_outgoing_(base.nodes.size()), grid_(grid), zone_weight_(zone_weight) { } @@ -76,7 +116,11 @@ public: void addEdge(int32_t from, int32_t to, std::vector points, EdgeKind kind, double cost) { extra_outgoing_[static_cast(from)].push_back(edgeCount()); - extra_edges_.push_back({ from, to, std::move(points), kind, cost }); + double deviation_cost = 0.0; + if (zone_weight_ != 0.0) + 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 }); } template @@ -95,12 +139,11 @@ private: std::vector extra_nodes_; std::vector extra_edges_; std::vector> extra_outgoing_; + const GridRef& grid_; + double zone_weight_; }; /** Everything one core pass needs. The corner cache lives across retries and the neutral pass. */ -class Standability; -struct ReferenceMemo; - struct QueryContext { const GridRef& grid; @@ -119,8 +162,6 @@ struct QueryContext std::map, std::vector> corner_options; PlanInfo* info = nullptr; const std::atomic* cancel = nullptr; - Standability* standability = nullptr; - ReferenceMemo* reference = nullptr; // Shared route_too_long reference of this pass; set with standability. bool expired() const { return (cancel && cancel->load(std::memory_order_relaxed)) || Clock::now() >= deadline; } bool lineLegal(const Point2& a, const Point2& b) const { return lineOk(grid, a, b, deviation_deg, hard_mm); } diff --git a/test/lane_route_core_test.cpp b/test/lane_route_core_test.cpp index 6fd0f31..26d3f5c 100644 --- a/test/lane_route_core_test.cpp +++ b/test/lane_route_core_test.cpp @@ -599,6 +599,28 @@ TEST_F(PlanRouteTest, WithTheFlowUsesTheStrictRung) EXPECT_EQ(result.info.rung_reasons.size(), 1u); } +TEST_F(PlanRouteTest, VerifiedPathSurvivesRelaxedReferenceLengthLimit) +{ + // Even an unrealistically short reference is not proof that a verified trajectory is unusable. + config_.suspicious_ratio = 0.1; + config_.suspicious_margin_m = 0.0; + config_.route_too_long_ratio = 0.1; + config_.route_too_long_margin_m = 0.0; + map_.finish(config_); + const RouteRequest request{ pose(1.0, 1.5, 0.0), pose(14.0, 1.5, 0.0), {} }; + expectLegal(plan(request), request, config_); +} + +TEST(GraphRetry, RemembersExactConstructedCandidates) +{ + detail::CandidateHistory history; + Path path{{1.0, 2.0, 0.0, 0.0}, {2.0, 2.0, 0.0, 0.0}}; + EXPECT_FALSE(history.seenOrRemember(path)); + EXPECT_TRUE(history.seenOrRemember(path)); + path.back().yaw = 0.1; + EXPECT_FALSE(history.seenOrRemember(path)); +} + TEST_F(PlanRouteTest, AgainstTheFlowFails) { map_.setDirection(100, 220, 1); @@ -1225,6 +1247,36 @@ TEST(Lattice, RejectsBlockedStartSpin) EXPECT_FALSE(space.spinLegal(request.start.x, request.start.y, 0.0, kPi/4.0)); } +TEST(Lattice, FiniteBinnedSearchDoesNotClaimContinuousExhaustion) +{ + LatticeTestGrid map(40, 40); + std::fill(map.cost.begin(), map.cost.end(), kLethalCost); + for (int y : {10, 30}) + for (int x : {10, 30}) + for (int dy = -5; dy <= 5; ++dy) + for (int dx = -5; dx <= 5; ++dx) + map.cost[static_cast(y + dy) * map.width + x + dx] = kFreeSpace; + PlannerConfig config = latticeConfig(); + config.half_x_m = 0.1; + config.half_y_m = 0.1; + const RouteRequest request = latticeRequest(pose(0.525, 0.525, 0.0), pose(1.525, 1.525, 0.0)); + const GridRef grid = map.view(); + PlanInfo info; + detail::LatticeMemory memory(32 * 1024 * 1024); + detail::LatticeContext context{request, grid, config, 90.0, detail::Clock::now() + std::chrono::seconds(5), info, memory}; + detail::LatticeCSpace space(context); + detail::LatticeField field(&memory); + Path path; + PathCheck check; + bool pruned = false; + EXPECT_FALSE(detail::searchLattice(context, space, field, &path, &check, 0.0, &pruned)); + EXPECT_EQ(info.lattice_reason, "lattice_approx_exhausted"); + const PlanResult result = map.plan(request, config); + EXPECT_FALSE(result.ok); + EXPECT_EQ(result.info.lattice_reason, "lattice_approx_exhausted"); + EXPECT_GE(result.info.lattice_refinement_attempts, 1u); +} + TEST(Lattice, TimeoutAndCancel) { LatticeTestGrid map(120, 120); @@ -1486,6 +1538,165 @@ TEST(Lattice, FieldZoneMarginKeepsDiagonalStepsOffTheLimit) EXPECT_FALSE(config.validate().empty()); } +TEST(Lattice, HeadingFieldRespectsSectorDirectionInAZone) +{ + LatticeTestGrid map(24, 16); + std::fill(map.direction.begin(), map.direction.end(), 1); + PlannerConfig config = latticeConfig(); + config.half_x_m = 0.03; + config.half_y_m = 0.03; + config.footprint_min_gap_m = 0.0; + config.max_deviation_deg = 45.0; + config.zone_transition_m = 0.0; + const RouteRequest request = latticeRequest(pose(0.225, 0.425, 0.0), pose(0.925, 0.425, 0.0)); + const GridRef grid = map.view(); + PlanInfo info; + detail::LatticeMemory memory(32 * 1024 * 1024); + const auto deadline = detail::Clock::now() + std::chrono::seconds(5); + detail::LatticeContext context{request, grid, config, 45.0, deadline, info, memory}; + detail::LatticeCSpace space(context); + detail::LatticeField field(&memory); + ASSERT_TRUE(detail::buildHeadingField(context, space, &field, deadline)); + const int x = static_cast(request.start.x / grid.resolution) / field.heading_factor; + const int y = static_cast(request.start.y / grid.resolution) / field.heading_factor; + const std::size_t state = (static_cast(y) * field.heading_width + x) * 8; + EXPECT_NE(field.heading_settled[state], 0u); // East is permitted. + EXPECT_EQ(field.heading_settled[state + 4], 0u); // West cannot rotate into east inside this zone. +} + +TEST(Lattice, HeadingFieldAvoidsWrongWayFootprintAlongZoneBoundary) +{ + LatticeTestGrid map(40, 30); + for (int y = 7; y < 13; ++y) + for (int x = 10; x < 30; ++x) + map.direction[static_cast(y) * map.width + x] = 5; // West. + PlannerConfig config = latticeConfig(); + config.half_x_m = 0.1; config.half_y_m = 0.15; config.footprint_min_gap_m = 0.0; + config.max_deviation_deg = 45.0; config.zone_transition_m = 1.0; + const RouteRequest request = latticeRequest(pose(0.225, 0.775, 0.0), pose(1.775, 0.775, 0.0)); + const GridRef grid = map.view(); + PlanInfo info; + detail::LatticeMemory memory(32 * 1024 * 1024); + const auto deadline = detail::Clock::now() + std::chrono::seconds(5); + detail::LatticeContext context{request, grid, config, 45.0, deadline, info, memory}; + detail::LatticeCSpace space(context); + detail::LatticeField field(&memory); + ASSERT_TRUE(detail::buildHeadingField(context, space, &field, deadline)); + const int x = static_cast(request.start.x / grid.resolution) / field.heading_factor; + const int y = static_cast(request.start.y / grid.resolution) / field.heading_factor; + const std::size_t state = (static_cast(y) * field.heading_width + x) * 8; + ASSERT_NE(field.heading_settled[state], 0u); + EXPECT_GT(field.heading_values[state], 1.55f + 0.025f); +} + +TEST(ZoneDeviation, SamplesDirectionAndValidatesWeight) +{ + LatticeTestGrid map(120, 120); + std::fill(map.direction.begin(), map.direction.end(), 3); + const GridRef grid = map.view(); + const ZoneDeviation diagonal = lineZoneDeviation({1.0, 1.0}, {3.0, 3.0}, grid); + EXPECT_NEAR(diagonal.deviated_length_m, std::sqrt(8.0), 1e-10); + EXPECT_NEAR(diagonal.integral_deg_m, 45.0 * std::sqrt(8.0), 1e-8); + EXPECT_NEAR(lineZoneDeviation({2.0, 1.0}, {2.0, 4.0}, grid).integral_deg_m, 0.0, 1e-10); + PlannerConfig config; + EXPECT_DOUBLE_EQ(config.zone_deviation_weight, 2.0); + config.zone_deviation_weight = -1.0; + EXPECT_FALSE(config.validate().empty()); + config.zone_deviation_weight = std::numeric_limits::quiet_NaN(); + EXPECT_FALSE(config.validate().empty()); +} + +TEST(ZoneDeviation, NorthLanePreferredAcrossZoneInterior) +{ + LatticeTestGrid map(300, 320); + for (int y = 80; y < 240; ++y) + for (int x = 20; x < 280; ++x) + map.direction[static_cast(y) * map.width + x] = 3; + PlannerConfig config = defaultConfig(); + config.max_deviation_deg = 45.0; + config.deviation_ladder_deg.clear(); + config.zone_deviation_weight = 20.0; + CoarseGraph coarse; + coarse.lanes.push_back({2, {5.0, 4.0}, {5.0, 12.0}, 8.0, 0.0}); + const GridRef grid = map.view(); + const GraphProvider provider = [&](double limit) { + return std::make_shared(compileGraph(coarse, grid, grid.cost, limit, config, RidgeBackend{})); + }; + const RouteRequest request{pose(5.0, 1.5, kPi/2), pose(7.0, 14.5, kPi/2), {}}; + const PlanResult result = planRoute(provider, request, grid, config, RidgeBackend{}); + ASSERT_TRUE(result.ok) << result.info.reason; + EXPECT_TRUE(result.check.valid); + double inside = 0.0, aligned = 0.0; + std::vector> visit; + const auto finish_visit = [&]() { + double length = 0.0, position = 0.0; + for (const auto& sample : visit) length += sample.first; + for (const auto& sample : visit) + { + const double part = std::max(0.0, std::min(position + sample.first, length - 1.0) - std::max(position, 1.0)); + inside += part; + if (sample.second) aligned += part; + position += sample.first; + } + visit.clear(); + }; + 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 ds = std::hypot(b.x-a.x, b.y-a.y); + if (ds < 1e-10) continue; + const int count = std::max(1, static_cast(std::ceil(ds / (grid.resolution * 0.5)))); + const bool follows = std::abs(wrapAngle(std::atan2(b.y-a.y, b.x-a.x)-kPi/2)) <= 3.0*kPi/180.0; + for (int j = 0; j < count; ++j) + { + const double t = (j + 0.5) / count; + const double x = a.x + (b.x-a.x)*t, y = a.y + (b.y-a.y)*t; + if (x >= 1.0 && x < 14.0 && y >= 4.0 && y < 12.0) visit.emplace_back(ds / count, follows); + else if (!visit.empty()) finish_visit(); + } + } + if (!visit.empty()) finish_visit(); + ASSERT_GT(inside, 5.0); + EXPECT_GE(aligned / inside, 0.9); + + // With the cost disabled the direct, diagonal shortcut is the old shortest-path choice. + config.zone_deviation_weight = 0.0; + const PlanResult old = planRoute(provider, request, grid, config, RidgeBackend{}); + ASSERT_TRUE(old.ok) << old.info.reason; + double old_deviated = 0.0; + for (std::size_t i = 1; i < old.path.size(); ++i) + old_deviated += lineZoneDeviation({old.path[i-1].x, old.path[i-1].y}, {old.path[i].x, old.path[i].y}, grid).deviated_length_m; + EXPECT_GT(old_deviated, 5.0); +} + +TEST(ZoneDeviation, DiagonalRemainsLegalAndZeroMatchesUnsetOnAlignedPath) +{ + LatticeTestGrid map(120, 120); + std::fill(map.direction.begin(), map.direction.end(), 1); + PlannerConfig config = latticeConfig(); + config.max_deviation_deg = 45.0; + config.deviation_ladder_deg.clear(); + const RouteRequest diagonal = latticeRequest(pose(1.025, 1.025, kPi/4), pose(3.025, 3.025, kPi/4)); + const PlanResult positive = map.plan(diagonal, config); + ASSERT_TRUE(positive.ok) << positive.info.reason; + EXPECT_TRUE(positive.check.valid); + const RouteRequest aligned = latticeRequest(pose(1.025, 2.025, 0.0), pose(4.025, 2.025, 0.0)); + const PlanResult unset = map.plan(aligned, config); // Default 2.0; the aligned path has no deviation cost. + config.zone_deviation_weight = 0.0; + const PlanResult zero = map.plan(aligned, config); + ASSERT_TRUE(unset.ok) << unset.info.reason; + ASSERT_EQ(zero.info.reason, unset.info.reason); + ASSERT_EQ(zero.path.size(), unset.path.size()); + for (std::size_t i = 0; i < zero.path.size(); ++i) + { + EXPECT_DOUBLE_EQ(zero.path[i].x, unset.path[i].x); + EXPECT_DOUBLE_EQ(zero.path[i].y, unset.path[i].y); + EXPECT_DOUBLE_EQ(zero.path[i].yaw, unset.path[i].yaw); + EXPECT_DOUBLE_EQ(zero.path[i].curvature, unset.path[i].curvature); + } +} + TEST(Lattice, AlternateFieldValidation) { PlannerConfig config = latticeConfig(); @@ -2466,6 +2677,9 @@ TEST(FootprintZones, OppositeZoneAcrossNarrowGapIsRejected) const PathCheck check = verifyPath(path, grid, 0.01, config); EXPECT_FALSE(check.valid); EXPECT_GT(check.zone_violations, 0); + EXPECT_TRUE(check.has_failure_location); + EXPECT_GE(check.failure_location.x, 1.0); + EXPECT_LE(check.failure_location.x, 4.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); @@ -2661,10 +2875,11 @@ TEST(FootprintZones, SideEntryUsesPathDistanceAndZeroDisablesTransition) 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)); + // The retry must retain a state on a legal side entry; the whole-path verifier enforces the transition distance. + context.allow_zone_transition = true; + EXPECT_TRUE(space.poseFree(path[69].x, path[69].y, path[69].yaw)); config.zone_transition_m = 0.0; + EXPECT_FALSE(space.poseFree(path[69].x, path[69].y, path[69].yaw)); const PathCheck blocked = verifyPath(path, grid, 10.0, 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 1f09324..2cc0308 100644 --- a/tools/lane_route_eval.cpp +++ b/tools/lane_route_eval.cpp @@ -131,7 +131,11 @@ void writeGraphDump(const std::string& directory, std::size_t ordinal, const std 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\":["; + << ",\"footprint_collisions\":" << attempt.footprint_collisions << ",\"failure_location\":"; + if (attempt.has_failure_location) + { out << '['; writeFinite(out, attempt.failure_location.x); out << ','; writeFinite(out, attempt.failure_location.y); out << ']'; } + else out << "null"; + out << ",\"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 << ']'; @@ -247,6 +251,7 @@ void applyOverrides(PlannerConfig* config) const std::map doubles{ { "lattice_closed_resolution_m", &config->lattice_closed_resolution_m }, { "zone_transition_m", &config->zone_transition_m }, + { "zone_deviation_weight", &config->zone_deviation_weight }, { "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 }, @@ -259,6 +264,7 @@ void applyOverrides(PlannerConfig* config) { "lattice_analytic_near_goal_m", &config->lattice_analytic_near_goal_m }, { "lattice_field_time_fraction", &config->lattice_field_time_fraction }, { "fallback_time_limit_s", &config->fallback_time_limit_s }, + { "time_limit_s", &config->time_limit_s }, { "lattice_end_relax_radius_m", &config->lattice_end_relax_radius_m }, { "min_turn_radius_m", &config->min_turn_radius_m }, { "max_kink_deg", &config->max_kink_deg }, @@ -478,8 +484,18 @@ int main(int argc, char** argv) 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; + ZoneDeviation zone_deviation; + 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 ZoneDeviation segment = lineZoneDeviation({a.x, a.y}, {b.x, b.y}, live_grid); + zone_deviation.deviated_length_m += segment.deviated_length_m; + zone_deviation.integral_deg_m += segment.integral_deg_m; + } 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 + << "\",\"zone_dev_len_m\":" << zone_deviation.deviated_length_m << ",\"zone_dev_integral\":" << zone_deviation.integral_deg_m + << ",\"query_ms\":" << info.query_ms << ",\"compile_ms\":" << info.compile_ms << ",\"coarse_ms\":" << coarse_ms << ",\"update_ms\":" << update_ms << ",\"search_ms\":" << info.search_ms << ",\"build_ms\":" << info.build_ms << ",\"verify_ms\":" << info.verify_ms << ",\"live_ridge_ms\":" << info.live_ridge_ms << ",\"live_ridge\":\"" << info.live_ridge << "\",\"rung\":" << info.rung_used_deg << ",\"retries\":" << info.retries << ",\"gap_failures\":" << info.gap_failures @@ -500,7 +516,9 @@ int main(int argc, char** argv) } out << ",\"tier\":\"" << info.tier_used << "\",\"graph_reason\":\"" << info.graph_reason << "\",\"lattice_reason\":\"" << info.lattice_reason << "\",\"lattice_states_expanded\":" << info.lattice_states_expanded + << ",\"lattice_closed_pruned\":" << info.lattice_closed_pruned << ",\"lattice_refinement_attempts\":" << info.lattice_refinement_attempts << ",\"lattice_pose_checks\":" << info.lattice_pose_checks << ",\"lattice_field_cells\":" << info.lattice_field_cells + << ",\"lattice_heading_field_states\":" << info.lattice_heading_field_states << ",\"lattice_tiles_built\":" << info.lattice_tiles_built << ",\"lattice_peak_bytes\":" << info.lattice_peak_bytes << ",\"lattice_crossing_rejects\":" << info.lattice_crossing_rejects << ",\"lattice_field_ms\":" << info.lattice_field_ms << ",\"lattice_search_ms\":" << info.lattice_search_ms