Files
costmap_2d/src/reference_graph.cpp
duongtd 5034029c6e feat(costmap_2d): background reference graph, shared keys under root:
- ReferenceGraph / ReferenceGraphWorker: Voronoi ridges and one-way lanes are
  computed on a low-priority thread when the map changes (reference_graph_*
  keys, off with rolling_window), with unit tests.
- Shared costmap keys can live in a root: map or flat at the top of the YAML;
  costmap_common_root_test covers both layouts.
- Static and directional layers report map changes to the layered costmap.
2026-11-10 16:37:55 +07:00

980 lines
38 KiB
C++

#include <robot_costmap_2d/reference_graph.h>
#include <algorithm>
#include <cmath>
#include <cstddef>
#include <limits>
#include <set>
#include <sstream>
#include <stdexcept>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <robot_costmap_2d/cost_values.h>
namespace robot_costmap_2d
{
namespace
{
// Lane scan constants of the prototype. They are geometry of the search, not robot tuning, so they
// stay out of YAML. A direction grid finer than 5 cm would need a smaller sample step.
constexpr double kLaneScanStepM = 0.1;
constexpr double kLaneSampleStepM = 0.05;
constexpr double kLaneMatchToleranceM = 0.12;
constexpr double kLaneMinLengthM = 0.3;
constexpr double kLaneSameEntryM = 0.02;
constexpr int kMaxSpurRounds = 20;
constexpr int kKeepEveryCells = 5; // 0.25 m at 5 cm, enough for the route search.
constexpr double kPi = 3.141592653589793;
constexpr uint16_t kMaxClearanceMm = 65535;
bool cancelled(const std::atomic<bool>* cancel)
{
return cancel != nullptr && cancel->load(std::memory_order_relaxed);
}
void checkGeometry(const DirectionGeometry& geometry)
{
if (geometry.width == 0 || geometry.height == 0 || !std::isfinite(geometry.resolution) || geometry.resolution <= 0.0 ||
!std::isfinite(geometry.origin_x) || !std::isfinite(geometry.origin_y))
throw std::invalid_argument("reference_graph: invalid grid geometry");
// Cell indices are int32_t in this file, with a one-cell padding on each side.
const uint64_t padded = (static_cast<uint64_t>(geometry.width) + 2) * (static_cast<uint64_t>(geometry.height) + 2);
if (padded > static_cast<uint64_t>(std::numeric_limits<int32_t>::max()))
throw std::invalid_argument("reference_graph: grid too large");
}
void checkParams(const ReferenceGraphParams& params)
{
const std::string error = validateReferenceGraphParams(params);
if (!error.empty())
throw std::invalid_argument("reference_graph: " + error);
}
/** Binary grid with a one-cell empty border, so neighbour lookups need no bounds checks. */
class PaddedMask
{
public:
PaddedMask(int32_t width, int32_t height)
: width_(width), height_(height), stride_(width + 2),
cells_(static_cast<std::size_t>(width + 2) * static_cast<std::size_t>(height + 2), 0)
{
}
int32_t index(int32_t x, int32_t y) const { return (y + 1) * stride_ + x + 1; }
int32_t x(int32_t padded) const { return padded % stride_ - 1; }
int32_t y(int32_t padded) const { return padded / stride_ - 1; }
int32_t stride() const { return stride_; }
int32_t width() const { return width_; }
int32_t height() const { return height_; }
std::size_t size() const { return cells_.size(); }
uint8_t& operator[](int32_t padded) { return cells_[static_cast<std::size_t>(padded)]; }
uint8_t operator[](int32_t padded) const { return cells_[static_cast<std::size_t>(padded)]; }
private:
int32_t width_, height_, stride_;
std::vector<uint8_t> cells_;
};
/** Skeleton neighbours. A diagonal step is skipped when a 4-connected path already links the two cells. */
int skeletonNeighbours(const PaddedMask& mask, int32_t cell, int32_t out[8])
{
const int32_t stride = mask.stride();
int count = 0;
for (int dy = -1; dy <= 1; ++dy)
{
for (int dx = -1; dx <= 1; ++dx)
{
if (dx == 0 && dy == 0)
continue;
const int32_t other = cell + dy * stride + dx;
if (mask[other] == 0)
continue;
if (dx != 0 && dy != 0 && (mask[cell + dx] != 0 || mask[cell + dy * stride] != 0))
continue;
out[count++] = other;
}
}
return count;
}
/** Nearest feature cell per grid cell, as row-major index, -1 when the grid has no feature.
*
* Same tie-breaking as scipy.ndimage.distance_transform_edt, which the ridge test is sensitive to:
* the lower row wins in the column pass, the lower column in the row pass.
* @return False when cancelled. */
template <typename IsFeature>
bool nearestFeature(int32_t width, int32_t height, IsFeature is_feature, std::vector<int32_t>* nearest,
const std::atomic<bool>* cancel)
{
nearest->assign(static_cast<std::size_t>(width) * static_cast<std::size_t>(height), -1);
std::vector<int32_t>& result = *nearest;
// Column pass, walked row by row to stay cache friendly on a 3000 x 3000 grid. Holds the feature row.
std::vector<int32_t> column_feature(static_cast<std::size_t>(width), -1);
for (int32_t y = 0; y < height; ++y)
{
if (cancelled(cancel))
return false;
int32_t* row = result.data() + static_cast<std::ptrdiff_t>(y) * width;
for (int32_t x = 0; x < width; ++x)
{
if (is_feature(y * width + x))
column_feature[static_cast<std::size_t>(x)] = y;
row[x] = column_feature[static_cast<std::size_t>(x)];
}
}
std::fill(column_feature.begin(), column_feature.end(), -1);
for (int32_t y = height - 1; y >= 0; --y)
{
int32_t* row = result.data() + static_cast<std::ptrdiff_t>(y) * width;
for (int32_t x = 0; x < width; ++x)
{
if (is_feature(y * width + x))
column_feature[static_cast<std::size_t>(x)] = y;
const int32_t below = column_feature[static_cast<std::size_t>(x)];
if (below >= 0 && (row[x] < 0 || below - y < y - row[x]))
row[x] = below;
}
}
// Row pass: lower envelope of the column results, as in Maurer's linear-time transform.
std::vector<int32_t> feature_row(static_cast<std::size_t>(width));
std::vector<int32_t> envelope(static_cast<std::size_t>(width));
for (int32_t y = 0; y < height; ++y)
{
if (cancelled(cancel))
return false;
int32_t* row = result.data() + static_cast<std::ptrdiff_t>(y) * width;
std::copy(row, row + width, feature_row.begin());
const auto squared_row = [&](int32_t x) {
const double dy = feature_row[static_cast<std::size_t>(x)] - y;
return dy * dy;
};
int32_t last = -1;
for (int32_t x = 0; x < width; ++x)
{
if (feature_row[static_cast<std::size_t>(x)] < 0)
continue;
const double new_row = squared_row(x);
while (last >= 1)
{
const int32_t middle = envelope[static_cast<std::size_t>(last)];
const int32_t before = envelope[static_cast<std::size_t>(last - 1)];
const double a = middle - before;
const double b = x - middle;
const double c = a + b;
if (c * squared_row(middle) - b * squared_row(before) - a * new_row - a * b * c <= 0.0)
break;
--last;
}
envelope[static_cast<std::size_t>(++last)] = x;
}
if (last < 0)
continue;
int32_t current = 0;
for (int32_t x = 0; x < width; ++x)
{
const auto squared_distance = [&](int32_t slot) {
const int32_t column = envelope[static_cast<std::size_t>(slot)];
const double dx = column - x;
return squared_row(column) + dx * dx;
};
double best = squared_distance(current);
while (current < last)
{
const double next = squared_distance(current + 1);
if (best <= next)
break;
best = next;
++current;
}
const int32_t column = envelope[static_cast<std::size_t>(current)];
row[x] = feature_row[static_cast<std::size_t>(column)] * width + column;
}
}
return true;
}
/** Zhang-Suen thinning. Only ridge cells are visited, so the cost follows the ridge size and not the map size.
* A cell is re-tested in a phase only after a neighbour changed, since the test depends on nothing else.
* @return False when cancelled. */
bool thinSkeleton(PaddedMask* mask_ptr, std::vector<int32_t>* active, const std::atomic<bool>* cancel)
{
PaddedMask& mask = *mask_ptr;
const int32_t stride = mask.stride();
const int32_t offsets[8] = { -stride, -stride + 1, 1, stride + 1, stride, stride - 1, -1, -stride - 1 };
std::vector<uint8_t> pending(mask.size(), 0);
for (int32_t cell : *active)
pending[static_cast<std::size_t>(cell)] = 3;
std::vector<int32_t> removal;
while (true)
{
if (cancelled(cancel))
return false;
bool changed = false;
for (int phase = 0; phase < 2; ++phase)
{
const uint8_t bit = static_cast<uint8_t>(1U << phase);
removal.clear();
for (int32_t cell : *active)
{
uint8_t& flags = pending[static_cast<std::size_t>(cell)];
if ((flags & bit) == 0 || mask[cell] == 0)
continue;
flags = static_cast<uint8_t>(flags & ~bit);
const uint8_t n = mask[cell + offsets[0]], ne = mask[cell + offsets[1]], e = mask[cell + offsets[2]],
se = mask[cell + offsets[3]], s = mask[cell + offsets[4]], sw = mask[cell + offsets[5]],
w = mask[cell + offsets[6]], nw = mask[cell + offsets[7]];
const int count = n + ne + e + se + s + sw + w + nw;
if (count < 2 || count > 6)
continue;
const uint8_t sequence[9] = { n, ne, e, se, s, sw, w, nw, n };
int transitions = 0;
for (int i = 0; i < 8; ++i)
transitions += (sequence[i] == 0 && sequence[i + 1] != 0) ? 1 : 0;
if (transitions != 1)
continue;
const bool extra = phase == 0 ? ((n == 0 || e == 0 || s == 0) && (e == 0 || s == 0 || w == 0)) :
((n == 0 || e == 0 || w == 0) && (n == 0 || s == 0 || w == 0));
if (extra)
removal.push_back(cell);
}
for (int32_t cell : removal)
{
mask[cell] = 0;
for (int32_t offset : offsets)
pending[static_cast<std::size_t>(cell + offset)] = 3;
}
changed = changed || !removal.empty();
}
active->erase(std::remove_if(active->begin(), active->end(), [&](int32_t cell) { return mask[cell] == 0; }),
active->end());
if (!changed)
return true;
}
}
/** Remove terminal branches shorter than `minimum` [m] that end on a junction. An isolated line stays.
* @return False when cancelled. */
bool pruneSpurs(PaddedMask* mask_ptr, std::vector<int32_t>* pixels, double resolution, double minimum,
const std::atomic<bool>* cancel)
{
PaddedMask& mask = *mask_ptr;
const int32_t stride = mask.stride();
const double diagonal = std::hypot(1.0, 1.0);
std::vector<int32_t> path;
std::vector<int32_t> doomed;
for (int round = 0; round < kMaxSpurRounds; ++round)
{
if (cancelled(cancel))
return false;
doomed.clear();
int32_t around[8];
for (int32_t start : *pixels)
{
if (skeletonNeighbours(mask, start, around) != 1)
continue;
path.assign(1, start);
int32_t previous = -1;
int32_t current = start;
double length = 0.0;
int degree = 1;
while (true)
{
int32_t next = -1;
int others = 0;
degree = skeletonNeighbours(mask, current, around);
for (int i = 0; i < degree; ++i)
{
if (around[i] != previous)
{
next = around[i];
++others;
}
}
if (others != 1)
break;
const int32_t step = next - current;
const bool straight = step == 1 || step == -1 || step == stride || step == -stride;
length += resolution * (straight ? 1.0 : diagonal);
previous = current;
current = next;
degree = skeletonNeighbours(mask, current, around);
if (degree != 2)
break;
path.push_back(current);
if (length >= minimum)
break;
}
if (length < minimum && degree > 2)
doomed.insert(doomed.end(), path.begin(), path.end());
}
if (doomed.empty())
break;
for (int32_t cell : doomed)
mask[cell] = 0;
pixels->erase(std::remove_if(pixels->begin(), pixels->end(), [&](int32_t cell) { return mask[cell] == 0; }),
pixels->end());
}
return true;
}
uint64_t linkKey(int32_t a, int32_t b)
{
const uint32_t low = static_cast<uint32_t>(std::min(a, b));
const uint32_t high = static_cast<uint32_t>(std::max(a, b));
return (static_cast<uint64_t>(high) << 32) | low;
}
/** Rectangle against lethal and unknown cell squares, separating-axis test. Centre cell must also be free. */
bool footprintFree(const uint8_t* cost, const DirectionGeometry& geometry, double x, double y, double c, double s,
double half_x, double half_y)
{
const double resolution = geometry.resolution;
const double abs_c = std::abs(c);
const double abs_s = std::abs(s);
const double reach_x = half_x * abs_c + half_y * abs_s;
const double reach_y = half_x * abs_s + half_y * abs_c;
const double x0 = std::floor((x - reach_x - geometry.origin_x) / resolution);
const double x1 = std::floor((x + reach_x - geometry.origin_x) / resolution);
const double y0 = std::floor((y - reach_y - geometry.origin_y) / resolution);
const double y1 = std::floor((y + reach_y - geometry.origin_y) / resolution);
if (x0 < 0.0 || y0 < 0.0 || x1 >= geometry.width || y1 >= geometry.height)
return false;
const int32_t width = static_cast<int32_t>(geometry.width);
const int32_t centre_x = static_cast<int32_t>(std::floor((x - geometry.origin_x) / resolution));
const int32_t centre_y = static_cast<int32_t>(std::floor((y - geometry.origin_y) / resolution));
if (cost[centre_y * width + centre_x] >= INSCRIBED_INFLATED_OBSTACLE)
return false;
const double half_cell = resolution / 2.0;
const double projected = half_cell * (abs_c + abs_s);
for (int32_t iy = static_cast<int32_t>(y0); iy <= static_cast<int32_t>(y1); ++iy)
{
const uint8_t* row = cost + static_cast<std::ptrdiff_t>(iy) * width;
for (int32_t ix = static_cast<int32_t>(x0); ix <= static_cast<int32_t>(x1); ++ix)
{
if (row[ix] != LETHAL_OBSTACLE && row[ix] != NO_INFORMATION)
continue;
const double dx = geometry.origin_x + (ix + 0.5) * resolution - x;
const double dy = geometry.origin_y + (iy + 0.5) * resolution - y;
if (std::abs(dx) <= reach_x + half_cell && std::abs(dy) <= reach_y + half_cell &&
std::abs(c * dx + s * dy) <= half_x + projected && std::abs(-s * dx + c * dy) <= half_y + projected)
return false;
}
}
return true;
}
struct LaneCandidate
{
ReferencePoint entry, exit;
double lateral;
double length;
};
struct ZoneRegion
{
uint8_t direction_index;
int32_t label;
std::vector<int32_t> cells;
};
/** 8-connected regions of equal nonzero code, ordered by direction, then by first cell in raster order. */
std::vector<ZoneRegion> findZoneRegions(const uint8_t* codes, int32_t width, int32_t height, std::vector<int32_t>* labels)
{
labels->assign(static_cast<std::size_t>(width) * static_cast<std::size_t>(height), 0);
std::vector<ZoneRegion> regions;
std::vector<int32_t> stack;
int32_t next_label = 0;
for (int32_t y = 0; y < height; ++y)
{
for (int32_t x = 0; x < width; ++x)
{
const int32_t seed = y * width + x;
const uint8_t code = codes[seed];
if (code == 0 || code > 8 || (*labels)[static_cast<std::size_t>(seed)] != 0)
continue;
ZoneRegion region;
region.direction_index = static_cast<uint8_t>(code - 1);
region.label = ++next_label;
(*labels)[static_cast<std::size_t>(seed)] = region.label;
stack.assign(1, seed);
while (!stack.empty())
{
const int32_t cell = stack.back();
stack.pop_back();
region.cells.push_back(cell);
const int32_t cx = cell % width;
const int32_t cy = cell / width;
for (int32_t ny = std::max(cy - 1, 0); ny <= std::min(cy + 1, height - 1); ++ny)
{
for (int32_t nx = std::max(cx - 1, 0); nx <= std::min(cx + 1, width - 1); ++nx)
{
const int32_t other = ny * width + nx;
if (codes[other] == code && (*labels)[static_cast<std::size_t>(other)] == 0)
{
(*labels)[static_cast<std::size_t>(other)] = region.label;
stack.push_back(other);
}
}
}
}
regions.push_back(std::move(region));
}
}
std::stable_sort(regions.begin(), regions.end(), [](const ZoneRegion& a, const ZoneRegion& b) {
return a.direction_index < b.direction_index;
});
return regions;
}
/** Candidate lanes of one region: free stretches along the zone direction, at each lateral offset.
* Fills `preferred_lateral` with the main lane's offset. */
std::vector<LaneCandidate> compileRegionLanes(const ZoneRegion& region, const std::vector<int32_t>& labels,
const uint8_t* cost, const DirectionGeometry& geometry, double half_x,
double half_y, double offset_step, double* preferred_lateral)
{
const int32_t width = static_cast<int32_t>(geometry.width);
const int32_t height = static_cast<int32_t>(geometry.height);
const double resolution = geometry.resolution;
const double yaw = region.direction_index * kPi / 4.0;
const double c = std::cos(yaw);
const double s = std::sin(yaw);
double lateral_min = std::numeric_limits<double>::infinity();
double lateral_max = -lateral_min;
double along_min = lateral_min;
double along_max = -lateral_min;
for (int32_t cell : region.cells)
{
const double x = geometry.origin_x + (cell % width + 0.5) * resolution;
const double y = geometry.origin_y + (cell / width + 0.5) * resolution;
const double along = x * c + y * s;
const double lateral = -x * s + y * c;
along_min = std::min(along_min, along);
along_max = std::max(along_max, along);
lateral_min = std::min(lateral_min, lateral);
lateral_max = std::max(lateral_max, lateral);
}
const double pad = resolution * 0.5 * (std::abs(c) + std::abs(s));
const double lo = lateral_min - pad;
const double hi = lateral_max + pad;
const double along_lo = along_min - pad;
const double along_hi = along_max + pad;
const double middle = (lo + hi) / 2.0;
const double section = (along_lo + along_hi) / 2.0;
const auto usable = [&](double t, double v) {
const double wx = t * c - v * s;
const double wy = t * s + v * c;
const double fx = std::floor((wx - geometry.origin_x) / resolution);
const double fy = std::floor((wy - geometry.origin_y) / resolution);
if (fx < 0.0 || fy < 0.0 || fx >= width || fy >= height)
return false;
const int32_t cell = static_cast<int32_t>(fy) * width + static_cast<int32_t>(fx);
return labels[static_cast<std::size_t>(cell)] == region.label &&
footprintFree(cost, geometry, wx, wy, c, s, half_x, half_y);
};
// Offsets across the mid section, spaced like numpy.arange so the values match the prototype.
std::vector<double> scan;
const double scan_start = lo + kLaneScanStepM / 2.0;
const double scan_delta = (scan_start + kLaneScanStepM) - scan_start;
const double scan_count = std::ceil((hi - scan_start) / kLaneScanStepM);
for (int64_t i = 0; i < static_cast<int64_t>(scan_count); ++i)
scan.push_back(i == 1 ? scan_start + kLaneScanStepM : scan_start + static_cast<double>(i) * scan_delta);
std::vector<std::pair<double, double>> spans;
int64_t begin = -1;
for (std::size_t i = 0; i <= scan.size(); ++i)
{
const bool free = i < scan.size() && usable(section, scan[i]);
if (free && begin < 0)
{
begin = static_cast<int64_t>(i);
}
else if (!free && begin >= 0)
{
spans.emplace_back(scan[static_cast<std::size_t>(begin)], scan[i - 1]);
begin = -1;
}
}
// The zone centre may be blocked. The main lane then moves to the free span closest to the centre.
double preferred = middle;
bool centre_free = spans.empty();
for (const auto& span : spans)
centre_free = centre_free || (span.first - kLaneScanStepM / 2.0 <= middle && middle <= span.second + kLaneScanStepM / 2.0);
if (!centre_free)
{
double best = std::numeric_limits<double>::infinity();
for (const auto& span : spans)
{
const double distance = std::abs((span.first + span.second) / 2.0 - middle);
if (distance < best)
{
best = distance;
preferred = (span.first + span.second) / 2.0;
}
}
}
*preferred_lateral = preferred;
std::set<double> offsets{ middle, preferred };
for (int64_t k = 1; preferred - k * offset_step > lo || preferred + k * offset_step < hi; ++k)
{
if (preferred - k * offset_step > lo)
offsets.insert(preferred - k * offset_step);
if (preferred + k * offset_step < hi)
offsets.insert(preferred + k * offset_step);
}
offsets.insert(scan.begin(), scan.end());
// numpy.linspace layout: the last sample is exactly along_hi.
const int64_t samples =
std::max<int64_t>(2, static_cast<int64_t>(std::ceil((along_hi - along_lo) / kLaneSampleStepM)) + 1);
const double sample_delta = (along_hi - along_lo) / static_cast<double>(samples - 1);
const auto sample = [&](int64_t i) {
return i == samples - 1 ? along_hi : static_cast<double>(i) * sample_delta + along_lo;
};
std::vector<LaneCandidate> lanes;
for (double v : offsets)
{
int64_t start = -1;
for (int64_t i = 0; i <= samples; ++i)
{
const bool free = i < samples && usable(sample(i), v);
if (free && start < 0)
{
start = i;
}
else if (!free && start >= 0)
{
const int64_t end = i - 1;
if (end > start)
{
const double t0 = sample(start);
const double t1 = sample(end);
LaneCandidate lane;
lane.entry = { t0 * c - v * s, t0 * s + v * c };
lane.exit = { t1 * c - v * s, t1 * s + v * c };
lane.lateral = v;
lane.length = t1 - t0;
lanes.push_back(lane);
}
start = -1;
}
}
}
return lanes;
}
/** Keep the main lane and up to two lanes on each side. */
void selectLanes(const ZoneRegion& region, uint32_t zone_id, const std::vector<LaneCandidate>& lanes, double middle,
double offset_step, std::vector<ReferenceLane>* out)
{
if (lanes.empty())
return;
const std::size_t first_of_zone = out->size();
const double targets[5] = { 0.0, -offset_step, offset_step, -2.0 * offset_step, 2.0 * offset_step };
for (double target : targets)
{
const LaneCandidate* chosen = nullptr;
double best_distance = std::numeric_limits<double>::infinity();
for (const LaneCandidate& lane : lanes)
{
const double distance = std::abs(lane.lateral - (middle + target));
if (chosen == nullptr || distance < best_distance || (distance == best_distance && lane.length > chosen->length))
{
chosen = &lane;
best_distance = distance;
}
}
if (best_distance > kLaneMatchToleranceM || chosen->length < kLaneMinLengthM)
continue;
bool duplicate = false;
for (std::size_t i = first_of_zone; i < out->size(); ++i)
{
const ReferencePoint& entry = (*out)[i].entry;
duplicate = duplicate || std::hypot(chosen->entry.x - entry.x, chosen->entry.y - entry.y) < kLaneSameEntryM;
}
if (duplicate)
continue;
ReferenceLane lane;
lane.zone_id = zone_id;
lane.direction_index = region.direction_index;
lane.entry = chosen->entry;
lane.exit = chosen->exit;
lane.length_m = chosen->length;
lane.offset_from_centre_m = std::abs(chosen->lateral - middle);
out->push_back(lane);
}
}
} // namespace
std::string validateReferenceGraphParams(const ReferenceGraphParams& params)
{
std::ostringstream error;
if (!std::isfinite(params.min_clearance_m) || params.min_clearance_m < 0.0)
error << "min_clearance_m must be finite and >= 0, got " << params.min_clearance_m;
else if (!std::isfinite(params.ridge_min_separation_m) || params.ridge_min_separation_m <= 0.0)
error << "ridge_min_separation_m must be finite and > 0, got " << params.ridge_min_separation_m;
else if (!std::isfinite(params.spur_min_length_m) || params.spur_min_length_m < 0.0)
error << "spur_min_length_m must be finite and >= 0, got " << params.spur_min_length_m;
else if (!std::isfinite(params.lane_offset_step_m) || params.lane_offset_step_m <= 0.0)
error << "lane_offset_step_m must be finite and > 0, got " << params.lane_offset_step_m;
return error.str();
}
VoronoiSkeleton computeVoronoiSkeleton(const ReferenceGridView& grid, const ReferenceGraphParams& params,
const std::atomic<bool>* cancel)
{
checkParams(params);
checkGeometry(grid.geometry);
if (grid.cost == nullptr)
throw std::invalid_argument("reference_graph: null cost grid");
const int32_t width = static_cast<int32_t>(grid.geometry.width);
const int32_t height = static_cast<int32_t>(grid.geometry.height);
const double resolution = grid.geometry.resolution;
const std::size_t cell_count = static_cast<std::size_t>(width) * static_cast<std::size_t>(height);
const uint8_t* cost = grid.cost;
VoronoiSkeleton result;
result.geometry = grid.geometry;
std::vector<int32_t> nearest;
if (!nearestFeature(width, height, [cost](int32_t cell) { return cost[cell] == LETHAL_OBSTACLE; }, &nearest, cancel))
return result;
std::vector<uint16_t> clearance_mm(cell_count, kMaxClearanceMm);
// A supplied clearance is already rounded down to millimetres, so it is compared in millimetres.
const int64_t supplied_threshold_mm = static_cast<int64_t>(std::ceil(params.min_clearance_m * 1000.0 - 1e-9));
PaddedMask mask(width, height);
std::vector<int32_t> ridge_cells;
for (int32_t y = 0; y < height; ++y)
{
if (cancelled(cancel))
return result;
for (int32_t x = 0; x < width; ++x)
{
const int32_t cell = y * width + x;
const int32_t feature = nearest[static_cast<std::size_t>(cell)];
bool clear_enough = feature >= 0;
if (grid.clearance_mm != nullptr)
{
clearance_mm[static_cast<std::size_t>(cell)] = grid.clearance_mm[cell];
clear_enough = clear_enough && grid.clearance_mm[cell] >= supplied_threshold_mm;
}
else if (feature >= 0)
{
const double dy = feature / width - y;
const double dx = feature % width - x;
const double metres = std::sqrt(dy * dy + dx * dx) * resolution;
clearance_mm[static_cast<std::size_t>(cell)] =
static_cast<uint16_t>(std::min(std::floor(metres * 1000.0), static_cast<double>(kMaxClearanceMm)));
clear_enough = metres >= params.min_clearance_m;
}
if (!clear_enough || cost[cell] >= INSCRIBED_INFLATED_OBSTACLE)
continue;
// A ridge cell has a neighbour whose nearest obstacle lies far from its own.
const auto separated = [&](int32_t other) {
const int32_t other_feature = nearest[static_cast<std::size_t>(other)];
if (other_feature == feature)
return false;
const double fy = feature / width - other_feature / width;
const double fx = feature % width - other_feature % width;
return std::hypot(fy, fx) * resolution >= params.ridge_min_separation_m;
};
if ((x + 1 < width && separated(cell + 1)) || (y + 1 < height && separated(cell + width)))
{
const int32_t padded = mask.index(x, y);
mask[padded] = 1;
ridge_cells.push_back(padded);
}
}
}
std::vector<int32_t>().swap(nearest);
if (!thinSkeleton(&mask, &ridge_cells, cancel) ||
!pruneSpurs(&mask, &ridge_cells, resolution, params.spur_min_length_m, cancel))
return result;
result.mask.assign(cell_count, 0);
for (int32_t padded : ridge_cells)
result.mask[static_cast<std::size_t>(mask.y(padded)) * static_cast<std::size_t>(width) + static_cast<std::size_t>(mask.x(padded))] = 1;
result.clearance_mm = std::move(clearance_mm);
return result;
}
std::vector<uint8_t> computeRegionCentreLine(const std::vector<uint8_t>& region_mask, const DirectionGeometry& geometry,
const ReferenceGraphParams& params)
{
checkParams(params);
checkGeometry(geometry);
const int32_t width = static_cast<int32_t>(geometry.width);
const int32_t height = static_cast<int32_t>(geometry.height);
if (region_mask.size() != static_cast<std::size_t>(width) * static_cast<std::size_t>(height))
throw std::invalid_argument("reference_graph: region mask size does not match the geometry");
std::vector<uint8_t> result(region_mask.size(), 0);
int32_t x_min = width, x_max = -1, y_min = height, y_max = -1;
for (int32_t y = 0; y < height; ++y)
{
for (int32_t x = 0; x < width; ++x)
{
if (region_mask[static_cast<std::size_t>(y * width + x)] == 0)
continue;
x_min = std::min(x_min, x);
x_max = std::max(x_max, x);
y_min = std::min(y_min, y);
y_max = std::max(y_max, y);
}
}
if (x_max < 0)
return result;
// Two cells of margin so the region always has an outside to measure from.
const int32_t crop_x = std::max(0, x_min - 2);
const int32_t crop_y = std::max(0, y_min - 2);
const int32_t crop_width = std::min(width, x_max + 3) - crop_x;
const int32_t crop_height = std::min(height, y_max + 3) - crop_y;
std::vector<uint8_t> crop(static_cast<std::size_t>(crop_width) * static_cast<std::size_t>(crop_height), 0);
for (int32_t y = 0; y < crop_height; ++y)
for (int32_t x = 0; x < crop_width; ++x)
crop[static_cast<std::size_t>(y * crop_width + x)] =
region_mask[static_cast<std::size_t>((y + crop_y) * width + x + crop_x)] != 0 ? 1 : 0;
std::vector<int32_t> nearest;
nearestFeature(crop_width, crop_height, [&crop](int32_t cell) { return crop[static_cast<std::size_t>(cell)] == 0; },
&nearest, nullptr);
// Two cells apart is the narrowest pair of boundary points that still has a centre.
PaddedMask mask(crop_width, crop_height);
std::vector<int32_t> cells;
for (int32_t y = 0; y < crop_height; ++y)
{
for (int32_t x = 0; x < crop_width; ++x)
{
const int32_t cell = y * crop_width + x;
if (crop[static_cast<std::size_t>(cell)] == 0)
continue;
const int32_t feature = nearest[static_cast<std::size_t>(cell)];
const auto separated = [&](int32_t other) {
const int32_t other_feature = nearest[static_cast<std::size_t>(other)];
const double fy = feature / crop_width - other_feature / crop_width;
const double fx = feature % crop_width - other_feature % crop_width;
return std::hypot(fy, fx) >= 2.0;
};
if (feature >= 0 && ((x + 1 < crop_width && separated(cell + 1)) || (y + 1 < crop_height && separated(cell + crop_width))))
{
const int32_t padded = mask.index(x, y);
mask[padded] = 1;
cells.push_back(padded);
}
}
}
thinSkeleton(&mask, &cells, nullptr);
pruneSpurs(&mask, &cells, geometry.resolution, params.spur_min_length_m, nullptr);
for (int32_t padded : cells)
result[static_cast<std::size_t>((mask.y(padded) + crop_y) * width + mask.x(padded) + crop_x)] = 1;
return result;
}
void extractVoronoiEdges(const std::vector<uint8_t>& skeleton_mask, const uint8_t* direction_codes,
const DirectionGeometry& geometry, const std::vector<uint16_t>* clearance_mm,
std::vector<ReferencePoint>* nodes, std::vector<VoronoiEdge>* edges,
const std::atomic<bool>* cancel)
{
checkGeometry(geometry);
if (nodes == nullptr || edges == nullptr)
throw std::invalid_argument("reference_graph: null output");
const int32_t width = static_cast<int32_t>(geometry.width);
const int32_t height = static_cast<int32_t>(geometry.height);
const std::size_t cell_count = static_cast<std::size_t>(width) * static_cast<std::size_t>(height);
if (skeleton_mask.size() != cell_count || (clearance_mm != nullptr && clearance_mm->size() != cell_count))
throw std::invalid_argument("reference_graph: skeleton size does not match the geometry");
nodes->clear();
edges->clear();
PaddedMask mask(width, height);
std::vector<int32_t> pixels;
for (int32_t y = 0; y < height; ++y)
{
for (int32_t x = 0; x < width; ++x)
{
if (skeleton_mask[static_cast<std::size_t>(y * width + x)] != 0)
{
const int32_t padded = mask.index(x, y);
mask[padded] = 1;
pixels.push_back(padded);
}
}
}
const auto code_at = [&](int32_t padded) -> uint8_t {
return direction_codes == nullptr ? 0 : direction_codes[mask.y(padded) * width + mask.x(padded)];
};
// Node cells: anything but a plain chain link, and both sides of a zone boundary.
PaddedMask critical(width, height);
std::vector<int32_t> critical_cells;
int32_t around[8];
for (int32_t cell : pixels)
{
const int degree = skeletonNeighbours(mask, cell, around);
bool is_critical = degree != 2;
for (int i = 0; i < degree && !is_critical; ++i)
is_critical = code_at(cell) != code_at(around[i]);
if (is_critical)
{
critical[cell] = 1;
critical_cells.push_back(cell);
}
}
const auto world = [&](int32_t padded) -> ReferencePoint {
return { geometry.origin_x + (mask.x(padded) + 0.5) * geometry.resolution,
geometry.origin_y + (mask.y(padded) + 0.5) * geometry.resolution };
};
std::unordered_map<int32_t, uint32_t> node_of;
const auto node_index = [&](int32_t padded) {
const auto inserted = node_of.emplace(padded, static_cast<uint32_t>(nodes->size()));
if (inserted.second)
nodes->push_back(world(padded));
return inserted.first->second;
};
std::unordered_set<uint64_t> visited;
visited.reserve(pixels.size() * 2);
std::vector<int32_t> chain;
for (int32_t start : critical_cells)
{
if (cancelled(cancel))
{
nodes->clear();
edges->clear();
return;
}
int32_t first_steps[8];
const int first_count = skeletonNeighbours(mask, start, first_steps);
for (int i = 0; i < first_count; ++i)
{
if (!visited.insert(linkKey(start, first_steps[i])).second)
continue;
chain.assign({ start, first_steps[i] });
int32_t previous = start;
int32_t current = first_steps[i];
// Every non-critical cell has exactly two neighbours, so the walk always ends on a critical cell.
while (critical[current] == 0)
{
const int degree = skeletonNeighbours(mask, current, around);
int32_t next = around[0] != previous ? around[0] : around[degree - 1];
visited.insert(linkKey(current, next));
chain.push_back(next);
previous = current;
current = next;
}
if (current == start)
continue;
VoronoiEdge edge;
edge.from = node_index(start);
edge.to = node_index(current);
edge.min_clearance_m = std::numeric_limits<double>::infinity();
edge.length_m = 0.0;
for (std::size_t k = 0; k < chain.size(); k += kKeepEveryCells)
edge.points.push_back(world(chain[k]));
if ((chain.size() - 1) % kKeepEveryCells != 0)
edge.points.push_back(world(chain.back()));
for (std::size_t k = 0; k < edge.points.size(); ++k)
{
if (k > 0)
edge.length_m += std::hypot(edge.points[k].x - edge.points[k - 1].x, edge.points[k].y - edge.points[k - 1].y);
}
if (clearance_mm != nullptr)
{
for (std::size_t k = 0; k < chain.size(); ++k)
{
if (k % kKeepEveryCells != 0 && k + 1 != chain.size())
continue;
const std::size_t cell = static_cast<std::size_t>(mask.y(chain[k])) * static_cast<std::size_t>(width) +
static_cast<std::size_t>(mask.x(chain[k]));
edge.min_clearance_m = std::min(edge.min_clearance_m, (*clearance_mm)[cell] / 1000.0);
}
}
edges->push_back(std::move(edge));
}
}
}
ReferenceGraph buildReferenceGraph(const ReferenceGridView& grid, const VoronoiSkeleton& skeleton,
const std::vector<robot_geometry_msgs::Point>& footprint,
const ReferenceGraphParams& params, const std::atomic<bool>* cancel)
{
checkParams(params);
checkGeometry(grid.geometry);
if (grid.cost == nullptr)
throw std::invalid_argument("reference_graph: null cost grid");
const int32_t width = static_cast<int32_t>(grid.geometry.width);
const int32_t height = static_cast<int32_t>(grid.geometry.height);
const std::size_t cell_count = static_cast<std::size_t>(width) * static_cast<std::size_t>(height);
if (skeleton.mask.size() != cell_count || skeleton.clearance_mm.size() != cell_count)
throw std::invalid_argument("reference_graph: skeleton size does not match the grid");
double half_x = 0.0;
double half_y = 0.0;
if (grid.direction_codes != nullptr)
{
if (footprint.size() < 3)
throw std::invalid_argument("reference_graph: footprint needs at least 3 points");
for (const robot_geometry_msgs::Point& point : footprint)
{
if (!std::isfinite(point.x) || !std::isfinite(point.y))
throw std::invalid_argument("reference_graph: footprint holds a non-finite point");
half_x = std::max(half_x, std::abs(point.x));
half_y = std::max(half_y, std::abs(point.y));
}
if (half_x <= 0.0 || half_y <= 0.0)
throw std::invalid_argument("reference_graph: footprint has no area");
}
ReferenceGraph graph;
graph.geometry = grid.geometry;
graph.params = params;
extractVoronoiEdges(skeleton.mask, grid.direction_codes, grid.geometry, &skeleton.clearance_mm, &graph.nodes,
&graph.edges, cancel);
if (cancelled(cancel))
return ReferenceGraph{};
if (grid.direction_codes != nullptr)
{
std::vector<int32_t> labels;
const std::vector<ZoneRegion> regions = findZoneRegions(grid.direction_codes, width, height, &labels);
for (std::size_t i = 0; i < regions.size(); ++i)
{
if (cancelled(cancel))
return ReferenceGraph{};
if (regions[i].cells.size() < 2)
continue;
double preferred = 0.0;
const std::vector<LaneCandidate> candidates =
compileRegionLanes(regions[i], labels, grid.cost, grid.geometry, half_x, half_y, params.lane_offset_step_m, &preferred);
selectLanes(regions[i], static_cast<uint32_t>(i), candidates, preferred, params.lane_offset_step_m, &graph.lanes);
}
}
graph.static_cost.assign(grid.cost, grid.cost + cell_count);
graph.clearance_mm = skeleton.clearance_mm;
return graph;
}
} // namespace robot_costmap_2d