first commit

This commit is contained in:
2026-09-22 15:44:53 +07:00
commit f2a5cf651a
32 changed files with 4841 additions and 0 deletions

View File

@@ -0,0 +1,24 @@
#ifndef VORONOI_ROUTE_ATTACHMENT_H_
#define VORONOI_ROUTE_ATTACHMENT_H_
#include "voronoi_route/types.h"
namespace voronoi_route {
class VoronoiField;
class VoronoiGraph;
/**
* @brief Walk from `from` through non-occupied cells to the nearest cell that lies on the route
* graph (BFS, 8-connected, Chebyshev radius bound).
*
* The start cell itself is accepted even if occupied: a robot reported inside a lethal cell
* (localisation jitter next to a wall) still needs a way out. Every other cell on the path is
* free. Inflation is deliberately not avoided — the start of a plan is usually inside it.
*/
Attachment attachPoint(const VoronoiField& field, const VoronoiGraph& graph, Cell from,
int max_radius_cells);
} // namespace voronoi_route
#endif // VORONOI_ROUTE_ATTACHMENT_H_

View File

@@ -0,0 +1,64 @@
#ifndef VORONOI_ROUTE_BUCKETED_QUEUE_H_
#define VORONOI_ROUTE_BUCKETED_QUEUE_H_
#include <vector>
#include <set>
#include <queue>
#include <assert.h>
#include <map>
#include "voronoi_route/point.h"
namespace voronoi_route {
//! Priority queue for integer coordinates with squared distances as priority.
/** A priority queue that uses buckets to group elements with the same priority.
* The individual buckets are unsorted, which increases efficiency if these groups are large.
* The elements are assumed to be integer coordinates, and the priorities are assumed
* to be squared Euclidean distances (integers).
*/
template <typename T>
class BucketPrioQueue {
public:
//! Standard constructor
/** Standard constructor. When called for the first time it creates a look up table
* that maps square distances to bucket numbers, which might take some time...
*/
BucketPrioQueue();
void clear() {
buckets.clear();
count = 0;
nextPop = buckets.end();
}
//! Checks whether the Queue is empty
bool empty();
//! push an element
void push(int prio, T t);
//! return and pop the element with the lowest squared distance */
T pop();
int size() { return count; }
int getNumBuckets() { return buckets.size(); }
int getTopPriority(){
return nextPop->first;
}
private:
int count;
typedef std::map< int, std::queue<T> > BucketType;
BucketType buckets;
typename BucketType::iterator nextPop;
};
} // namespace voronoi_route
#include "voronoi_route/bucketed_queue.hxx"
#endif // VORONOI_ROUTE_BUCKETED_QUEUE_H_

View File

@@ -0,0 +1,41 @@
// Template bodies of BucketPrioQueue; included only from bucketed_queue.h.
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
namespace voronoi_route {
template <class T>
BucketPrioQueue<T>::BucketPrioQueue() {
clear();
}
template <class T>
bool BucketPrioQueue<T>::empty() {
return (count==0);
}
template <class T>
void BucketPrioQueue<T>::push(int prio, T t) {
buckets[prio].push(t);
if (nextPop == buckets.end() || prio < nextPop->first) nextPop = buckets.find(prio);
count++;
}
template <class T>
T BucketPrioQueue<T>::pop() {
while (nextPop!=buckets.end() && nextPop->second.empty()) ++nextPop;
T p = nextPop->second.front();
nextPop->second.pop();
if (nextPop->second.empty()) {
typename BucketType::iterator it = nextPop;
nextPop++;
buckets.erase(it);
}
count--;
return p;
}
} // namespace voronoi_route

View File

