#include #include #include #include #include #include #include namespace lane_route_core { namespace { constexpr double kLeadStepM = 0.25; constexpr int kLeadSteps = 10; // Straight lead of at most 2.5 m on each lane end. // Must not exceed the depth of a gate zone. Gates are about 0.5 m deep, and a strict rung has no other way through them. 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; constexpr double kPreferredAttachRadiusM = 6.0; constexpr int32_t kPreferredAttachCandidates = 30; constexpr double kMinLinkM = 0.05; constexpr double kClearancePenalty = 0.25; constexpr double kClearancePenaltyStartM = 0.6; double polylineLength(const std::vector& points) { double total = 0.0; for (std::size_t i = 0; i + 1 < points.size(); ++i) total += distanceOf(points[i], points[i + 1]); return total; } /** Sample cells of one polyline, spaced at most half a cell. */ template void forEachSample(const std::vector& points, const GridRef& grid, Visit visit) { const double half = grid.resolution * 0.5; for (std::size_t i = 0; i + 1 < points.size(); ++i) { const double dx = points[i + 1].x - points[i].x; const double dy = points[i + 1].y - points[i].y; const double length = std::hypot(dx, dy); if (length < 1e-12) continue; const int samples = std::max(1, static_cast(std::ceil(length / half))); const double weight = length / samples; 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); } } } /** Length-weighted mean of the cost factors. Blocked or off-grid samples make the edge impassable. */ class FactorSum { public: void add(int32_t cell, double weight, const uint8_t* master) { const uint8_t value = cell >= 0 ? master[cell] : kNoInformation; cost_ += weight * costFactor(value); length_ += weight; blocked_ = blocked_ || value >= kInscribedCost; } double factor() const { if (blocked_) return std::numeric_limits::infinity(); return length_ > 0.0 ? cost_ / length_ : 1.0; } private: double cost_ = 0.0, length_ = 0.0; bool blocked_ = false; }; } // namespace 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); }); return sum.factor(); } void compiledEdgeFactors(const CompiledGraph& graph, const uint8_t* master, std::vector* factors) { factors->resize(graph.edges.size()); for (std::size_t i = 0; i < graph.edges.size(); ++i) { FactorSum sum; for (int32_t k = graph.sample_offsets[i]; k < graph.sample_offsets[i + 1]; ++k) sum.add(graph.sample_cells[static_cast(k)], graph.sample_weights[static_cast(k)], master); (*factors)[i] = sum.factor(); } } CompiledGraph compileGraph(const CoarseGraph& coarse, const GridRef& grid, const uint8_t* master, double deviation_deg, const PlannerConfig& config, const RidgeBackend& backend, const std::atomic* cancel) { const auto cancelled = [cancel]() { return cancel && cancel->load(std::memory_order_relaxed); }; if (cancelled()) return {}; const int hard_mm = clearanceThresholdMm(config.clearance_hard_m); const auto line_ok = [&](const Point2& a, const Point2& b) { return lineOk(grid, a, b, deviation_deg, hard_mm); }; const auto poly_ok = [&](const std::vector& points) { return polylineOk(grid, points, deviation_deg, hard_mm); }; CompiledGraph graph; graph.deviation_deg = deviation_deg; graph.nodes = coarse.nodes; const int32_t voronoi_nodes = static_cast(graph.nodes.size()); const auto add_both_ways = [&](int32_t from, int32_t to, const std::vector& points, EdgeKind kind) { const double length = polylineLength(points); if (poly_ok(points)) graph.edges.push_back({ from, to, points, kind, length }); std::vector reversed(points.rbegin(), points.rend()); if (poly_ok(reversed)) graph.edges.push_back({ to, from, std::move(reversed), kind, length }); }; for (const CoarseEdge& edge : coarse.edges) { if (cancelled()) return {}; add_both_ways(edge.from, edge.to, edge.points, EdgeKind::kVoronoi); } // Lanes with the longest legal straight lead on each end. std::vector lane_ends; const auto add_node = [&](const Point2& point) { graph.nodes.push_back(point); return static_cast(graph.nodes.size()) - 1; }; for (const CoarseLane& lane : coarse.lanes) { if (cancelled()) return {}; if (lane.length_m < kMinCompiledLaneM) continue; const double angle = lane.direction_index * kPi / 4.0; const double ux = std::cos(angle); const double uy = std::sin(angle); const Point2 a = lane.entry; const Point2 b = lane.exit; const auto along = [&](const Point2& origin, double distance) { return Point2{ origin.x + distance * ux, origin.y + distance * uy }; }; Point2 left = a; Point2 right = b; for (int k = 1; k <= kLeadSteps; ++k) { const Point2 candidate = along(a, -kLeadStepM * k); if (!line_ok(candidate, a)) break; left = candidate; } for (int k = 1; k <= kLeadSteps; ++k) { const Point2 candidate = along(b, kLeadStepM * k); if (!line_ok(b, candidate)) break; right = candidate; } const std::vector full{ left, a, b, right }; if (!poly_ok(full)) continue; const double penalty = kLaneOffsetPenalty * lane.offset_from_centre_m; const int32_t u = add_node(left); const int32_t v = add_node(right); graph.edges.push_back({ u, v, full, EdgeKind::kLane, polylineLength(full) + penalty }); lane_ends.push_back(u); lane_ends.push_back(v); // A goal may lie just outside a zone: shorter exits on the straight lead, without turning off the lane. std::vector> exits{ { v, right } }; const double lead_out = distanceOf(b, right); for (double distance : kShortLeads) { if (distance >= lead_out - 0.02) continue; const Point2 stop = along(b, distance); const int32_t w = add_node(stop); exits.emplace_back(w, stop); const std::vector shorter{ left, a, b, stop }; graph.edges.push_back({ u, w, shorter, EdgeKind::kLane, polylineLength(shorter) + penalty }); } // Entries on the lead as well. With only the far entry, a start beside the lead has to pass it // and circle back to enter the lane, which is how self-crossing loops appeared. const double lead_in = distanceOf(a, left); for (double distance : kShortLeads) { if (distance >= lead_in - 0.02) continue; const Point2 begin = along(a, -distance); const int32_t w = add_node(begin); for (const auto& target : exits) { const std::vector shorter{ begin, a, b, target.second }; graph.edges.push_back({ w, target.first, shorter, EdgeKind::kLane, polylineLength(shorter) + penalty }); } } } // Links between lane ends and the network, both ways where the direction limit allows. std::vector junction_ids(static_cast(voronoi_nodes)); for (int32_t i = 0; i < voronoi_nodes; ++i) junction_ids[static_cast(i)] = i; junction_ids.insert(junction_ids.end(), lane_ends.begin(), lane_ends.end()); std::vector junction_points; junction_points.reserve(junction_ids.size()); for (int32_t id : junction_ids) junction_points.push_back(graph.nodes[static_cast(id)]); const int32_t junction_count = static_cast(junction_points.size()); for (int32_t u : lane_ends) { if (cancelled()) return {}; const Point2 here = graph.nodes[static_cast(u)]; int accepted = 0; for (const auto& found : nearestNodes(junction_points, junction_count, here, std::min(junction_count, kJunctionCandidates), kJunctionRadiusM)) { const int32_t v = junction_ids[static_cast(found.second)]; if (v == u || found.first < kMinLinkM) continue; const Point2 there = graph.nodes[static_cast(v)]; if (line_ok(here, there)) graph.edges.push_back({ u, v, { here, there }, EdgeKind::kJunction, found.first }); if (line_ok(there, here)) graph.edges.push_back({ v, u, { there, here }, EdgeKind::kJunction, found.first }); if (++accepted >= kJunctionLinks) break; } } // Preferred region: its centre line joins the network. Direction grid and real clearance still gate each edge. const std::size_t cell_count = static_cast(grid.width) * static_cast(grid.height); if (master != nullptr && backend.region_centre_edges && std::find(master, master + cell_count, kPreferredSpace) != master + cell_count) { std::vector mask(cell_count, 0); for (std::size_t i = 0; i < cell_count; ++i) { if ((i & 4095u) == 0 && cancelled()) return {}; mask[i] = master[i] == kPreferredSpace && grid.cost[i] < kInscribedCost ? 1 : 0; } std::vector preferred_nodes; std::vector preferred_edges; if (cancelled()) return {}; backend.region_centre_edges(mask, grid, &preferred_nodes, &preferred_edges, cancel); if (cancelled()) return {}; const int32_t base = static_cast(graph.nodes.size()); graph.nodes.insert(graph.nodes.end(), preferred_nodes.begin(), preferred_nodes.end()); for (const CoarseEdge& edge : preferred_edges) add_both_ways(base + edge.from, base + edge.to, edge.points, EdgeKind::kPreferredRidge); if (base > 0) { for (std::size_t local = 0; local < preferred_nodes.size(); ++local) { if (cancelled()) return {}; const Point2 here = preferred_nodes[local]; const int32_t id = base + static_cast(local); for (const auto& found : nearestNodes(graph.nodes, base, here, std::min(base, kPreferredAttachCandidates), kPreferredAttachRadiusM)) { if (found.first < kMinLinkM) continue; const Point2 there = graph.nodes[static_cast(found.second)]; if (line_ok(there, here)) graph.edges.push_back({ found.second, id, { there, here }, EdgeKind::kPreferredAttach, found.first }); if (line_ok(here, there)) graph.edges.push_back({ id, found.second, { here, there }, EdgeKind::kPreferredAttach, found.first }); } } } } // Penalise low clearance without changing the hard clearance rule. for (GraphEdge& edge : graph.edges) { if (cancelled()) return {}; int minimum_mm = std::numeric_limits::max(); for (const Point2& point : edge.points) { const int32_t ix = std::min(grid.width - 1, std::max(0, static_cast(std::floor((point.x - grid.origin_x) / grid.resolution)))); const int32_t iy = std::min(grid.height - 1, std::max(0, static_cast(std::floor((point.y - grid.origin_y) / grid.resolution)))); minimum_mm = std::min(minimum_mm, grid.clearance_mm[iy * grid.width + ix]); } const double clearance = minimum_mm / 1000.0; edge.cost += kClearancePenalty * polylineLength(edge.points) * std::max(0.0, (kClearancePenaltyStartM - clearance) / kClearancePenaltyStartM); } graph.outgoing.resize(graph.nodes.size()); graph.sample_offsets.reserve(graph.edges.size() + 1); graph.sample_offsets.push_back(0); for (std::size_t i = 0; i < graph.edges.size(); ++i) { 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) { graph.sample_cells.push_back(cell); graph.sample_weights.push_back(weight); }); graph.sample_offsets.push_back(static_cast(graph.sample_cells.size())); } return graph; } } // namespace lane_route_core