feat(sbpl): plan only along allowed directions of the direction field

- DirectionalEnvironmentNAVXYTHETALAT overrides GetActionCost: after the
  base obstacle cost, it rejects an action when a cell crossed by the
  primitive's reference point has a direction code whose mask forbids
  that segment's displacement, or when the cell is outside the grid.
  Per-action (dx, dy, mask) tables are precomputed with the shared DDA.
- makePlan reads the direction snapshot once per call: PENDING or a
  geometry mismatch refuses to plan, a state or generation change forces
  planning from scratch, and the path is discarded if the field changed
  during the search. Environment init failure returns false instead of
  exit(1).
- The mask table records the deviation it was built with and is rebuilt
  when a ready field carries another max_deviation_deg; on failure the
  field is detached and planning is refused.

Full history: branch feature/direction-zone.
This commit is contained in:
2026-11-04 13:24:16 +07:00
parent c98a5acf44
commit f021a9ea59
8 changed files with 2245 additions and 11 deletions

View File

@@ -0,0 +1,124 @@
#include <sbpl_lattice_planner/directional_environment.h>
#include <cmath>
#include <map>
#include <utility>
#include <sbpl/utils/key.h>
namespace sbpl_lattice_planner
{
DirectionDecision decideDirection(const robot_costmap_2d::DirectionFieldSnapshot& snapshot,
bool have_previous, robot_costmap_2d::DirectionFieldState previous_state,
uint64_t previous_generation, const robot_costmap_2d::DirectionGeometry& grid)
{
using State = robot_costmap_2d::DirectionFieldState;
using Result = DirectionDecision::Result;
const bool changed = !have_previous || snapshot.state != previous_state || snapshot.generation != previous_generation;
if (snapshot.state == State::kDisabled)
return {Result::kDisabled, changed};
if (snapshot.state == State::kPending)
return {Result::kPending, changed};
if (snapshot.state != State::kReady || !snapshot.field)
return {Result::kGeometryMismatch, changed};
const auto& g = snapshot.field->geometry();
const auto equal = [](double a, double b)
{
return std::isfinite(a) && std::isfinite(b) && std::abs(a - b) <= 1e-6;
};
if (g.width != grid.width || g.height != grid.height || !equal(g.resolution, grid.resolution) ||
!equal(g.origin_x, grid.origin_x) || !equal(g.origin_y, grid.origin_y))
return {Result::kGeometryMismatch, changed};
return {Result::kReady, changed};
}
bool DirectionalEnvironmentNAVXYTHETALAT::buildDirectionTable(double max_deviation_rad)
{
std::vector<CellMask> cells;
std::vector<size_t> offsets;
const double resolution = EnvNAVXYTHETALATCfg.cellsize_m;
if (!std::isfinite(max_deviation_rad) || max_deviation_rad <= 0 || max_deviation_rad >= M_PI ||
!std::isfinite(resolution) || resolution <= 0 || !EnvNAVXYTHETALATCfg.ActionsV)
return false;
// Snap near boundaries before DDA: binary rounding must not create a spurious sliver cell.
const auto snap = [](double q)
{
const double n = std::round(q);
return std::abs(q - n) <= 1e-9 ? n : q;
};
for (int theta = 0; theta < thetaCount(); ++theta)
{
for (int a = 0; a < actionWidth(); ++a)
{
offsets.push_back(cells.size());
const auto& primitive = action(theta, a);
std::map<std::pair<int64_t, int64_t>, uint8_t> masks;
auto segment = [&](double x0, double y0, double x1, double y1)
{
const double dx = x1 - x0;
const double dy = y1 - y0;
if (dx == 0 && dy == 0)
return true;
const uint8_t mask = robot_costmap_2d::allowedDirectionMask(dx, dy, max_deviation_rad);
return robot_costmap_2d::traverseGridSegment(snap(0.5 + x0 / resolution), snap(0.5 + y0 / resolution),
snap(0.5 + x1 / resolution), snap(0.5 + y1 / resolution), [&](int64_t x, int64_t y)
{
auto result = masks.emplace(std::make_pair(x, y), mask);
if (!result.second)
result.first->second &= mask;
return true;
});
};
const auto& points = primitive.intermptV;
if (points.empty())
{
// SBPL's deprecated built-in primitives have no samples; their motion is a straight cell displacement.
if (!segment(0, 0, primitive.dX * resolution, primitive.dY * resolution))
return false;
}
else
{
for (size_t i = 1; i < points.size(); ++i)
if (!segment(points[i - 1].x, points[i - 1].y, points[i].x, points[i].y))
return false;
if (points.size() == 1 && (primitive.dX != 0 || primitive.dY != 0))
return false;
}
for (const auto& entry : masks)
cells.push_back({entry.first.first, entry.first.second, entry.second});
}
}
offsets.push_back(cells.size());
cells_.swap(cells);
offsets_.swap(offsets);
table_max_deviation_rad_ = max_deviation_rad;
return true;
}
int DirectionalEnvironmentNAVXYTHETALAT::GetActionCost(int source_x, int source_y, int source_theta,
EnvNAVXYTHETALATAction_t* primitive)
{
const int cost = EnvironmentNAVXYTHETALAT::GetActionCost(source_x, source_y, source_theta, primitive);
if (cost >= INFINITECOST || !field_)
return cost;
const int theta = static_cast<unsigned char>(primitive->starttheta);
const size_t index = static_cast<size_t>(theta) * actionWidth() + primitive->aind;
if (theta >= thetaCount() || primitive->aind >= actionWidth() || index + 1 >= offsets_.size())
{
++rejections_;
return INFINITECOST;
}
for (size_t i = offsets_[index]; i < offsets_[index + 1]; ++i)
{
const auto& cell = cells_[i];
uint8_t code = 0;
if (!field_->codeAt(static_cast<int64_t>(source_x) + cell.dx, static_cast<int64_t>(source_y) + cell.dy, &code) ||
(code != 0 && (code > 8 || !(cell.mask & (1u << (code - 1))))))
{
++rejections_;
return INFINITECOST;
}
}
return cost;
}
} // namespace sbpl_lattice_planner