@@ -0,0 +1,44 @@
#ifndef VORONOI_ROUTE_BUNDLE_IO_H_
#define VORONOI_ROUTE_BUNDLE_IO_H_
#include <cstdint>
#include <string>
#include <vector>
#include "voronoi_route/types.h"
#include "voronoi_route/voronoi_route.h"
namespace voronoi_route {
/** What a bundle says about the map it was built from. Consumers compare this before trusting it. */
struct BundleMeta {
uint32_t version = 1; ///< Bundle schema; bump when extraction semantics change.
int width = 0;
int height = 0;
double resolution = 0.0; ///< [m/cell]
double origin_x = 0.0; ///< [m] map_server origin (lower-left corner of the image)
double origin_y = 0.0;
double origin_yaw = 0.0;
std::string source; ///< e.g. "map_server:occupied+unknown"
uint64_t map_hash = 0; ///< hashObstacleMask() of the occupancy the graph came from
};
/**
* @brief Write `<dir>/voronoi.json` (meta, params, stats, nodes, edges with cell chains) and
* optionally `<dir>/voronoi_gvd.pgm` (8-bit, 255 = GVD cell) and `<dir>/voronoi_dist.pgm`
* (16-bit, clearance x10 in cells). Creates `dir`. No preview image — that needs an image
* library and lives in the tool.
*/
bool saveBundle(const VoronoiRoute& vr, const BundleMeta& meta, const std::string& dir,
bool with_gvd, bool with_dist, std::string* err);
/** Read only the meta block of `<dir>/voronoi.json` (cheap; for "is this bundle for my map?"). */
bool loadBundleMeta(const std::string& dir, BundleMeta* meta, std::string* err);
/** Route polyline + mask count the tool may add under "route"; optional. */
bool appendRouteToBundle(const std::string& dir, const Polyline& route, size_t mask_cells,
std::string* err);
} // namespace voronoi_route
#endif // VORONOI_ROUTE_BUNDLE_IO_H_

View File

@@ -0,0 +1,29 @@
#ifndef VORONOI_ROUTE_CORRIDOR_MASK_H_
#define VORONOI_ROUTE_CORRIDOR_MASK_H_
#include <cstddef>
#include <cstdint>
#include <vector>
#include "voronoi_route/types.h"
namespace voronoi_route {
class VoronoiField;
/**
* @brief Bitmap of cells within an adaptive half-width of a polyline.
*
* Width at a route cell is max(W_min, scale * clearance) capped at W_max: narrow where the map
* is narrow, the whole hall where it is open, so the corridor never forces a detour through the
* middle of a big room. Drawn by stamping discs on cells sampled every ~W/2 along the line; the
* discs overlap, so the band has no gaps. Every polyline cell is guaranteed inside the mask.
*
* @return row-major size_x*size_y bitmap, 1 = inside corridor. `cells_in_mask` gets the count.
*/
std::vector<uint8_t> corridorMask(const VoronoiField& field, const Polyline& polyline,
const CorridorParams& params, size_t* cells_in_mask);
} // namespace voronoi_route
#endif // VORONOI_ROUTE_CORRIDOR_MASK_H_

View File

