#include #include #include #include #include #include #include namespace lane_route_core { namespace { // Raw points are 0.25 m apart, so this is 50 m of route. It bounds a window at about 20000 line checks. constexpr std::size_t kMaxRawVertices = 200; constexpr double kLengthWeightDegPerM = 1.0; constexpr double kReversalPenaltyDeg = 30.0; // Turns below this keep the previous sign: a raw chain is never quite straight. constexpr double kSignThresholdDeg = 1.0; constexpr double kAngularTieRad = 1e-12; // One degree less turning may cost this much length. It keeps every removal of a swing on the measured maps, where // the dearest was 0.26 m for 12 degrees, and refuses the long way round: 2 m for 3.4 degrees, 0.36 m for 4.9 degrees. constexpr double kLengthPerDegreeM = 0.03; constexpr double kLengthMarginM = 0.02; constexpr double degrees(double radians) { return radians * 180.0 / kPi; } int classify(double turn_deg, int sign) { if (turn_deg >= kSignThresholdDeg) return 1; if (turn_deg <= -kSignThresholdDeg) return -1; return sign; } /** Same value as wrapAngle for a difference of two headings, which stays within one turn, without the division. */ double wrapHeadingDifference(double difference) { if (difference > kPi) return difference - 2.0 * kPi; return difference < -kPi ? difference + 2.0 * kPi : difference; } double reversalPenalty(int first, int second) { return first != 0 && second != 0 && first != second ? kReversalPenaltyDeg : 0.0; } double pathLength(const Path& path) { double total = 0.0; for (std::size_t i = 0; i + 1 < path.size(); ++i) total += std::hypot(path[i + 1].x - path[i].x, path[i + 1].y - path[i].y); return total; } /** Signs of the turns along these points that reach the threshold. */ std::vector turnSigns(const std::vector& points) { std::vector signs; for (std::size_t i = 0; i + 2 < points.size(); ++i) { const double turn = degrees(wrapAngle(headingOf(points[i + 1], points[i + 2]) - headingOf(points[i], points[i + 1]))); if (std::abs(turn) >= kSignThresholdDeg) signs.push_back(turn > 0.0 ? 1 : -1); } return signs; } /** Where each greedy vertex sits in the raw points. */ bool locateGreedy(const std::vector& raw, const std::vector& greedy, std::vector* indices) { indices->clear(); std::size_t cursor = 0; for (const Point2& point : greedy) { while (cursor < raw.size() && distanceOf(raw[cursor], point) > 1e-7) ++cursor; if (cursor == raw.size()) return false; indices->push_back(cursor); ++cursor; } return true; } struct DpState { int32_t previous, current; int sign; double heading; // Of the step previous -> current [rad]. double cost; int32_t parent; }; struct DpStep { int32_t to; double heading; // [rad] double length_m; }; } // namespace std::vector oppositePairs(const std::vector& chain) { std::vector pairs; for (std::size_t j = 1; j + 2 < chain.size(); ++j) { const double first = wrapAngle(headingOf(chain[j], chain[j + 1]) - headingOf(chain[j - 1], chain[j])); const double second = wrapAngle(headingOf(chain[j + 1], chain[j + 2]) - headingOf(chain[j], chain[j + 1])); if (first * second < 0.0) pairs.push_back(j); } return pairs; } double chainTurning(const std::vector& chain) { double total = 0.0; for (std::size_t j = 1; j + 1 < chain.size(); ++j) total += std::abs(wrapAngle(headingOf(chain[j], chain[j + 1]) - headingOf(chain[j - 1], chain[j]))); return total; } double movingTurning(const Path& path) { double total = 0.0; for (std::size_t i = 0; i + 1 < path.size(); ++i) if (std::hypot(path[i + 1].x - path[i].x, path[i + 1].y - path[i].y) > 1e-9) total += std::abs(wrapAngle(path[i + 1].yaw - path[i].yaw)); return total; } bool preferLessTurning(const Path& candidate, const Path& baseline) { const double new_turn = movingTurning(candidate); const double old_turn = movingTurning(baseline); if (new_turn < old_turn - kAngularTieRad) return pathLength(candidate) <= pathLength(baseline) + kLengthMarginM + kLengthPerDegreeM * degrees(old_turn - new_turn); return std::abs(new_turn - old_turn) <= kAngularTieRad && pathLength(candidate) < pathLength(baseline); } bool solveSwingWindow(const std::vector& raw, const std::vector& locked, std::size_t start, std::size_t end, const SwingSearch& search, const Point2* preceding, int preceding_sign, const Point2* following, int following_sign, SwingStats* stats, std::vector* selected) { const std::size_t count = end - start + 1; if (end <= start || count > kMaxRawVertices) return false; const auto expired = [&search]() { return (search.cancel != nullptr && search.cancel->load(std::memory_order_relaxed)) || std::chrono::steady_clock::now() >= search.deadline; }; const Point2* v = raw.data() + start; const uint8_t* lock = locked.data() + start; std::vector prefix(count, 0.0); for (std::size_t i = 0; i + 1 < count; ++i) prefix[i + 1] = prefix[i] + search.line_cost(v[i], v[i + 1]); // Allowed steps from each point, under the same tiers as the greedy shortcut. std::vector> allowed(count - 1); for (std::size_t i = 0; i + 1 < count; ++i) { if (expired()) return false; std::size_t boundary = count - 1; for (std::size_t j = i + 1; j < count; ++j) { if (lock[j] != 0) { boundary = j; break; } } std::vector steps; for (int tier : search.tiers_mm) { for (std::size_t j = boundary; j > i; --j) { if (expired()) return false; ++stats->line_checks; if (search.line_ok(v[i], v[j], tier) && search.line_cost(v[i], v[j]) <= prefix[j] - prefix[i] + 1e-8) steps.push_back(static_cast(j)); } bool reaches = false; for (int32_t j : steps) reaches = reaches || j > static_cast(i) + 1; if (reaches) break; } steps.push_back(static_cast(i) + 1); std::sort(steps.begin(), steps.end()); steps.erase(std::unique(steps.begin(), steps.end()), steps.end()); // Each step is visited once per state arriving at i, so on a long open section the search below repeats it very // often. Its heading and length are computed once, here. allowed[i].reserve(steps.size()); for (int32_t j : steps) allowed[i].push_back({ j, headingOf(v[i], v[j]), distanceOf(v[i], v[j]) }); } // A state is the last step and the sign of the last turn, because the next turn depends on both. const std::size_t n = count; std::vector state_at(n * n * 3, -1); const auto slot = [n](int32_t previous, int32_t current, int sign) { return (static_cast(previous) * n + static_cast(current)) * 3 + static_cast(sign + 1); }; std::vector states; std::vector> by_current(n); const auto relax = [&](int32_t previous, const DpStep& step, int sign, double cost, int32_t parent) { const int32_t current = step.to; int32_t& at = state_at[slot(previous, current, sign)]; if (at < 0) { at = static_cast(states.size()); states.push_back({ previous, current, sign, step.heading, cost, parent }); by_current[static_cast(current)].push_back(at); } else if (cost < states[static_cast(at)].cost - 1e-12) { states[static_cast(at)].cost = cost; states[static_cast(at)].parent = parent; } }; for (const DpStep& step : allowed[0]) { const double turn = preceding != nullptr ? degrees(wrapAngle(step.heading - headingOf(*preceding, v[0]))) : 0.0; const int sign = classify(turn, preceding_sign); relax(0, step, sign, kLengthWeightDegPerM * step.length_m + std::abs(turn) + reversalPenalty(preceding_sign, sign), -1); } for (int32_t i = 1; i + 1 < static_cast(n); ++i) { if (expired()) return false; // A later point can never add a state here, so this list and these costs are final. for (int32_t id : by_current[static_cast(i)]) { const double incoming = states[static_cast(id)].heading; const int sign = states[static_cast(id)].sign; const double base = states[static_cast(id)].cost; for (const DpStep& step : allowed[static_cast(i)]) { const double turn = degrees(wrapHeadingDifference(step.heading - incoming)); const int new_sign = classify(turn, sign); relax(i, step, new_sign, base + std::abs(turn) + kLengthWeightDegPerM * step.length_m + reversalPenalty(sign, new_sign), id); } } } const int32_t last = static_cast(n) - 1; int32_t best = -1; double best_score = std::numeric_limits::infinity(); for (int32_t id : by_current[static_cast(last)]) { const DpState& state = states[static_cast(id)]; double score = state.cost; int sign = state.sign; if (following != nullptr) { const double angle = degrees(wrapAngle(headingOf(v[last], *following) - state.heading)); const int updated = classify(angle, sign); score += std::abs(angle) + reversalPenalty(sign, updated); sign = updated; } score += reversalPenalty(sign, following_sign); bool better = score < best_score; if (!better && score == best_score && best >= 0) { const DpState& other = states[static_cast(best)]; better = std::make_tuple(state.previous, state.current, state.sign) < std::make_tuple(other.previous, other.current, other.sign); } if (better) { best = id; best_score = score; } } if (best < 0) return false; selected->clear(); selected->push_back(start + static_cast(last)); for (int32_t id = best; id >= 0; id = states[static_cast(id)].parent) selected->push_back(start + static_cast(states[static_cast(id)].previous)); std::reverse(selected->begin(), selected->end()); return true; } bool optimizeSwingChain(const RawChain& raw, const std::vector& greedy, const SwingSearch& search, SwingStats* stats, std::vector* vertices, std::vector* indices) { const std::vector pairs = oppositePairs(greedy); if (pairs.empty()) return false; std::vector greedy_indices; if (!locateGreedy(raw.vertices, greedy, &greedy_indices)) return false; // Each swing searches its whole free run, from the lane point before it to the lane point after it. std::vector> windows; const std::size_t raw_count = raw.vertices.size(); for (std::size_t j : pairs) { std::size_t left = 0; for (std::size_t i = greedy_indices[j] + 1; i-- > 0;) { if (raw.locked[i] != 0) { left = i; break; } } std::size_t right = raw_count - 1; for (std::size_t i = greedy_indices[j + 1]; i < raw_count; ++i) { if (raw.locked[i] != 0) { right = i; break; } } if (right - left + 1 > kMaxRawVertices) { left = greedy_indices[j >= 2 ? j - 2 : 0]; right = greedy_indices[std::min(greedy_indices.size() - 1, j + 3)]; ++stats->trimmed_windows; } windows.emplace_back(left, right); } std::sort(windows.begin(), windows.end()); std::vector> merged; for (const auto& window : windows) { if (!merged.empty() && window.first <= merged.back().second) merged.back().second = std::max(window.second, merged.back().second); else merged.push_back(window); } std::vector chosen = greedy_indices; for (const auto& window : merged) { ++stats->windows; const std::size_t left = window.first, right = window.second; if (right - left + 1 > kMaxRawVertices) { ++stats->oversize_windows; continue; } std::vector before, after; for (std::size_t i : chosen) { if (i < left) before.push_back(raw.vertices[i]); else if (i > right) after.push_back(raw.vertices[i]); } const bool has_before = !before.empty(), has_after = !after.empty(); const Point2 previous = has_before ? before.back() : Point2{}; const Point2 next = has_after ? after.front() : Point2{}; before.push_back(raw.vertices[left]); after.insert(after.begin(), raw.vertices[right]); const std::vector before_signs = turnSigns(before); const std::vector after_signs = turnSigns(after); std::vector selected; if (!solveSwingWindow(raw.vertices, raw.locked, left, right, search, has_before ? &previous : nullptr, before_signs.empty() ? 0 : before_signs.back(), has_after ? &next : nullptr, after_signs.empty() ? 0 : after_signs.front(), stats, &selected)) continue; std::set updated(selected.begin(), selected.end()); for (std::size_t i : chosen) if (i < left || i > right) updated.insert(i); chosen.assign(updated.begin(), updated.end()); } if (chosen == greedy_indices) return false; vertices->clear(); for (std::size_t i : chosen) vertices->push_back(raw.vertices[i]); *indices = chosen; return true; } } // namespace lane_route_core