- New output_endpoint_spins (default false): the published plan starts at the first driving pose and ends with one goal pose. The local planner turns in place by itself; the planner still verifies both spins are collision free. - Load and clamp zone_deviation_weight; print both keys in the boot line. - Tests for the trim helper (29 pass).
445 lines
18 KiB
C++
445 lines
18 KiB
C++
#include <lane_route_planner/lane_route_session.h>
|
|
|
|
#include <algorithm>
|
|
#include <chrono>
|
|
#include <cmath>
|
|
#include <cstring>
|
|
#include <ctime>
|
|
#include <filesystem>
|
|
#include <fstream>
|
|
#include <iomanip>
|
|
#include <limits>
|
|
#include <sstream>
|
|
#include <system_error>
|
|
#include <utility>
|
|
|
|
#include <lane_route_core/costmap_backend.h>
|
|
#include <lane_route_core/grid_checks.h>
|
|
|
|
namespace lane_route_planner
|
|
{
|
|
namespace
|
|
{
|
|
bool finitePose(const robot_geometry_msgs::PoseStamped& p)
|
|
{
|
|
const auto& q = p.pose.orientation;
|
|
const auto& x = p.pose.position;
|
|
return std::isfinite(x.x) && std::isfinite(x.y) && std::isfinite(x.z) && std::isfinite(q.x) &&
|
|
std::isfinite(q.y) && std::isfinite(q.z) && std::isfinite(q.w);
|
|
}
|
|
|
|
bool sameGeometry(const robot_costmap_2d::DirectionGeometry& g, const lane_route_core::GridRef& grid,
|
|
const std::string& frame)
|
|
{
|
|
return g.width == static_cast<uint32_t>(grid.width) && g.height == static_cast<uint32_t>(grid.height) &&
|
|
std::abs(g.resolution - grid.resolution) < 1e-8 && std::abs(g.origin_x - grid.origin_x) < 1e-8 &&
|
|
std::abs(g.origin_y - grid.origin_y) < 1e-8 && g.frame_id == frame;
|
|
}
|
|
|
|
lane_route_core::Pose2 poseOf(const robot_geometry_msgs::PoseStamped& p, bool has_yaw)
|
|
{
|
|
const auto& q = p.pose.orientation;
|
|
return { p.pose.position.x, p.pose.position.y,
|
|
std::atan2(2.0 * (q.w * q.z + q.x * q.y), 1.0 - 2.0 * (q.y * q.y + q.z * q.z)), has_yaw };
|
|
}
|
|
} // namespace
|
|
|
|
std::string SessionConfig::validate() const
|
|
{
|
|
const auto nonnegative = [](double x)
|
|
{
|
|
return std::isfinite(x) && x >= 0.0;
|
|
};
|
|
std::ostringstream error;
|
|
if (!nonnegative(clearance_min_margin_m))
|
|
error << "clearance_min_margin_m must be finite and >= 0, got " << clearance_min_margin_m;
|
|
else if (!nonnegative(clearance_preferred_margin_m))
|
|
error << "clearance_preferred_margin_m must be finite and >= 0, got " << clearance_preferred_margin_m;
|
|
else if (clearance_preferred_margin_m < clearance_min_margin_m)
|
|
error << "clearance_preferred_margin_m=" << clearance_preferred_margin_m
|
|
<< " must be >= clearance_min_margin_m=" << clearance_min_margin_m;
|
|
else if (!nonnegative(collision_check_margin_m))
|
|
error << "collision_check_margin_m must be finite and >= 0, got " << collision_check_margin_m;
|
|
else if (debug_dump_max_files < 0)
|
|
error << "debug/dump_max_files must be >= 0, got " << debug_dump_max_files;
|
|
if (!error.str().empty())
|
|
return error.str();
|
|
return planner.validate();
|
|
}
|
|
|
|
lane_route_core::Path trimEndpointSpins(const lane_route_core::Path& path)
|
|
{
|
|
// The core writes an endpoint rotation as poses at one exact position, so a tight tolerance is enough.
|
|
constexpr double kSamePositionM = 1e-6;
|
|
const auto same = [&path](std::size_t a, std::size_t b) {
|
|
return std::hypot(path[a].x - path[b].x, path[a].y - path[b].y) <= kSamePositionM;
|
|
};
|
|
if (path.size() < 3)
|
|
return path;
|
|
std::size_t first = 0;
|
|
while (first + 1 < path.size() && same(first, first + 1))
|
|
++first;
|
|
std::size_t last = path.size() - 1;
|
|
while (last > first && same(last - 1, last))
|
|
--last;
|
|
if (first >= last)
|
|
return path;
|
|
return lane_route_core::Path(path.begin() + static_cast<std::ptrdiff_t>(first),
|
|
path.begin() + static_cast<std::ptrdiff_t>(last) + 1);
|
|
}
|
|
|
|
namespace
|
|
{
|
|
// Run-length text in the format lane_route_eval reads: "<key> <run count>" then "<value> <count>" pairs.
|
|
void writeRuns(std::ostream& out, const char* key, const uint8_t* data, std::size_t count)
|
|
{
|
|
std::vector<std::pair<int, std::size_t>> runs;
|
|
for (std::size_t i = 0; i < count;)
|
|
{
|
|
std::size_t j = i;
|
|
while (j < count && data[j] == data[i])
|
|
++j;
|
|
runs.emplace_back(data[i], j - i);
|
|
i = j;
|
|
}
|
|
out << key << ' ' << runs.size() << '\n';
|
|
for (const auto& run : runs)
|
|
out << run.first << ' ' << run.second << ' ';
|
|
out << '\n';
|
|
}
|
|
|
|
void writePose(std::ostream& out, const lane_route_core::Pose2& pose)
|
|
{
|
|
out << (pose.has_yaw ? 1 : 0) << ' ' << pose.x << ' ' << pose.y << ' ' << pose.yaw;
|
|
}
|
|
} // namespace
|
|
|
|
std::string writeFailureDump(const std::string& dir, const std::string& name, const lane_route_core::GridRef& live,
|
|
const std::vector<uint8_t>& static_cost, const std::vector<uint8_t>& directions,
|
|
const lane_route_core::RouteRequest& route, const lane_route_core::PlannerConfig& config,
|
|
const lane_route_core::PlanResult& result)
|
|
{
|
|
const std::size_t cells = static_cast<std::size_t>(live.width) * static_cast<std::size_t>(live.height);
|
|
if (!live.cost || static_cost.size() != cells || (!directions.empty() && directions.size() != cells))
|
|
return {};
|
|
std::error_code error;
|
|
std::filesystem::create_directories(dir, error);
|
|
if (error)
|
|
return {};
|
|
const std::string stem = (std::filesystem::path(dir) / name).string();
|
|
{
|
|
std::ofstream grid(stem + ".grid");
|
|
grid << std::setprecision(10) << "reference_grid 1\nsize " << live.width << ' ' << live.height << "\nresolution "
|
|
<< live.resolution << "\norigin " << live.origin_x << ' ' << live.origin_y << '\n';
|
|
writeRuns(grid, "cost", static_cost.data(), cells);
|
|
grid << "variants 1\n";
|
|
if (directions.empty())
|
|
{
|
|
const std::vector<uint8_t> none(cells, 0);
|
|
writeRuns(grid, "direction", none.data(), cells);
|
|
}
|
|
else
|
|
{
|
|
writeRuns(grid, "direction", directions.data(), cells);
|
|
}
|
|
std::ofstream master(stem + ".live");
|
|
writeRuns(master, "cost", live.cost, cells);
|
|
std::ofstream scene(stem + ".scene");
|
|
scene << std::setprecision(10) << name << ' ' << stem << ".grid 0 " << stem << ".live ";
|
|
writePose(scene, route.start);
|
|
scene << ' ';
|
|
writePose(scene, route.goal);
|
|
scene << " 0\n";
|
|
std::ofstream meta(stem + ".txt");
|
|
const auto& info = result.info;
|
|
meta << std::setprecision(10) << "reason " << info.reason << "\ngraph_reason " << info.graph_reason << "\nlattice_reason "
|
|
<< info.lattice_reason << "\nquery_ms " << info.query_ms << "\nlattice_states_expanded " << info.lattice_states_expanded
|
|
<< "\nmax_deviation_deg " << config.max_deviation_deg << "\nhalf_x_m " << config.half_x_m << "\nhalf_y_m "
|
|
<< config.half_y_m << "\nclearance_min_m " << config.clearance_min_m << "\nfootprint_min_gap_m "
|
|
<< config.footprint_min_gap_m << "\nmin_turn_radius_m " << config.min_turn_radius_m << "\nlattice_enabled "
|
|
<< config.lattice_enabled << "\nfallback_time_limit_s " << config.fallback_time_limit_s << "\ntime_limit_s "
|
|
<< config.time_limit_s << "\n# Replay: lane_route_eval " << stem << ".scene " << stem
|
|
<< ".jsonl <profile with these half sizes> " << config.max_deviation_deg << " none fallback\n";
|
|
if (!grid || !master || !scene || !meta)
|
|
return {};
|
|
}
|
|
return stem;
|
|
}
|
|
|
|
bool footprintRectangle(const std::vector<robot_geometry_msgs::Point>& footprint, double* half_x, double* half_y,
|
|
bool* centered_rectangle)
|
|
{
|
|
if (!half_x || !half_y || !centered_rectangle || footprint.size() < 3)
|
|
return false;
|
|
*half_x = 0.0;
|
|
*half_y = 0.0;
|
|
for (const auto& p : footprint)
|
|
{
|
|
if (!std::isfinite(p.x) || !std::isfinite(p.y))
|
|
return false;
|
|
*half_x = std::max(*half_x, std::abs(p.x));
|
|
*half_y = std::max(*half_y, std::abs(p.y));
|
|
}
|
|
if (*half_x <= 0 || *half_y <= 0)
|
|
return false;
|
|
unsigned corners = 0;
|
|
for (const auto& p : footprint)
|
|
{
|
|
if (std::abs(std::abs(p.x) - *half_x) > 1e-9 || std::abs(std::abs(p.y) - *half_y) > 1e-9)
|
|
continue;
|
|
corners |= 1u << ((p.x > 0 ? 1 : 0) + (p.y > 0 ? 2 : 0));
|
|
}
|
|
*centered_rectangle = footprint.size() == 4 && corners == 15;
|
|
if (*centered_rectangle)
|
|
{
|
|
for (std::size_t i = 0; i < 4; ++i)
|
|
{
|
|
const auto& a = footprint[i];
|
|
const auto& b = footprint[(i + 1) % 4];
|
|
if ((std::abs(a.x - b.x) < 1e-9) == (std::abs(a.y - b.y) < 1e-9))
|
|
*centered_rectangle = false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
std::string validateState(const SessionRequest& r)
|
|
{
|
|
if (!r.initialized)
|
|
return "not_initialized";
|
|
if (!finitePose(r.start))
|
|
return "invalid_start_pose";
|
|
if (!finitePose(r.goal))
|
|
return "invalid_goal_pose";
|
|
if (r.start.header.frame_id != r.frame || r.goal.header.frame_id != r.frame)
|
|
return "frame_mismatch";
|
|
if (r.graph.state == robot_costmap_2d::ReferenceGraphState::kDisabled)
|
|
return "graph_disabled";
|
|
if (r.graph.state == robot_costmap_2d::ReferenceGraphState::kPending || !r.graph.graph)
|
|
return "graph_pending";
|
|
if (r.direction.state == robot_costmap_2d::DirectionFieldState::kPending ||
|
|
(r.direction.state == robot_costmap_2d::DirectionFieldState::kReady && !r.direction.field))
|
|
return "direction_pending";
|
|
if (r.graph.graph->direction_generation != r.direction.generation)
|
|
return "direction_generation_mismatch";
|
|
return {};
|
|
}
|
|
|
|
std::string validateGrid(const SessionRequest& r)
|
|
{
|
|
if (r.live.width <= 0 || r.live.height <= 0 || !std::isfinite(r.live.resolution) || r.live.resolution <= 0 ||
|
|
!std::isfinite(r.live.origin_x) || !std::isfinite(r.live.origin_y) || !r.live.cost ||
|
|
!sameGeometry(r.graph.graph->geometry, r.live, r.frame) ||
|
|
(r.direction.field && !sameGeometry(r.direction.field->geometry(), r.live, r.frame)))
|
|
return "graph_geometry_mismatch";
|
|
const std::size_t cells = static_cast<std::size_t>(r.live.width) * static_cast<std::size_t>(r.live.height);
|
|
if (cells > static_cast<std::size_t>(std::numeric_limits<int32_t>::max()))
|
|
return "graph_geometry_mismatch";
|
|
if (r.graph.graph->static_cost.size() != cells || r.graph.graph->clearance_mm.size() != cells)
|
|
return "graph_data_invalid";
|
|
double x, y;
|
|
bool rect;
|
|
if (!footprintRectangle(r.footprint, &x, &y, &rect))
|
|
return "invalid_footprint";
|
|
if (!std::isfinite(r.inscribed_radius_m) || r.inscribed_radius_m < 0)
|
|
return "invalid_inscribed_radius";
|
|
return {};
|
|
}
|
|
|
|
std::string validateRequest(const SessionRequest& r)
|
|
{
|
|
const std::string state_error = validateState(r);
|
|
if (!state_error.empty())
|
|
return state_error;
|
|
return validateGrid(r);
|
|
}
|
|
|
|
void LaneRouteSession::clearCache()
|
|
{
|
|
graphs_.clear();
|
|
coarse_ = {};
|
|
preferred_mask_.clear();
|
|
preferred_mask_empty_ = true;
|
|
directions_.clear();
|
|
graph_identity_ = nullptr;
|
|
direction_identity_ = nullptr;
|
|
half_x_ = -1;
|
|
half_y_ = -1;
|
|
inscribed_ = -1;
|
|
}
|
|
|
|
lane_route_core::PlanResult LaneRouteSession::plan(const SessionRequest& request)
|
|
{
|
|
using namespace lane_route_core;
|
|
last_dump_.clear();
|
|
PlanResult failed;
|
|
failed.info.reason = validateRequest(request);
|
|
if (!failed.info.reason.empty())
|
|
return failed;
|
|
const std::string error = config_.validate();
|
|
if (!error.empty())
|
|
{
|
|
failed.info.reason = "invalid_config: " + error;
|
|
return failed;
|
|
}
|
|
if (request.cancel && request.cancel->load(std::memory_order_relaxed))
|
|
{
|
|
failed.info.reason = "cancelled";
|
|
return failed;
|
|
}
|
|
const auto& reference = *request.graph.graph;
|
|
const std::size_t cells = static_cast<std::size_t>(request.live.width) * request.live.height;
|
|
double half_x, half_y;
|
|
bool rectangle;
|
|
footprintRectangle(request.footprint, &half_x, &half_y, &rectangle);
|
|
if (graph_identity_ != request.graph.graph.get() || graph_generation_ != request.graph.generation ||
|
|
half_x_ != half_x || half_y_ != half_y || inscribed_ != request.inscribed_radius_m)
|
|
{
|
|
graphs_.clear();
|
|
preferred_mask_.clear();
|
|
coarse_ = toCoarseGraph(reference, request.cancel);
|
|
if (request.cancel && request.cancel->load(std::memory_order_relaxed))
|
|
{
|
|
clearCache();
|
|
failed.info.reason = "cancelled";
|
|
return failed;
|
|
}
|
|
graph_identity_ = request.graph.graph.get();
|
|
graph_generation_ = request.graph.generation;
|
|
half_x_ = half_x;
|
|
half_y_ = half_y;
|
|
inscribed_ = request.inscribed_radius_m;
|
|
}
|
|
const auto* field = request.direction.field.get();
|
|
if (direction_identity_ != field || direction_generation_ != request.direction.generation)
|
|
{
|
|
graphs_.clear();
|
|
directions_.clear();
|
|
direction_identity_ = field;
|
|
direction_generation_ = request.direction.generation;
|
|
if (field && field->hasConstraints())
|
|
{
|
|
directions_.resize(cells);
|
|
for (int32_t y = 0; y < request.live.height; ++y)
|
|
for (int32_t x = 0; x < request.live.width; ++x)
|
|
directions_[static_cast<std::size_t>(y) * request.live.width + x] = field->code(x, y);
|
|
}
|
|
}
|
|
const bool live_has_preferred = std::memchr(request.live.cost, kPreferredSpace, cells) != nullptr;
|
|
bool preferred_changed = preferred_mask_.size() != cells;
|
|
if (!preferred_changed && (live_has_preferred || !preferred_mask_empty_))
|
|
{
|
|
for (std::size_t i = 0; i < cells; ++i)
|
|
{
|
|
if (preferred_mask_[i] != (request.live.cost[i] == kPreferredSpace))
|
|
{
|
|
preferred_changed = true;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
if (preferred_changed)
|
|
{
|
|
graphs_.clear();
|
|
preferred_mask_.resize(cells);
|
|
for (std::size_t i = 0; i < cells; ++i)
|
|
preferred_mask_[i] = request.live.cost[i] == kPreferredSpace;
|
|
preferred_mask_empty_ = !live_has_preferred;
|
|
}
|
|
PlannerConfig config = config_.planner;
|
|
config.half_x_m = half_x;
|
|
config.half_y_m = half_y;
|
|
config.clearance_min_m = request.inscribed_radius_m + config_.clearance_min_margin_m;
|
|
config.clearance_hard_m = config.clearance_min_m;
|
|
config.clearance_preferred_m = request.inscribed_radius_m + config_.clearance_preferred_margin_m;
|
|
config.collision_check_distance_m = std::hypot(half_x, half_y) + config_.collision_check_margin_m;
|
|
if (field)
|
|
config.max_deviation_deg = field->maxDeviationRad() * 180.0 / kPi;
|
|
GridRef compile_grid = request.live;
|
|
compile_grid.cost = reference.static_cost.data();
|
|
compile_grid.clearance_mm = reference.clearance_mm.data();
|
|
compile_grid.direction = directions_.empty() ? nullptr : directions_.data();
|
|
GridRef live = request.live;
|
|
live.direction = compile_grid.direction;
|
|
live.clearance_mm = reference.clearance_mm.data();
|
|
RouteRequest route;
|
|
route.start = poseOf(request.start, request.start_has_yaw);
|
|
route.goal = poseOf(request.goal, request.goal_has_yaw);
|
|
route.cancel = request.cancel;
|
|
route.changed_boxes = changedBoxes(reference.static_cost.data(), live, request.cancel, &changed_cells_, &changed_stack_);
|
|
if (request.cancel && request.cancel->load(std::memory_order_relaxed))
|
|
{
|
|
failed.info.reason = "cancelled";
|
|
return failed;
|
|
}
|
|
if (!route.changed_boxes.empty())
|
|
{
|
|
const double radius = std::max({ 1.5, config.clearance_preferred_m, config.collision_check_distance_m,
|
|
config.clearance_hard_m, config.clearance_min_m });
|
|
patchClearance(reference.static_cost.data(), reference.clearance_mm.data(), live, radius, &live_clearance_, request.cancel);
|
|
if (request.cancel && request.cancel->load(std::memory_order_relaxed))
|
|
{
|
|
failed.info.reason = "cancelled";
|
|
return failed;
|
|
}
|
|
live.clearance_mm = live_clearance_.data();
|
|
}
|
|
const RidgeBackend backend = makeRidgeBackend(config, reference.params);
|
|
const GraphProvider provider = [&](double deviation) -> std::shared_ptr<const CompiledGraph>
|
|
{
|
|
auto it = graphs_.find(deviation);
|
|
if (it != graphs_.end())
|
|
return it->second;
|
|
auto graph = std::make_shared<const CompiledGraph>(
|
|
compileGraph(coarse_, compile_grid, live.cost, deviation, config, backend, request.cancel));
|
|
if (request.cancel && request.cancel->load(std::memory_order_relaxed))
|
|
return {};
|
|
graphs_.emplace(deviation, graph);
|
|
++compile_count_;
|
|
return graph;
|
|
};
|
|
PlanResult result = planRoute(provider, route, live, config, backend);
|
|
if (result.ok && !result.path.empty())
|
|
{
|
|
// The adapter outputs the exact goal pose. Verify that final adjustment as well, while
|
|
// keeping the original core path available to callers comparing against the eval tool.
|
|
const auto verify_begin = std::chrono::steady_clock::now();
|
|
Path exact = result.path;
|
|
exact.back().x = route.goal.x;
|
|
exact.back().y = route.goal.y;
|
|
if (route.goal.has_yaw)
|
|
exact.back().yaw = route.goal.yaw;
|
|
const PathCheck check = verifyPath(exact, live, result.info.rung_used_deg, config, request.cancel);
|
|
const bool valid = check.valid && endpointOk(exact, route.start, route.goal) &&
|
|
freeClearanceOk(exact, live, clearanceThresholdMm(config.clearance_min_m)) &&
|
|
!blockedEndpointTurn(exact, live, config.half_x_m, config.half_y_m) &&
|
|
checkFootprintGap(exact, live, config.footprint_min_gap_m, config.half_x_m,
|
|
config.half_y_m, request.cancel).valid;
|
|
const double verify_ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - verify_begin).count();
|
|
result.info.verify_ms += verify_ms;
|
|
result.info.query_ms += verify_ms;
|
|
if (!valid || (request.cancel && request.cancel->load(std::memory_order_relaxed)))
|
|
{
|
|
result.ok = false;
|
|
result.path.clear();
|
|
result.info.reason = request.cancel && request.cancel->load(std::memory_order_relaxed) ? "cancelled" : "exact_goal_invalid";
|
|
}
|
|
}
|
|
// A failed query is dumped only after the core ran on it, so the replay sees the same grid, zones and poses.
|
|
if (!result.ok && result.info.reason != "cancelled" && !config_.debug_dump_dir.empty() &&
|
|
dumps_attempted_ < config_.debug_dump_max_files)
|
|
{
|
|
++dumps_attempted_;
|
|
const std::time_t now = std::time(nullptr);
|
|
std::tm local{};
|
|
localtime_r(&now, &local);
|
|
std::ostringstream name;
|
|
name << "lane_route_" << std::put_time(&local, "%Y%m%d_%H%M%S") << '_' << dumps_attempted_;
|
|
const std::string stem = writeFailureDump(config_.debug_dump_dir, name.str(), live, reference.static_cost, directions_,
|
|
route, config, result);
|
|
last_dump_ = stem.empty() ? "!" + config_.debug_dump_dir : stem;
|
|
}
|
|
return result;
|
|
}
|
|
} // namespace lane_route_planner
|