@@ -0,0 +1,124 @@
// Port of DynamicVoronoi (Lau, Sprunk, Burgard, ICRA 2010) from
// Test/simulators/third_party/map_plugins/voronoi_layer (BSD). Namespaced, otherwise unchanged.
#ifndef VORONOI_ROUTE_DYNAMIC_VORONOI_H_
#define VORONOI_ROUTE_DYNAMIC_VORONOI_H_
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#include <queue>
#include <vector>
#include "voronoi_route/bucketed_queue.h"
namespace voronoi_route {
//! A DynamicVoronoi object computes and updates a distance map and Voronoi diagram.
class DynamicVoronoi {
public:
DynamicVoronoi();
~DynamicVoronoi();
//! Initialization with an empty map
void initializeEmpty(int _sizeX, int _sizeY, bool initGridMap=true);
//! Initialization with a given binary map (false==free, true==occupied)
void initializeMap(int _sizeX, int _sizeY, bool** _gridMap);
//! add an obstacle at the specified cell coordinate
void occupyCell(int x, int y);
//! remove an obstacle at the specified cell coordinate
void clearCell(int x, int y);
//! remove old dynamic obstacles and add the new ones
void exchangeObstacles(std::vector<INTPOINT>& newObstacles);
//! update distance map and Voronoi diagram to reflect the changes
void update(bool updateRealDist=true);
//! prune the Voronoi diagram
void prune();
//! prune the Voronoi diagram by globally revisiting all Voronoi nodes. Takes more time but gives a more sparsely pruned Voronoi graph. You need to call this after every call to udpate()
void updateAlternativePrunedDiagram();
//! retrieve the alternatively pruned diagram. see updateAlternativePrunedDiagram()
int** alternativePrunedDiagram() const {
return alternativeDiagram;
};
//! retrieve the number of neighbors that are Voronoi nodes (4-connected)
int getNumVoronoiNeighborsAlternative(int x, int y) const;
//! returns whether the specified cell is part of the alternatively pruned diagram. See updateAlternativePrunedDiagram.
bool isVoronoiAlternative( int x, int y ) const;
//! returns the obstacle distance at the specified location
float getDistance( int x, int y ) const;
//! returns whether the specified cell is part of the (pruned) Voronoi graph
bool isVoronoi( int x, int y ) const;
//! checks whether the specficied location is occupied
bool isOccupied(int x, int y) const;
//! write the current distance map and voronoi diagram as ppm file
void visualize(const char* filename="result.ppm");
//! returns the horizontal size of the workspace/map
unsigned int getSizeX() const {return sizeX;}
//! returns the vertical size of the workspace/map
unsigned int getSizeY() const {return sizeY;}
private:
struct dataCell {
float dist;
char voronoi;
char queueing;
int obstX;
int obstY;
bool needsRaise;
int sqdist;
};
typedef enum {voronoiKeep=-4, freeQueued = -3, voronoiRetry=-2, voronoiPrune=-1, free=0, occupied=1} State;
typedef enum {fwNotQueued=1, fwQueued=2, fwProcessed=3, bwQueued=4, bwProcessed=1} QueueingState;
typedef enum {invalidObstData = SHRT_MAX/2} ObstDataState;
typedef enum {pruned, keep, retry} markerMatchResult;
// methods
void setObstacle(int x, int y);
void removeObstacle(int x, int y);
inline void checkVoro(int x, int y, int nx, int ny, dataCell& c, dataCell& nc);
void recheckVoro();
void commitAndColorize(bool updateRealDist=true);
inline void reviveVoroNeighbors(int &x, int &y);
inline bool isOccupied(int &x, int &y, dataCell &c);
inline markerMatchResult markerMatch(int x, int y);
inline bool markerMatchAlternative(int x, int y);
inline int getVoronoiPruneValence(int x, int y);
// queues
BucketPrioQueue<INTPOINT> open;
std::queue<INTPOINT> pruneQueue;
BucketPrioQueue<INTPOINT> sortedPruneQueue;
std::vector<INTPOINT> removeList;
std::vector<INTPOINT> addList;
std::vector<INTPOINT> lastObstacles;
// maps
int sizeY;
int sizeX;
dataCell** data;
bool** gridMap;
bool allocatedGridMap;
// parameters
int padding;
double doubleThreshold;
double sqrt2;
// dataCell** getData(){ return data; }
int** alternativeDiagram;
};
} // namespace voronoi_route
#endif // VORONOI_ROUTE_DYNAMIC_VORONOI_H_

View File