View File

@@ -39,6 +39,7 @@
#include <algorithm>
#include <cmath>
#include <exception>
#include <string>
#include <cstdlib>
#include <dlfcn.h>
@@ -292,7 +293,7 @@ bool SBPLLatticePlanner::initialize(std::string name, robot_costmap_2d::Costmap2
if ("XYThetaLattice" == environment_type_){
robot::log_debug("Using a 3D costmap for theta lattice\n");
env_ = new EnvironmentNAVXYTHETALAT();
env_ = new DirectionalEnvironmentNAVXYTHETALAT();
}
else{
robot::log_error("XYThetaLattice is currently the only supported environment!\n");
@@ -356,7 +357,8 @@ bool SBPLLatticePlanner::initialize(std::string name, robot_costmap_2d::Costmap2
perimeterptsV, init_grid->getResolution(), nominalvel_mpersecs,
timetoturn45degsinplace_secs, obst_cost_thresh,
primitive_filename_.c_str());
ret = true;
if (ret) ret = env_->buildDirectionTable(M_PI / 2.0);
current_env_resolution_ = init_grid->getResolution();
current_env_width_ = init_grid->getSizeInCellsX();
current_env_height_ = init_grid->getSizeInCellsY();
// robot::log_warning("DEBUG 3000");
@@ -366,8 +368,10 @@ bool SBPLLatticePlanner::initialize(std::string name, robot_costmap_2d::Costmap2
ret = false;
}
if(!ret){
robot::log_error("SBPL initialization failed!");
exit(1);
robot::log_error("SBPL initialization or direction table construction failed!");
delete env_;
env_ = NULL;
return false;
}
for (ssize_t ix(0); ix < init_grid->getSizeInCellsX(); ++ix)
for (ssize_t iy(0); iy < init_grid->getSizeInCellsY(); ++iy)
@@ -485,8 +489,37 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start,
// inflation và frame vẫn thuộc costmap sống — lưới ngoài bắt buộc cùng kích thước với nó.
const robot_costmap_2d::Costmap2D* grid = activeGrid();
const auto direction_snapshot = costmap_robot_->getLayeredCostmap()->getDirectionFieldSnapshot();
const robot_costmap_2d::DirectionGeometry initial_geometry{grid->getSizeInCellsX(), grid->getSizeInCellsY(),
grid->getResolution(), grid->getOriginX(), grid->getOriginY(), costmap_robot_->getGlobalFrameID()};
const auto initial_decision = decideDirection(direction_snapshot, have_previous_direction_,
previous_direction_state_, previous_direction_generation_, initial_geometry);
if (initial_decision.result == DirectionDecision::Result::kPending) {
const auto now = std::chrono::steady_clock::now();
if (direction_pending_since_ == std::chrono::steady_clock::time_point{}) direction_pending_since_ = now;
if (last_direction_pending_log_ == std::chrono::steady_clock::time_point{} ||
now - last_direction_pending_log_ >= std::chrono::seconds(5)) {
const double waited = std::chrono::duration<double>(now - direction_pending_since_).count();
robot::log_error("[sbpl_lattice_planner] direction field is not ready (%.1f s); refusing to plan", waited);
last_direction_pending_log_ = now;
}
direction_scratch_pending_ = direction_scratch_pending_ || initial_decision.force_scratch;
have_previous_direction_ = true;
previous_direction_state_ = direction_snapshot.state;
previous_direction_generation_ = direction_snapshot.generation;
if (debug_plan_) robot::log_info("[sbpl_lattice_planner] direction state=PENDING generation=%llu rejected=0",
static_cast<unsigned long long>(direction_snapshot.generation));
return false;
}
direction_pending_since_ = {};
last_direction_pending_log_ = {};
bool do_init = false;
if (current_env_width_ != grid->getSizeInCellsX() ||
if (current_env_resolution_ != grid->getResolution()) {
robot::log_info("Costmap resolution has changed, reinitializing sbpl_lattice_planner.");
do_init = true;
}
else if (current_env_width_ != grid->getSizeInCellsX() ||
current_env_height_ != grid->getSizeInCellsY()) {
robot::log_info("Costmap dimensions have changed from (%d x %d) to (%d x %d), reinitializing sbpl_lattice_planner.",
current_env_width_, current_env_height_,
@@ -526,7 +559,69 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start,
grid = activeGrid();
}
// Re-init đọc cell từ activeGrid(): bản chụp nếu có, lưới sống nếu không (xem initialize()).
initialize(name_, costmap_robot_);
if (!initialize(name_, costmap_robot_)) return false;
}
// The snapshot owns the field through search, conversion and the optional realignment retry.
struct DirectionGuard {
DirectionalEnvironmentNAVXYTHETALAT* env;
const robot_costmap_2d::DirectionFieldSnapshot& snapshot;
bool debug;
~DirectionGuard() {
if (debug) {
const char* state = snapshot.state == robot_costmap_2d::DirectionFieldState::kReady ? "READY" :
snapshot.state == robot_costmap_2d::DirectionFieldState::kPending ? "PENDING" : "DISABLED";
robot::log_info("[sbpl_lattice_planner] direction state=%s generation=%llu rejected=%llu", state,
static_cast<unsigned long long>(snapshot.generation),
static_cast<unsigned long long>(env->directionRejections()));
}
env->setDirectionField(nullptr);
}
} guard{env_, direction_snapshot, debug_plan_};
env_->resetDirectionRejections();
const robot_costmap_2d::DirectionGeometry geometry{grid->getSizeInCellsX(), grid->getSizeInCellsY(),
grid->getResolution(), grid->getOriginX(), grid->getOriginY(), costmap_robot_->getGlobalFrameID()};
const auto decision = decideDirection(direction_snapshot, have_previous_direction_, previous_direction_state_,
previous_direction_generation_, geometry);
using DirectionResult = DirectionDecision::Result;
direction_scratch_pending_ = direction_scratch_pending_ || decision.force_scratch;
have_previous_direction_ = true;
previous_direction_state_ = direction_snapshot.state;
previous_direction_generation_ = direction_snapshot.generation;
if (decision.result == DirectionResult::kGeometryMismatch) {
const auto now = std::chrono::steady_clock::now();
if (last_direction_geometry_log_ == std::chrono::steady_clock::time_point{} ||
now - last_direction_geometry_log_ >= std::chrono::seconds(5)) {
robot::log_error("[sbpl_lattice_planner] direction field geometry does not match the active grid");
last_direction_geometry_log_ = now;
}
return false;
}
last_direction_geometry_log_ = {};
if (decision.result == DirectionResult::kReady &&
direction_snapshot.field->maxDeviationRad() != env_->tableMaxDeviationRad()) {
const double old_deviation = env_->tableMaxDeviationRad();
const double new_deviation = direction_snapshot.field->maxDeviationRad();
bool rebuilt = false;
try {
rebuilt = env_->buildDirectionTable(new_deviation);
} catch (const std::exception& e) {
robot::log_error("[sbpl_lattice_planner] direction table rebuild exception: %s", e.what());
}
if (!rebuilt) {
robot::log_error("[sbpl_lattice_planner] direction table rebuild failed; refusing to plan");
env_->setDirectionField(nullptr);
direction_scratch_pending_ = true;
return false;
}
robot::log_info("[sbpl_lattice_planner] direction table max deviation changed %.3f -> %.3f deg",
old_deviation * 180.0 / M_PI, new_deviation * 180.0 / M_PI);
direction_scratch_pending_ = true;
}
env_->setDirectionField(decision.result == DirectionResult::kReady ? direction_snapshot.field.get() : nullptr);
if (direction_scratch_pending_) {
planner_->force_planning_from_scratch();
direction_scratch_pending_ = false;
}
plan.clear();
@@ -980,6 +1075,20 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start,
// plan_pub_.publish(gui_path);
// publishStats(solution_cost, sbpl_path.size(), start, goal);
// The search and realignment use one immutable snapshot. Refuse to hand off a path
// for an older map or field when the provider changed while planning.
const auto handoff_snapshot = costmap_robot_->getLayeredCostmap()->getDirectionFieldSnapshot();
const bool both_disabled = direction_snapshot.state == robot_costmap_2d::DirectionFieldState::kDisabled &&
handoff_snapshot.state == robot_costmap_2d::DirectionFieldState::kDisabled;
if (!both_disabled && (direction_snapshot.state != handoff_snapshot.state ||
direction_snapshot.generation != handoff_snapshot.generation)) {
plan.clear();
robot::log_warning("[sbpl_lattice_planner] direction field changed during planning "
"(generation %llu -> %llu); discarding path",
static_cast<unsigned long long>(direction_snapshot.generation),
static_cast<unsigned long long>(handoff_snapshot.generation));
return false;
}
return true;
}