@@ -0,0 +1,127 @@
#ifndef VORONOI_ROUTE_MAP_CONVERT_H_
#define VORONOI_ROUTE_MAP_CONVERT_H_
#include <cstddef>
#include <cstdint>
#include <string>
#include <vector>
namespace voronoi_route {
/**
* The costmap's own reading of an OccupancyGrid value — a port of
* `robot_costmap_2d::StaticLayer::interpretValue()` with the same parameter names, so a Voronoi
* built here calls the same cells "obstacle" as the static layer the planner runs on. Values are
* the ones `static_layer_params.yaml` (block `static_layer:`) carries; overrides per layer come
* from the costmap YAML (`global_costmap/<layer>/...`).
*/
struct StaticLayerRule {
bool track_unknown_space = true; ///< unknown -> NO_INFORMATION (true) or FREE_SPACE (false)
int lethal_cost_threshold = 100; ///< value >= this -> LETHAL_OBSTACLE
int unknown_cost_value = -1; ///< the grid value that means "unknown"
bool trinary_costmap = true; ///< true: everything below lethal is FREE; false: scaled cost
};
/** What the planner does with NO_INFORMATION cells: SBPL `allow_unknown`. */
enum class UnknownPolicy : uint8_t {
kTraversable, ///< allow_unknown = true (SBPL default): unknown is not an obstacle
kObstacle ///< allow_unknown = false: unknown blocks the robot
};
/** Full obstacle rule: how a grid value becomes a cost class, and which classes block. */
struct ObstacleRule {
StaticLayerRule layer;
UnknownPolicy unknown = UnknownPolicy::kTraversable;
/**
* Region of interest: the bounding box of obstacle cells grown by this margin; everything
* outside counts as obstacle. Kills the Voronoi rays that shoot from every wall gap to the image
* edge when the outside is free/unknown-traversable, and skips the distance transform over
* millions of empty cells. < 0 = off. The consumer must apply the same margin (it is part of the
* rule string) — the box is derived from the map itself, so both sides get the same box.
*/
int roi_margin_cells = -1;
};
/** Cost classes the static layer can produce. `kScaled` only when !trinary_costmap. */
enum class CostClass : uint8_t { kFree, kLethal, kNoInformation, kScaled };
/** Costmap cost values as `robot_costmap_2d/cost_values.h` defines them (copied, no dependency). */
constexpr unsigned char kCostmapLethalObstacle = 254;
constexpr unsigned char kCostmapNoInformation = 255;
/** map_server YAML fields that decide what an image pixel means. */
struct MapServerThresholds {
bool negate = false;
double occupied_thresh = 0.65;
double free_thresh = 0.196;
};
struct MapConvertStats {
size_t occupied = 0; ///< cells classified kLethal
size_t unknown = 0; ///< cells classified kNoInformation
size_t free = 0; ///< everything else
};
/** StaticLayer::interpretValue(), classification only. */
CostClass classifyGridValue(int value, const StaticLayerRule& rule);
/** True when a cell of this class is an obstacle for the Voronoi diagram under `rule`. */
bool isObstacleClass(CostClass c, const ObstacleRule& rule);
/**
* @brief Map image (any channel count) -> obstacle mask, by the ROS map_server rule in TRINARY
* mode, which is what the robot's static layer actually receives.
*
* map_server (`image_loader.cpp`) averages ALL channels of a pixel — alpha included in trinary
* mode — then occ = (255 - avg) / 255 (avg / 255 when negate); occ > occupied_thresh -> 100,
* occ < free_thresh -> 0, otherwise -1. On an RGBA map a gray pixel (79,79,79,255) therefore
* averages to 123 and is UNKNOWN, not occupied, and (205,205,205,255) averages to 217 and is
* FREE. Reading the same file as luminance gives a different lethal set and a different hash, so
* the producer must apply this rule, not a decoder's grayscale conversion.
*
* Then value -> class by `rule.layer`, class -> obstacle by `rule.unknown`. `pixels` is row-major,
* row 0 = top, `channels` bytes per pixel; the mask keeps that layout.
*/
std::vector<uint8_t> occupancyFromImage(const uint8_t* pixels, int width, int height, int channels,
const MapServerThresholds& thresholds,
const ObstacleRule& rule, MapConvertStats* stats = nullptr);
/** Single-channel convenience: occupancyFromImage(gray, w, h, 1, ...). */
std::vector<uint8_t> occupancyFromGray(const uint8_t* gray, int width, int height,
const MapServerThresholds& thresholds,
const ObstacleRule& rule, MapConvertStats* stats = nullptr);
/**
* @brief OccupancyGrid int8 array -> obstacle mask, by `rule`. Input is ROS layout (row 0 =
* bottom); output is flipped to row 0 = top to match the image layout used everywhere else.
*/
std::vector<uint8_t> occupancyFromGrid(const int8_t* data, int width, int height,
const ObstacleRule& rule, MapConvertStats* stats = nullptr);
/**
* @brief Live costmap char map (values 0..255 as the static layer wrote them) -> obstacle mask.
* This is what a runtime consumer hashes to decide whether a bundle matches:
* 254 -> obstacle; 255 -> obstacle only under UnknownPolicy::kObstacle; else free.
* @param rows_bottom_up true for a costmap (row 0 = bottom): the mask is flipped to row 0 = top.
*/
std::vector<uint8_t> occupancyFromCostmap(const unsigned char* charmap, int width, int height,
UnknownPolicy unknown, bool rows_bottom_up);
/**
* @brief Apply ObstacleRule::roi_margin_cells to a mask in place: cells outside the grown bounding
* box of the mask's obstacle cells become obstacles. No-op when margin < 0 or when the mask
* has fewer than `min_obstacle_cells` obstacles (a near-empty map has no meaningful box).
* @return number of cells turned into obstacles.
*/
size_t applyObstacleRoi(std::vector<uint8_t>& mask, int width, int height, int margin_cells,
size_t min_obstacle_cells = 16);
/** Compact, stable description for the bundle's `source` field, e.g. "lethal>=100;...;unknown=traversable;roi=40". */
std::string obstacleRuleString(const ObstacleRule& rule);
/** Inverse of obstacleRuleString(); false if the string is not one it produced. */
bool parseObstacleRuleString(const std::string& s, ObstacleRule* rule);
} // namespace voronoi_route
#endif // VORONOI_ROUTE_MAP_CONVERT_H_

View File

@@ -0,0 +1,62 @@
#ifndef VORONOI_ROUTE_PARAMS_H_
#define VORONOI_ROUTE_PARAMS_H_
#include <string>
#include <vector>
#include "voronoi_route/map_convert.h"
#include "voronoi_route/types.h"
#include "voronoi_route/voronoi_route.h"
namespace voronoi_route {
/**
* @brief Operator-facing parameters, in metres — the contents of `voronoi_route_params.yaml`.
*
* The library computes in cells; convert with the map's resolution at load time. Defaults here
* are the ones in the packaged YAML; a missing key keeps the default and the loader says so.
*/
struct RouteParams {
// graph
double min_edge_length_m = 0.3;
double spur_clearance_ratio = 1.2;
double min_component_length_m = 2.0;
double min_clearance_m = 0.3;
double attach_max_radius_m = 10.0;
int graph_rebuild_min_changed_cells = 200;
double full_rebuild_fraction = 0.02;
// corridor
double half_width_min_m = 1.5;
double clearance_scale = 0.8;
double half_width_max_m = 6.0;
// bundle
bool write_gvd = true;
bool write_dist = true;
bool write_preview = true;
bool write_graph_image = true;
bool write_graph_overlay = false;
// obstacle: luật "ô nào là vật cản" của riêng gói này, không đọc chéo sang config gói khác.
bool track_unknown_space = true;
int lethal_cost_threshold = 100;
int unknown_cost_value = -1;
bool trinary_costmap = true;
// obstacle.unknown: false traversable, true obstacle — quyết định thẳng, không suy từ khoá nào khác.
bool unknown_is_obstacle = false;
// obstacle.roi_margin_m: < 0 = off
double roi_margin_m = 0.5;
VoronoiRoute::Config toConfig(double resolution_m) const;
CorridorParams toCorridor(double resolution_m) const;
/** Obstacle rule for this map's resolution, resolved from the fields above only. */
ObstacleRule toObstacleRule(double resolution_m) const;
};
/**
* @brief Clamp out-of-range values to something safe and describe each fix. Empty vector = all
* good. Never throws: a bad number in a YAML must not stop a map from being compiled.
*/
std::vector<std::string> validateRouteParams(RouteParams* p);
} // namespace voronoi_route
#endif // VORONOI_ROUTE_PARAMS_H_

View File

@@ -0,0 +1,29 @@
#ifndef VORONOI_ROUTE_PARAMS_IO_H_
#define VORONOI_ROUTE_PARAMS_IO_H_
#include <string>
#include <vector>
#include "voronoi_route/params.h"
namespace voronoi_route {
/**
* @brief First file named `name` under `dir`, searched recursively — the lookup
* robot_costmap_2d uses for its layer YAMLs, so "the robot's config dir" means the same
* thing here. Empty string if not found or `dir` is not a directory.
*/
std::string findConfigFile(const std::string& dir, const std::string& name);
/**
* @brief Load `voronoi_route_params.yaml` (root key `voronoi_route`). Missing keys keep defaults;
* every missing key is listed in `notes` so a typo does not silently become a default.
* Out-of-range values are clamped by validateRouteParams(), also reported in `notes`.
* @return false only when the file cannot be read or parsed at all.
*/
bool loadRouteParams(const std::string& yaml_path, RouteParams* params, std::string* err,
std::vector<std::string>* notes);
} // namespace voronoi_route
#endif // VORONOI_ROUTE_PARAMS_IO_H_

View File

@@ -0,0 +1,18 @@
#ifndef VORONOI_ROUTE_POINT_H_
#define VORONOI_ROUTE_POINT_H_
namespace voronoi_route {
#define INTPOINT IntPoint
/*! A light-weight integer point with fields x,y */
class IntPoint {
public:
IntPoint() : x(0), y(0) {}
IntPoint(int _x, int _y) : x(_x), y(_y) {}
int x,y;
};
} // namespace voronoi_route
#endif // VORONOI_ROUTE_POINT_H_

View File

@@ -0,0 +1,39 @@
#ifndef VORONOI_ROUTE_TYPES_H_
#define VORONOI_ROUTE_TYPES_H_
#include <cstdint>
#include <vector>
namespace voronoi_route {
/** Integer grid cell. x = column, y = row of the occupancy grid as handed to the library. */
struct Cell {
int x = 0;
int y = 0;
Cell() = default;
Cell(int x_, int y_) : x(x_), y(y_) {}
bool operator==(const Cell& o) const { return x == o.x && y == o.y; }
bool operator!=(const Cell& o) const { return !(*this == o); }
};
/** Ordered, 8-connected chain of cells. */
using Polyline = std::vector<Cell>;
/** Where a free cell attaches to the route graph, plus the free-space path that gets there. */
struct Attachment {
bool ok = false;
int edge = -1; ///< Graph edge holding the attach cell.
int index = -1; ///< Position of the attach cell inside that edge's cell chain.
Polyline path; ///< From the queried cell (front) to the attach cell (back), 8-connected, free.
};
/** Corridor width policy, all in cells. */
struct CorridorParams {
double half_width_min_cells = 30.0; ///< W_min: never narrower than this.
double clearance_scale = 0.8; ///< W(c) = max(W_min, scale * clearance(c)).
double half_width_max_cells = 120.0; ///< Cap for the adaptive width.
};
} // namespace voronoi_route
#endif // VORONOI_ROUTE_TYPES_H_

View File

@@ -0,0 +1,65 @@
#ifndef VORONOI_ROUTE_VORONOI_FIELD_H_
#define VORONOI_ROUTE_VORONOI_FIELD_H_
#include <cstdint>
#include <memory>
#include <vector>
#include "voronoi_route/types.h"
namespace voronoi_route {
class DynamicVoronoi;
/**
* @brief Distance map + generalized Voronoi diagram over a flat occupancy grid.
*
* Thin owner of the ported DynamicVoronoi (Lau et al.). Callers hand in a flat row-major grid;
* this class keeps the column-major `bool**` view DynamicVoronoi insists on, so the caller never
* sees that layout. Only cells flagged occupied by the caller's predicate are obstacles — the
* library has no opinion on what "occupied" means (lethal, unknown, ...). That decision is the
* caller's, and it must be the same decision the runtime consumer makes, or hashes will not match.
*/
class VoronoiField {
public:
VoronoiField();
~VoronoiField();
VoronoiField(const VoronoiField&) = delete;
VoronoiField& operator=(const VoronoiField&) = delete;
/** Rebuild from scratch. `occupied` is row-major, size_x*size_y, nonzero = obstacle. */
void rebuild(const std::vector<uint8_t>& occupied, int size_x, int size_y);
/** Queue occupancy changes; nothing is recomputed until refresh(). */
void setOccupied(const std::vector<Cell>& cells);
void setFree(const std::vector<Cell>& cells);
/** Propagate queued changes (incremental) and re-thin the diagram. */
void refresh();
bool ready() const { return ready_; }
int sizeX() const { return size_x_; }
int sizeY() const { return size_y_; }
bool inBounds(int x, int y) const { return x >= 0 && y >= 0 && x < size_x_ && y < size_y_; }
bool isVoronoi(int x, int y) const;
bool isOccupied(int x, int y) const;
/** Euclidean distance to the nearest obstacle, in cells. Occupied cells return 0. */
float distanceCells(int x, int y) const;
/** Row-major copy of the occupancy the field currently holds (what the diagram was built from). */
const std::vector<uint8_t>& occupancy() const { return occupancy_; }
private:
std::unique_ptr<DynamicVoronoi> dv_;
int size_x_ = 0;
int size_y_ = 0;
bool ready_ = false;
std::vector<uint8_t> occupancy_; // row-major mirror, kept in sync with dv_
std::vector<std::unique_ptr<bool[]>> columns_; // column-major storage DynamicVoronoi points into
std::vector<bool*> column_ptrs_;
};
} // namespace voronoi_route
#endif // VORONOI_ROUTE_VORONOI_FIELD_H_

View File

@@ -0,0 +1,114 @@
#ifndef VORONOI_ROUTE_VORONOI_GRAPH_H_
#define VORONOI_ROUTE_VORONOI_GRAPH_H_
#include <cstdint>
#include <vector>
#include "voronoi_route/types.h"
namespace voronoi_route {
class VoronoiField;
struct GraphNode {
Cell cell;
std::vector<int> edges; ///< Incident edge indices. A loop edge (u == v) appears once.
};
struct GraphEdge {
int u = -1;
int v = -1;
Polyline cells; ///< cells.front() is node u's cell, cells.back() node v's.
std::vector<float> cum_cells; ///< cum_cells[i] = walked length from cells[0] to cells[i].
float length_cells = 0.0f; ///< == cum_cells.back().
float min_clearance_cells = 0.0f; ///< Narrowest point along the chain.
};
/**
* @brief Route graph extracted from a thinned GVD: junctions/dead-ends are nodes, the chains
* between them are edges. Also answers "which edge does this GVD cell belong to" and
* routes between two attached points with Dijkstra.
*/
class VoronoiGraph {
public:
/**
* @param min_edge_length_cells Dead-end branches shorter than this are pruned (SLAM wall
* noise grows stubs a few cells long at every convex corner). Pruning repeats until
* nothing short is left, and nodes left with exactly two edges are merged away.
*/
struct ExtractParams {
double min_edge_length_cells = 6.0;
/**
* A dead-end branch shorter than `ratio * clearance(root junction)` never leaves the empty
* disc around its junction: it is the diagram reacting to a notch in a far wall, not a way
* anywhere. Real dead-end corridors are longer than the hall they leave. 0 disables.
*/
double spur_clearance_ratio = 1.0;
/** Connected components whose total edge length is below this are dropped (pockets). */
double min_component_length_cells = 0.0;
/**
* Edges whose narrowest point has less clearance than this are dropped before anything
* else: a passage the robot cannot fit through is not a route, and on SLAM maps the ragged
* free/unknown frontier grows dense little loops of exactly that kind. Set it to the robot's
* inscribed radius in cells. 0 disables.
*/
double min_clearance_cells = 0.0;
};
void extract(const VoronoiField& field, const ExtractParams& params);
void extract(const VoronoiField& field, double min_edge_length_cells)
{
ExtractParams p;
p.min_edge_length_cells = min_edge_length_cells;
extract(field, p);
}
void clear();
bool empty() const { return edges_.empty(); }
int sizeX() const { return size_x_; }
int sizeY() const { return size_y_; }
const std::vector<GraphNode>& nodes() const { return nodes_; }
const std::vector<GraphEdge>& edges() const { return edges_; }
/** Edge index of a GVD cell, -1 if the cell is not on the graph. */
int edgeAt(int x, int y) const;
/** Position of the cell inside edges()[edgeAt(x,y)].cells, -1 if not on the graph. */
int indexOnEdge(int x, int y) const;
/** Number of connected components (nodes reachable from each other). */
int componentCount() const;
/**
* Shortest route along the graph between two attached points. Result runs from a's attach
* cell to b's attach cell inclusive, 8-connected. Empty if they are on different components.
*/
Polyline route(const Attachment& a, const Attachment& b) const;
private:
struct RawEdge {
int u, v;
Polyline cells;
};
void traceFromNodes(const VoronoiField& field, const std::vector<uint8_t>& is_gvd,
const std::vector<int>& degree, std::vector<int>& node_of_cell,
std::vector<uint8_t>& visited, std::vector<RawEdge>& raw);
void traceCycles(const VoronoiField& field, const std::vector<uint8_t>& is_gvd,
std::vector<int>& node_of_cell, std::vector<uint8_t>& visited,
std::vector<RawEdge>& raw);
void pruneSpursAndMerge(const VoronoiField& field, const ExtractParams& params);
void dropSmallComponents(double min_total_length_cells);
void finalize(const VoronoiField& field);
int size_x_ = 0;
int size_y_ = 0;
std::vector<GraphNode> nodes_;
std::vector<GraphEdge> edges_;
std::vector<int32_t> cell_edge_; // size_x*size_y, -1 = not on graph
std::vector<int32_t> cell_index_; // position within that edge's chain
};
} // namespace voronoi_route
#endif // VORONOI_ROUTE_VORONOI_GRAPH_H_

View File

@@ -0,0 +1,98 @@
#ifndef VORONOI_ROUTE_VORONOI_ROUTE_H_
#define VORONOI_ROUTE_VORONOI_ROUTE_H_
#include <cstddef>
#include <cstdint>
#include <vector>
#include "voronoi_route/attachment.h"
#include "voronoi_route/corridor_mask.h"
#include "voronoi_route/types.h"
#include "voronoi_route/voronoi_field.h"
#include "voronoi_route/voronoi_graph.h"
namespace voronoi_route {
/**
* @brief FNV-1a 64 over the bit-packed obstacle mask, row-major. The one hash both the producer
* (offline compile) and the consumer (planner on the live static layer) use; if they ever
* computed it differently, a stale graph could be accepted in silence.
*/
uint64_t hashObstacleMask(const std::vector<uint8_t>& occupied);
/**
* @brief Facade: occupancy in, route polylines and corridor masks out.
*
* Holds the distance field, the extracted graph and the config. Nothing here knows about
* costmaps, messages or threads; the caller decides what "occupied" means and serialises access.
*/
class VoronoiRoute {
public:
struct Config {
double min_edge_length_cells = 6.0; ///< Spur filter, absolute (0.3 m at 5 cm).
double spur_clearance_ratio = 1.2; ///< Spur filter, relative to clearance at root.
double min_component_length_cells = 40.0; ///< Drop pocket components (2 m at 5 cm).
double min_clearance_cells = 0.0; ///< Drop edges narrower than the robot (0 = off).
int attach_max_radius_cells = 200; ///< BFS bound for attach() (10 m at 5 cm).
size_t graph_rebuild_min_changed_cells = 200; ///< Below: distance update only, graph kept.
double full_rebuild_fraction = 0.02; ///< Above this share of cells: rebuild, not incremental.
};
struct Stats {
int nodes = 0;
int edges = 0;
int components = 0;
size_t gvd_cells = 0;
size_t obstacle_cells = 0;
double field_ms = 0.0; ///< DynamicVoronoi build/update + prune.
double extract_ms = 0.0; ///< Graph extraction.
size_t last_sync_changed = 0;
bool last_sync_full_rebuild = false;
};
VoronoiRoute();
explicit VoronoiRoute(const Config& cfg);
/** Build everything from scratch. `occupied` row-major, size_x*size_y, nonzero = obstacle. */
void rebuild(const std::vector<uint8_t>& occupied, int size_x, int size_y);
/**
* Compare `occupied` (same size as the current field) with what the field holds and bring it up
* to date: nothing, incremental occupy/clear + refresh, or a full rebuild when the change is
* wide (a whole-floor swap is faster from scratch than by propagation). The graph is
* re-extracted when the number of changed cells exceeds `graph_rebuild_min_changed_cells`.
* @return number of cells whose obstacle state differed. Size mismatch -> full rebuild.
*/
size_t syncOccupancy(const std::vector<uint8_t>& occupied, int size_x, int size_y);
bool ready() const { return field_.ready() && !graph_.empty(); }
Attachment attach(Cell c) const;
/** start -> ... -> goal, including both attach paths. Empty if no route on the graph. */
Polyline query(const Attachment& start, const Attachment& goal) const;
std::vector<uint8_t> corridorMask(const Polyline& route, const CorridorParams& p,
size_t* cells_in_mask) const;
const VoronoiField& field() const { return field_; }
const VoronoiGraph& graph() const { return graph_; }
const Stats& stats() const { return stats_; }
const Config& config() const { return cfg_; }
/** Hash of the occupancy the field was built from. */
uint64_t occupancyHash() const { return occupancy_hash_; }
private:
void extractGraph();
Config cfg_;
VoronoiField field_;
VoronoiGraph graph_;
Stats stats_;
uint64_t occupancy_hash_ = 0;
};
} // namespace voronoi_route
#endif // VORONOI_ROUTE_VORONOI_ROUTE_H_