diff --git a/CMakeLists.txt b/CMakeLists.txt index 0f10164..b003d47 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -23,6 +23,7 @@ find_package(Boost REQUIRED COMPONENTS system thread filesystem) # still configure. The test block below requires it where it is actually used. find_package(GTest QUIET) find_package(yaml-cpp REQUIRED) +find_package(Threads REQUIRED) # DepthCameraObstacleLayer only (voxel grid, kd-tree clearing, Euclidean clustering); the core # library and the other layers do not use PCL. find_package(PCL REQUIRED COMPONENTS common filters kdtree search segmentation) @@ -113,6 +114,8 @@ add_library(robot_costmap_2d SHARED src/layer.cpp src/layered_costmap.cpp src/direction_field.cpp + src/reference_graph.cpp + src/reference_graph_worker.cpp src/costmap_math.cpp src/footprint.cpp src/costmap_layer.cpp @@ -136,6 +139,7 @@ if(BUILDING_WITH_CATKIN) PRIVATE yaml-cpp PRIVATE dl PRIVATE ${TF3_LIBRARY} + PUBLIC Threads::Threads ) else() @@ -157,6 +161,7 @@ else() yaml-cpp dl ${TF3_LIBRARY} + Threads::Threads ) set_target_properties(robot_costmap_2d PROPERTIES @@ -301,9 +306,18 @@ if(BUILD_COSTMAP_TESTS) find_package(Boost REQUIRED COMPONENTS system thread filesystem) find_library(TF3_LIBRARY NAMES tf3 PATHS /usr/lib /usr/local/lib /usr/lib/x86_64-linux-gnu) + add_executable(costmap_common_root_test test/costmap_common_root_test.cpp) + target_link_libraries(costmap_common_root_test PRIVATE robot_costmap_2d GTest::GTest GTest::Main) + add_executable(direction_field_test test/direction_field_test.cpp) target_link_libraries(direction_field_test PRIVATE robot_costmap_2d GTest::GTest GTest::Main) + add_executable(reference_graph_test test/reference_graph_test.cpp) + target_link_libraries(reference_graph_test PRIVATE robot_costmap_2d GTest::GTest GTest::Main) + + add_executable(reference_graph_worker_test test/reference_graph_worker_test.cpp) + target_link_libraries(reference_graph_worker_test PRIVATE robot_costmap_2d GTest::GTest GTest::Main Boost::thread) + add_executable(directional_layer_test test/directional_layer_test.cpp) target_link_libraries(directional_layer_test PRIVATE plugins robot_costmap_2d GTest::GTest GTest::Main Boost::thread ${TF3_LIBRARY}) diff --git a/README.md b/README.md index 0f72c3a..d505b3a 100644 --- a/README.md +++ b/README.md @@ -53,6 +53,11 @@ Tham số có ba tầng ưu tiên, tầng sau ghi đè tầng trước: 3. Tham số trong `robot::NodeHandle`, thường được launch nạp cho `global_costmap` hoặc `local_costmap`. +Các khóa chung có thể nằm trong map `root:` hoặc trực tiếp ở đầu cây YAML (flat). +Khi có `root:`, costmap chỉ lấy khóa chung từ map đó; nếu không có thì dùng layout +flat. Khóa trong `/` được ưu tiên, còn block plugin chung chỉ +bổ sung những khóa chưa được costmap đặt. + Biến môi trường `PNKX_NAV_CORE_CONFIG_DIR` phải trỏ tới thư mục cha có thư mục con `config/`. Hàm nạp sẽ tìm đệ quy các file sau: diff --git a/include/robot_costmap_2d/costmap_2d_robot.h b/include/robot_costmap_2d/costmap_2d_robot.h index e84ffce..3f7e5ab 100755 --- a/include/robot_costmap_2d/costmap_2d_robot.h +++ b/include/robot_costmap_2d/costmap_2d_robot.h @@ -79,6 +79,14 @@ namespace robot_costmap_2d class Costmap2DROBOT { public: + /** @brief Select the namespace containing shared costmap parameters. */ + static robot::NodeHandle commonParametersHandle(robot::NodeHandle& tree_nh); + + /** @brief Fill missing costmap layer parameters from the shared layer block. */ + static void copyParentParameters(const std::string& costmap_name, const std::string& plugin_name, + const std::string& plugin_type, robot::NodeHandle& source_nh, + robot::NodeHandle& target_nh); + /** * @brief Constructor for the wrapper * @param name The name for this costmap @@ -295,7 +303,6 @@ protected: double transform_tolerance_; ///< timeout before transform errors private: - void copyParentParameters(const std::string& costmap_name, const std::string& plugin_name, const std::string& plugin_type, robot::NodeHandle& nh); /** @brief Set the footprint from the new_config object. * * If the values of footprint and robot_radius are the same in diff --git a/include/robot_costmap_2d/layered_costmap.h b/include/robot_costmap_2d/layered_costmap.h index 277b4a2..515f15c 100755 --- a/include/robot_costmap_2d/layered_costmap.h +++ b/include/robot_costmap_2d/layered_costmap.h @@ -39,9 +39,13 @@ #define ROBOT_COSTMAP_2D_LAYERED_COSTMAP_H_ #include +#include #include #include #include +#include +#include +#include #include #include #include @@ -50,6 +54,8 @@ namespace robot_costmap_2d { class Layer; +class ReferenceGraphWorker; +enum class LayerType; // layer.h includes this header before it defines the enum. /** * @class LayeredCostmap @@ -103,6 +109,23 @@ public: /** Consistent snapshot; plugin list must be fixed before concurrent reads. */ DirectionFieldSnapshot getDirectionFieldSnapshot() const; + /** @brief Start computing the coarse graph in the background. Call once, after the plugins are loaded. + * The first computation starts by itself, so a map that arrived earlier still counts. + * @return False, with an error logged, on a rolling costmap, bad parameters or a second call. */ + bool enableReferenceGraph(const ReferenceGraphParams& params); + + /** @brief Consistent snapshot, safe to retain on a planner thread. Never takes the master mutex. */ + ReferenceGraphSnapshot getReferenceGraphSnapshot() const; + + /** @brief Counts map changes per layer type, e.g. PREFERRED_LAYER, so a planner knows when to rebuild what it derives. */ + uint64_t getStaticMapRevision(LayerType type) const; + + /** @brief Called by the StaticLayer family under the master mutex. Only STATIC_LAYER reruns steps 1 and 2. */ + void notifyStaticMapChanged(LayerType type); + + /** @brief Called by DirectionalLayer whenever it publishes. Reruns step 2 only. */ + void notifyDirectionFieldChanged(); + Costmap2D* getCostmap() { return &costmap_; @@ -218,6 +241,10 @@ private: std::uint64_t window_cells_sum_ = 0; std::uint64_t window_cells_max_ = 0; std::uint64_t performance_empty_cycles_ = 0; + + static constexpr std::size_t kMaxLayerTypes = 16; ///< Checked against LayerType in layered_costmap.cpp. + std::array, kMaxLayerTypes> static_map_revisions_{}; + std::unique_ptr reference_graph_worker_; ///< Null when reference_graph_enabled is false: no thread at all. }; } // namespace robot_costmap_2d diff --git a/include/robot_costmap_2d/reference_graph.h b/include/robot_costmap_2d/reference_graph.h new file mode 100644 index 0000000..c3a87b2 --- /dev/null +++ b/include/robot_costmap_2d/reference_graph.h @@ -0,0 +1,157 @@ +#ifndef ROBOT_COSTMAP_2D_REFERENCE_GRAPH_H_ +#define ROBOT_COSTMAP_2D_REFERENCE_GRAPH_H_ + +#include +#include +#include +#include +#include + +#include + +#include + +namespace robot_costmap_2d +{ + +/** @brief Inputs of the coarse graph. All lengths are absolute, none is derived from the footprint. */ +struct ReferenceGraphParams +{ + double min_clearance_m = 0.335; ///< [m] Ridge cells closer to a lethal cell than this are dropped. + double ridge_min_separation_m = 0.7; ///< [m] Two nearest obstacles closer than this count as one. + double spur_min_length_m = 1.0; ///< [m] Dead-end branches shorter than this are pruned. + double lane_offset_step_m = 0.5; ///< [m] Spacing of the parallel lanes inside one zone. + bool debug_log = true; ///< One [debug] line per finished computation. Errors always log. +}; + +/** @brief Return an empty string for valid parameters, otherwise a description of the first bad value. */ +std::string validateReferenceGraphParams(const ReferenceGraphParams& params); + +/** @brief Point [m] in ReferenceGraph::geometry.frame_id. */ +struct ReferencePoint +{ + double x, y; +}; + +/** @brief Undirected ridge segment, split at zone boundaries. Direction rules belong to the planner. */ +struct VoronoiEdge +{ + uint32_t from, to; ///< Indices into ReferenceGraph::nodes. + std::vector points; ///< [m] Every fifth skeleton cell plus the exact end, from -> to. + double length_m; ///< [m] Length of the polyline through points. + double min_clearance_m; ///< [m] Smallest clearance at points. Infinity when no clearance grid was given. +}; + +/** @brief Straight one-way lane inside one zone, in travel direction. */ +struct ReferenceLane +{ + uint32_t zone_id; ///< Connected region of equal direction code. Unique inside one graph. + uint8_t direction_index; ///< 0..7 CCW from +X, as in direction_field.h. + ReferencePoint entry, exit; ///< [m] + double length_m; ///< [m] + double offset_from_centre_m; ///< [m] Absolute distance from the zone's main lane. The planner turns it into a penalty. +}; + +/** @brief Plain grid input. A window crop passes the full-map clearance so obstacles just outside still count. */ +struct ReferenceGridView +{ + const uint8_t* cost = nullptr; ///< width*height, row-major, cost_values.h. + const uint16_t* clearance_mm = nullptr; ///< [mm] May be null: computed from `cost`. + const uint8_t* direction_codes = nullptr; ///< May be null: no zones. 0 unconstrained, 1..8 as in direction_field.h. + DirectionGeometry geometry{}; +}; + +/** @brief Output of step 1. Kept by the worker so a zone or footprint change reruns step 2 only. */ +struct VoronoiSkeleton +{ + DirectionGeometry geometry{}; + std::vector mask; ///< width*height, row-major, 1 on a skeleton cell. Empty when cancelled. + std::vector clearance_mm; ///< [mm] width*height. Distance to the nearest lethal cell, capped at 65535. +}; + +/** @brief Coarse graph of one map and one direction grid. */ +struct ReferenceGraph +{ + DirectionGeometry geometry{}; ///< Same grid layout as the master costmap. + ReferenceGraphParams params; ///< Parameters this graph was built with. + uint64_t direction_generation = 0; ///< DirectionFieldSnapshot::generation the lanes came from. Set by the worker. + std::vector nodes; ///< [m] Junctions, dead ends and zone-boundary points. + std::vector edges; ///< Green lines in the review image. + std::vector lanes; ///< Red lines in the review image, before the lead extension. + std::vector static_cost; ///< width*height, row-major, cost_values.h. Empty when cancelled. + std::vector clearance_mm; ///< [mm] width*height. +}; + +enum class ReferenceGraphState +{ + kDisabled, ///< reference_graph_enabled is false. + kPending, ///< A map, zone or footprint change is being processed. + kReady ///< graph matches the current map and direction grid. +}; + +/** @brief Consistent view of the graph, safe to retain on a planner thread. */ +struct ReferenceGraphSnapshot +{ + ReferenceGraphState state = ReferenceGraphState::kDisabled; + std::shared_ptr graph; ///< Non-null only in kReady. + uint64_t generation = 0; ///< Changes whenever state or graph changes. +}; + +/** @brief Step 1: distance transform, ridge cells, thinning and spur pruning. + * + * Only LETHAL_OBSTACLE cells are obstacles. Ridge cells must have cost below + * INSCRIBED_INFLATED_OBSTACLE, so unknown and inflated cells never join the skeleton. + * @param grid Input grid. `direction_codes` is ignored here. + * @param params Graph parameters. + * @param cancel When non-null and set, returns early with an empty mask. + * @throws std::invalid_argument on bad parameters, geometry or a null cost pointer. + */ +VoronoiSkeleton computeVoronoiSkeleton(const ReferenceGridView& grid, const ReferenceGraphParams& params, + const std::atomic* cancel = nullptr); + +/** @brief Centre line of a cell mask of any width, used by the planner for the `preferred` region in step 3. + * @param mask width*height, row-major, nonzero inside the region. + * @param geometry Grid layout of the mask. + * @param params Only spur_min_length_m is used: the region's own boundary replaces the obstacle thresholds. + * @return width*height mask of the centre line. + * @throws std::invalid_argument on bad parameters or a size mismatch. + */ +std::vector computeRegionCentreLine(const std::vector& mask, const DirectionGeometry& geometry, + const ReferenceGraphParams& params); + +/** @brief Nodes and edges of a skeleton, split where the direction code changes. Part of step 2. + * + * A closed ring without a junction yields no node and no edge, and neither does a branch that + * returns to the node it left. The graph search could not enter them through a node anyway. + * @param skeleton_mask width*height, row-major, nonzero on a skeleton cell. + * @param direction_codes May be null: no zones. + * @param geometry Grid layout of the mask. + * @param clearance_mm May be null: VoronoiEdge::min_clearance_m is then infinity. + * @param nodes Output, replaced. Must not be null. + * @param edges Output, replaced. Must not be null. + * @param cancel When non-null and set, returns early with both outputs empty. + * @throws std::invalid_argument on a size mismatch or a null output. + */ +void extractVoronoiEdges(const std::vector& skeleton_mask, const uint8_t* direction_codes, + const DirectionGeometry& geometry, const std::vector* clearance_mm, + std::vector* nodes, std::vector* edges, + const std::atomic* cancel = nullptr); + +/** @brief Step 2: Voronoi edges split at zone boundaries, plus straight lanes from the direction grid. + * + * Lanes use the rectangle that bounds the footprint, centred on the robot origin, so an off-centre + * or non-rectangular footprint is checked conservatively. + * @param grid Input grid, the same one the skeleton came from. + * @param skeleton Output of computeVoronoiSkeleton. + * @param footprint Robot footprint [m]. Needs at least 3 points when `grid.direction_codes` is non-null. + * @param params Graph parameters. + * @param cancel When non-null and set, returns early with an empty graph. + * @throws std::invalid_argument on bad parameters, a skeleton of another size or a bad footprint. + */ +ReferenceGraph buildReferenceGraph(const ReferenceGridView& grid, const VoronoiSkeleton& skeleton, + const std::vector& footprint, + const ReferenceGraphParams& params, const std::atomic* cancel = nullptr); + +} // namespace robot_costmap_2d + +#endif // ROBOT_COSTMAP_2D_REFERENCE_GRAPH_H_ diff --git a/include/robot_costmap_2d/reference_graph_worker.h b/include/robot_costmap_2d/reference_graph_worker.h new file mode 100644 index 0000000..f7ea970 --- /dev/null +++ b/include/robot_costmap_2d/reference_graph_worker.h @@ -0,0 +1,133 @@ +#ifndef ROBOT_COSTMAP_2D_REFERENCE_GRAPH_WORKER_H_ +#define ROBOT_COSTMAP_2D_REFERENCE_GRAPH_WORKER_H_ + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include + +namespace robot_costmap_2d +{ + +/** @brief Everything the worker reads from the costmap, taken in one short lock. */ +struct ReferenceGraphInput +{ + DirectionGeometry geometry{}; ///< Master grid layout. + std::vector> static_layers; ///< One width*height copy per enabled static layer. + std::vector footprint; ///< [m] Robot footprint. +}; + +enum class ReferenceCaptureStatus +{ + kReady, ///< The input is complete. + kWait, ///< A static layer has not written its map yet. Try again later. + kNoStaticLayer ///< Nothing to build a graph from: a configuration error. +}; + +/** @brief Merge static layer copies into the grid the coarse graph is built from. + * + * A cell is lethal when any layer says so, because virtual walls and forbidden zones are static layers too. It is + * unknown only when every layer says so. Everything else is free: soft values are read from the master at query time. + * @throws std::invalid_argument when the layers differ in size. + */ +std::vector mergeStaticLayers(const std::vector>& layers); + +/** @brief Counters of finished work. */ +struct ReferenceGraphWorkerStats +{ + uint64_t step1_runs = 0; ///< Finished runs of step 1. + uint64_t step2_runs = 0; ///< Finished runs of step 2. + uint64_t published = 0; ///< Graphs that reached kReady. + uint64_t errors = 0; ///< Computations that threw. + double capture_ms_max = 0.0; ///< [ms] Longest wait inside the capture callback, which holds the master mutex. + double step1_ms_last = 0.0; ///< [ms] Duration of the last finished step 1. + double step2_ms_last = 0.0; ///< [ms] Duration of the last finished step 2. +}; + +/** @brief Background thread that keeps the coarse graph in step with the map, the zones and the footprint. + * + * Lock order is master mutex, then the mutex of DirectionalLayer, then the mutex of this class. The notify functions + * may therefore be called while holding the first two. The thread never holds its own mutex while calling a callback. + */ +class ReferenceGraphWorker +{ +public: + struct Source + { + /** Called on the worker thread. Takes the master mutex itself and holds it only for the copy. */ + std::function capture; + /** Called on the worker thread, without the master mutex. */ + std::function direction; + }; + + /** @brief Starts the thread. The first computation starts by itself, so a map that arrived earlier counts. + * @throws std::invalid_argument on bad parameters or a missing callback. */ + ReferenceGraphWorker(Source source, const ReferenceGraphParams& params); + + /** @brief Cancels any computation and joins the thread. */ + ~ReferenceGraphWorker(); + + ReferenceGraphWorker(const ReferenceGraphWorker&) = delete; + ReferenceGraphWorker& operator=(const ReferenceGraphWorker&) = delete; + + /** @brief The static map changed: reruns steps 1 and 2. */ + void notifyStaticChanged(); + /** @brief The direction grid changed: reruns step 2 only. */ + void notifyDirectionChanged(); + /** @brief The footprint changed: reruns step 2 only. */ + void notifyFootprintChanged(); + + /** @brief Consistent snapshot, safe to retain. Takes only this class's mutex, so a planner never waits for the costmap. */ + ReferenceGraphSnapshot snapshot() const; + + ReferenceGraphWorkerStats stats() const; + +private: + enum class Outcome + { + kDone, ///< graph holds a new result. + kWait, ///< An input is not ready yet. + kCancelled, ///< An input changed during the computation. + kFailed ///< It threw. Stay pending until the next change: the same input would throw again. + }; + + void run(); + Outcome compute(uint64_t static_revision, ReferenceGraph* graph); + void markPendingLocked(); + + const Source source_; + const ReferenceGraphParams params_; + + mutable std::mutex mutex_; + std::condition_variable wake_; + bool stop_ = false; + uint64_t static_revision_ = 1; // Starts ahead of handled_, which starts the first computation. + uint64_t step2_revision_ = 1; + uint64_t handled_static_ = 0; + uint64_t handled_step2_ = 0; + ReferenceGraphSnapshot snapshot_; + ReferenceGraphWorkerStats stats_; + std::atomic cancel_{ false }; + + // Used only by the worker thread. + std::vector static_cost_; + DirectionGeometry geometry_{}; + VoronoiSkeleton skeleton_; + bool skeleton_valid_ = false; + uint64_t skeleton_revision_ = 0; + bool no_static_logged_ = false; + + std::thread thread_; // Last member: it starts after everything above exists. +}; + +} // namespace robot_costmap_2d + +#endif // ROBOT_COSTMAP_2D_REFERENCE_GRAPH_WORKER_H_ diff --git a/plugins/directional_layer.cpp b/plugins/directional_layer.cpp index e18e506..4e08be4 100644 --- a/plugins/directional_layer.cpp +++ b/plugins/directional_layer.cpp @@ -84,7 +84,7 @@ void DirectionalLayer::onInitialize() { throw std::runtime_error("DirectionalLayer " + name_ + ": cannot open the default file " + filename); } - if (!std::isfinite(max_deviation_deg) || max_deviation_deg <= 0.0 || max_deviation_deg >= 180.0) + if (!std::isfinite(max_deviation_deg) || max_deviation_deg < 0.0 || max_deviation_deg >= 180.0) throw std::runtime_error("DirectionalLayer " + name_ + ": max_deviation_deg must be finite and in (0, 180)"); if (max_deviation_deg < 22.5) robot::log_warning("DirectionalLayer %s: max_deviation_deg < 22.5 may leave SBPL without a path", name_.c_str()); @@ -121,6 +121,7 @@ void DirectionalLayer::publishLocked(DirectionFieldState state, std::shared_ptr< if (debug_state_) robot::log_info("[debug] DirectionalLayer %s: %s generation=%llu", name_.c_str(), stateName(state), static_cast(snapshot_.generation)); + layered_costmap_->notifyDirectionFieldChanged(); } DirectionFieldSnapshot DirectionalLayer::directionSnapshot() const diff --git a/plugins/static_layer.cpp b/plugins/static_layer.cpp index 69352d2..5d03be5 100755 --- a/plugins/static_layer.cpp +++ b/plugins/static_layer.cpp @@ -177,6 +177,7 @@ void StaticLayer::matchSize() Costmap2D* master = layered_costmap_->getCostmap(); resizeMap(master->getSizeInCellsX(), master->getSizeInCellsY(), master->getResolution(), master->getOriginX(), master->getOriginY()); + layered_costmap_->notifyStaticMapChanged(getType()); } } @@ -305,6 +306,7 @@ void StaticLayer::incomingMap(const robot_nav_msgs::OccupancyGrid& new_map) height_ = size_y_; map_received_ = true; has_updated_data_ = true; + layered_costmap_->notifyStaticMapChanged(getType()); } else { @@ -373,6 +375,7 @@ void StaticLayer::incomingUpdate(const robot_map_msgs::OccupancyGridUpdate& upda height_ = update.height; } has_updated_data_ = true; + layered_costmap_->notifyStaticMapChanged(getType()); } } diff --git a/src/costmap_2d_robot.cpp b/src/costmap_2d_robot.cpp index 86b6a8e..c67b971 100644 --- a/src/costmap_2d_robot.cpp +++ b/src/costmap_2d_robot.cpp @@ -63,7 +63,7 @@ namespace robot_costmap_2d template void move_parameter(robot::NodeHandle& old_h, robot::NodeHandle& new_h, std::string name,T& value) { - if (!old_h.hasParam(name)) + if (new_h.hasParam(name) || !old_h.hasParam(name)) return; // A failed getParam() writes its default (0, false, "") into value; copying that would replace @@ -86,6 +86,17 @@ void move_parameters(robot::NodeHandle& old_h, robot::NodeHandle& new_h, } } +robot::NodeHandle Costmap2DROBOT::commonParametersHandle(robot::NodeHandle& tree_nh) +{ + if (!tree_nh.hasParam("root")) + return tree_nh; + // A scalar or list `root:` would still be selected, and every shared key (sensor sources, zone + // topics, transform_tolerance) would then read as missing. Refuse it instead of running blind. + if (!tree_nh.getParamValue("root").IsMap()) + throw std::invalid_argument("'root' must be a map of shared costmap parameters"); + return robot::NodeHandle("root"); +} + Costmap2DROBOT::Costmap2DROBOT(const std::string& name, tf3::BufferCore& tf) : layered_costmap_(NULL), name_(name), @@ -127,6 +138,27 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name,const std::st YAML::Node layer = config["robot_costmap_2d"]; robot::NodeHandle priv_nh(nh, name); + robot::NodeHandle tree_nh("~"); + const bool rooted = tree_nh.hasParam("root"); + robot::NodeHandle common_nh = commonParametersHandle(tree_nh); + robot::log_info("costmap '%s': shared parameters use %s layout\n", + name.c_str(), rooted ? "root" : "flat"); + if (rooted) + { + std::string ignored_keys; + for (const char* key : {"robot_base_frame", "transform_tolerance", "footprint_padding"}) + { + if (tree_nh.hasParam(key)) + { + if (!ignored_keys.empty()) + ignored_keys += ", "; + ignored_keys += key; + } + } + if (!ignored_keys.empty()) + robot::log_warning("costmap '%s': root layout ignores file-root keys: %s\n", + name.c_str(), ignored_keys.c_str()); + } // A costmap missing a layer, the layers after it or its update thread still looks alive to the // planner, which then drives on a map that never marks obstacles. Refuse to build it instead: @@ -147,8 +179,8 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name,const std::st if (priv_nh.hasParam("global_frame")) priv_nh.getParam("global_frame", global_frame); - if (nh.hasParam("robot_base_frame")) - nh.getParam("robot_base_frame", robot_base_frame); + if (common_nh.hasParam("robot_base_frame")) + common_nh.getParam("robot_base_frame", robot_base_frame); global_frame_ = global_frame; robot_base_frame_ = robot_base_frame; @@ -285,12 +317,11 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name,const std::st } } } - robot::NodeHandle private_nh("~"); for (auto& info : my_list) { try { - copyParentParameters(name_, info.name, info.type, private_nh); + copyParentParameters(name_, info.name, info.type, common_nh, tree_nh); creators_.push_back( boost::dll::import_alias( path_plugins, info.type, boost::dll::load_mode::append_decorations) @@ -318,8 +349,8 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name,const std::st new_footprint = makeFootprintFromParams(priv_nh); } - if (nh.hasParam("transform_tolerance")) - nh.getParam("transform_tolerance", transform_tolerance_); + if (common_nh.hasParam("transform_tolerance")) + common_nh.getParam("transform_tolerance", transform_tolerance_); // robot::log_info("transform_tolerance: %d", transform_tolerance_); setUnpaddedRobotFootprint(new_footprint); @@ -342,8 +373,8 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name,const std::st // If the padding has changed, call setUnpaddedRobotFootprint() to // re-apply the padding. float footprint_padding = loadParam(layer, "footprint_padding", 0.0); - if (nh.hasParam("footprint_padding")) - nh.getParam("footprint_padding", footprint_padding); + if (common_nh.hasParam("footprint_padding")) + common_nh.getParam("footprint_padding", footprint_padding); if (footprint_padding_ != footprint_padding) { footprint_padding_ = footprint_padding; @@ -355,6 +386,40 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name,const std::st priv_nh.getParam("robot_radius", robot_radius); readFootprintFromConfig(new_footprint, unpadded_footprint_, robot_radius); + bool reference_graph_enabled = loadParam(layer, "reference_graph_enabled", false); + if (priv_nh.hasParam("reference_graph_enabled")) + priv_nh.getParam("reference_graph_enabled", reference_graph_enabled); + if (reference_graph_enabled) + { + if (rolling_window) + fail("reference_graph_enabled: true does not work with rolling_window: true"); + ReferenceGraphParams graph_params; + const auto read_length = [&](const char* key, double* value) { + *value = loadParam(layer, key, *value); + if (priv_nh.hasParam(key)) + priv_nh.getParam(key, *value); + }; + read_length("reference_graph_min_clearance_m", &graph_params.min_clearance_m); + read_length("reference_graph_ridge_min_separation_m", &graph_params.ridge_min_separation_m); + read_length("reference_graph_spur_min_length_m", &graph_params.spur_min_length_m); + read_length("reference_graph_lane_offset_step_m", &graph_params.lane_offset_step_m); + graph_params.debug_log = loadParam(layer, "reference_graph_debug_log", graph_params.debug_log); + if (priv_nh.hasParam("reference_graph_debug_log")) + priv_nh.getParam("reference_graph_debug_log", graph_params.debug_log); + const std::string graph_error = validateReferenceGraphParams(graph_params); + if (!graph_error.empty()) + fail("reference_graph: " + graph_error); + if (!layered_costmap_->enableReferenceGraph(graph_params)) + fail("reference_graph: could not start"); + robot::log_info("costmap '%s': reference graph on, min_clearance=%.3f m ridge_separation=%.3f m spur=%.3f m lane_step=%.3f m debug_log=%d\n", + name_.c_str(), graph_params.min_clearance_m, graph_params.ridge_min_separation_m, graph_params.spur_min_length_m, + graph_params.lane_offset_step_m, graph_params.debug_log ? 1 : 0); + } + else + { + robot::log_info("costmap '%s': reference graph off\n", name_.c_str()); + } + // only construct the thread if the frequency is positive if(map_update_frequency > 0.0) map_update_thread_ = new boost::thread(boost::bind(&Costmap2DROBOT::mapUpdateLoop, this, map_update_frequency)); @@ -372,21 +437,27 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name,const std::st void Costmap2DROBOT::copyParentParameters(const std::string& costmap_name, const std::string& plugin_name, const std::string& plugin_type, - robot::NodeHandle& nh) + robot::NodeHandle& source_nh, + robot::NodeHandle& target_nh) { // Step 2 of the layer config flow. A layer reads its default file, then overrides each key found - // in "/". This copies the keys of the shared ":" block there first, so the - // lists below must hold every key the layer reads with hasParam(): a key missing here is ignored - // without a word when it is set in the shared block. A copied key overwrites the same key in - // "/". Types follow what the layer reads. - robot::NodeHandle costmap_nh(nh, costmap_name); + // in "/". Shared ":" values fill only keys that the costmap block + // does not set. The lists must cover every shared key read by the layer, with matching types. + if (!source_nh.hasParam(plugin_name)) + return; + // Child handles fall back to their parent when an intermediate namespace is missing. + if (!target_nh.hasParam(costmap_name)) + target_nh.setParam(costmap_name, YAML::Node(YAML::NodeType::Map)); + robot::NodeHandle costmap_nh(target_nh, costmap_name); robot::NodeHandle costmap_plugin_nh(costmap_nh, plugin_name); - robot::NodeHandle plugin_nh(nh, plugin_name); + robot::NodeHandle plugin_nh(source_nh, plugin_name); // observation_sources, then the keys of each source under "//". const auto move_sources = [&](const auto& move_source_keys) { std::string topics_string; move_parameter(plugin_nh, costmap_plugin_nh, "observation_sources", topics_string); + if (costmap_plugin_nh.hasParam("observation_sources")) + costmap_plugin_nh.getParam("observation_sources", topics_string); std::stringstream ss(topics_string); std::string source; while (ss >> source) @@ -397,7 +468,10 @@ void Costmap2DROBOT::copyParentParameters(const std::string& costmap_name, } }; - if (plugin_type == "StaticLayer") + // PreferredLayer and UnPreferredLayer inherit StaticLayer::getParams(), so they read the same keys. + // Without them here a shared "preferred:" block is ignored and the layer keeps the default + // map_topic "map", i.e. it would consume the static map itself. + if (plugin_type == "StaticLayer" || plugin_type == "PreferredLayer" || plugin_type == "UnPreferredLayer") { move_parameters(plugin_nh, costmap_plugin_nh, {"map_topic", "base_frame_id"}); move_parameters(plugin_nh, costmap_plugin_nh, {"unknown_cost_value", "lethal_cost_threshold"}); @@ -717,7 +791,7 @@ bool Costmap2DROBOT::getRobotPose(robot_geometry_msgs::PoseStamped& global_pose) // check global_pose timeout if (!global_pose.header.stamp.isZero() && current_time.toSec() - global_pose.header.stamp.toSec() > transform_tolerance_) { - robot::log_warning("Costmap2DROBOT %s transform timeout. Current time: %.4f, global_pose stamp: %.4f, tolerance: %.4f\n", name_.c_str(), + robot::log_warning_throttle(1.0,"Costmap2DROBOT %s transform timeout. Current time: %.4f, global_pose stamp: %.4f, tolerance: %.4f\n", name_.c_str(), current_time.toSec(), global_pose.header.stamp.toSec(), transform_tolerance_); return false; } diff --git a/src/layered_costmap.cpp b/src/layered_costmap.cpp index 8316ee1..fb4b297 100755 --- a/src/layered_costmap.cpp +++ b/src/layered_costmap.cpp @@ -37,7 +37,10 @@ *********************************************************************/ #include #include +#include #include +#include +#include #include #include #include @@ -186,6 +189,8 @@ namespace robot_costmap_2d LayeredCostmap::~LayeredCostmap() { + // The worker reads the plugins, so it stops first. + reference_graph_worker_.reset(); while (plugins_.size() > 0) { plugins_.pop_back(); @@ -385,6 +390,88 @@ namespace robot_costmap_2d return result; } + bool LayeredCostmap::enableReferenceGraph(const ReferenceGraphParams& params) + { + if (rolling_window_) + { + robot::log_error("Reference graph needs a static map; it cannot run on a rolling costmap\n"); + return false; + } + if (reference_graph_worker_) + { + robot::log_error("Reference graph is already enabled\n"); + return false; + } + + ReferenceGraphWorker::Source source; + source.capture = [this](bool with_grid, ReferenceGraphInput* input) { + boost::unique_lock lock(*costmap_.getMutex()); + input->geometry = {costmap_.getSizeInCellsX(), costmap_.getSizeInCellsY(), costmap_.getResolution(), + costmap_.getOriginX(), costmap_.getOriginY(), global_frame_}; + input->footprint = footprint_; + if (!with_grid) + return ReferenceCaptureStatus::kReady; + + // Copy under the lock and merge outside it: a large map must not stall the costmap update. + std::vector grids; + for (const auto& plugin : plugins_) + { + if (!plugin->isEnabled() || plugin->getType() != LayerType::STATIC_LAYER) + continue; + const auto* grid = dynamic_cast(plugin.get()); + if (grid == nullptr || !plugin->isCurrent() || grid->getSizeInCellsX() != costmap_.getSizeInCellsX() || + grid->getSizeInCellsY() != costmap_.getSizeInCellsY()) + return ReferenceCaptureStatus::kWait; + grids.push_back(grid); + } + if (grids.empty()) + return ReferenceCaptureStatus::kNoStaticLayer; + const std::size_t cells = static_cast(costmap_.getSizeInCellsX()) * costmap_.getSizeInCellsY(); + if (cells == 0) + return ReferenceCaptureStatus::kWait; + input->static_layers.reserve(grids.size()); + for (const Costmap2D* grid : grids) + input->static_layers.emplace_back(grid->getCharMap(), grid->getCharMap() + cells); + return ReferenceCaptureStatus::kReady; + }; + source.direction = [this]() { return getDirectionFieldSnapshot(); }; + try + { + reference_graph_worker_.reset(new ReferenceGraphWorker(std::move(source), params)); + } + catch (const std::exception& error) + { + robot::log_error("Reference graph not started: %s\n", error.what()); + return false; + } + return true; + } + + ReferenceGraphSnapshot LayeredCostmap::getReferenceGraphSnapshot() const + { + return reference_graph_worker_ ? reference_graph_worker_->snapshot() : ReferenceGraphSnapshot{}; + } + + static_assert(static_cast(LayerType::DEPTH_CAMERA_LAYER) < 16, "grow kMaxLayerTypes"); + + uint64_t LayeredCostmap::getStaticMapRevision(LayerType type) const + { + return static_map_revisions_[static_cast(type)].load(); + } + + void LayeredCostmap::notifyStaticMapChanged(LayerType type) + { + ++static_map_revisions_[static_cast(type)]; + if (type == LayerType::STATIC_LAYER && reference_graph_worker_) + reference_graph_worker_->notifyStaticChanged(); + } + + void LayeredCostmap::notifyDirectionFieldChanged() + { + if (reference_graph_worker_) + reference_graph_worker_->notifyDirectionChanged(); + } + bool LayeredCostmap::isCurrent() { current_ = true; @@ -399,7 +486,16 @@ namespace robot_costmap_2d void LayeredCostmap::setFootprint(const std::vector &footprint_spec) { - footprint_ = footprint_spec; + bool changed = footprint_.size() != footprint_spec.size(); + for (std::size_t i = 0; !changed && i < footprint_.size(); ++i) + changed = footprint_[i].x != footprint_spec[i].x || footprint_[i].y != footprint_spec[i].y; + { + // The reference graph thread copies the footprint under this lock. + boost::unique_lock lock(*costmap_.getMutex()); + footprint_ = footprint_spec; + } + if (changed && reference_graph_worker_) + reference_graph_worker_->notifyFootprintChanged(); robot_costmap_2d::calculateMinAndMaxDistances(footprint_spec, inscribed_radius_, circumscribed_radius_); for (vector>::iterator plugin = plugins_.begin(); plugin != plugins_.end(); diff --git a/src/reference_graph.cpp b/src/reference_graph.cpp new file mode 100644 index 0000000..33e5c35 --- /dev/null +++ b/src/reference_graph.cpp @@ -0,0 +1,979 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +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* 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(geometry.width) + 2) * (static_cast(geometry.height) + 2); + if (padded > static_cast(std::numeric_limits::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(width + 2) * static_cast(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(padded)]; } + uint8_t operator[](int32_t padded) const { return cells_[static_cast(padded)]; } + +private: + int32_t width_, height_, stride_; + std::vector 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 +bool nearestFeature(int32_t width, int32_t height, IsFeature is_feature, std::vector* nearest, + const std::atomic* cancel) +{ + nearest->assign(static_cast(width) * static_cast(height), -1); + std::vector& result = *nearest; + + // Column pass, walked row by row to stay cache friendly on a 3000 x 3000 grid. Holds the feature row. + std::vector column_feature(static_cast(width), -1); + for (int32_t y = 0; y < height; ++y) + { + if (cancelled(cancel)) + return false; + int32_t* row = result.data() + static_cast(y) * width; + for (int32_t x = 0; x < width; ++x) + { + if (is_feature(y * width + x)) + column_feature[static_cast(x)] = y; + row[x] = column_feature[static_cast(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(y) * width; + for (int32_t x = 0; x < width; ++x) + { + if (is_feature(y * width + x)) + column_feature[static_cast(x)] = y; + const int32_t below = column_feature[static_cast(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 feature_row(static_cast(width)); + std::vector envelope(static_cast(width)); + for (int32_t y = 0; y < height; ++y) + { + if (cancelled(cancel)) + return false; + int32_t* row = result.data() + static_cast(y) * width; + std::copy(row, row + width, feature_row.begin()); + const auto squared_row = [&](int32_t x) { + const double dy = feature_row[static_cast(x)] - y; + return dy * dy; + }; + int32_t last = -1; + for (int32_t x = 0; x < width; ++x) + { + if (feature_row[static_cast(x)] < 0) + continue; + const double new_row = squared_row(x); + while (last >= 1) + { + const int32_t middle = envelope[static_cast(last)]; + const int32_t before = envelope[static_cast(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(++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(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(current)]; + row[x] = feature_row[static_cast(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* active, const std::atomic* 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 pending(mask.size(), 0); + for (int32_t cell : *active) + pending[static_cast(cell)] = 3; + + std::vector removal; + while (true) + { + if (cancelled(cancel)) + return false; + bool changed = false; + for (int phase = 0; phase < 2; ++phase) + { + const uint8_t bit = static_cast(1U << phase); + removal.clear(); + for (int32_t cell : *active) + { + uint8_t& flags = pending[static_cast(cell)]; + if ((flags & bit) == 0 || mask[cell] == 0) + continue; + flags = static_cast(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(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* pixels, double resolution, double minimum, + const std::atomic* cancel) +{ + PaddedMask& mask = *mask_ptr; + const int32_t stride = mask.stride(); + const double diagonal = std::hypot(1.0, 1.0); + std::vector path; + std::vector 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(std::min(a, b)); + const uint32_t high = static_cast(std::max(a, b)); + return (static_cast(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(geometry.width); + const int32_t centre_x = static_cast(std::floor((x - geometry.origin_x) / resolution)); + const int32_t centre_y = static_cast(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(y0); iy <= static_cast(y1); ++iy) + { + const uint8_t* row = cost + static_cast(iy) * width; + for (int32_t ix = static_cast(x0); ix <= static_cast(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 cells; +}; + +/** 8-connected regions of equal nonzero code, ordered by direction, then by first cell in raster order. */ +std::vector findZoneRegions(const uint8_t* codes, int32_t width, int32_t height, std::vector* labels) +{ + labels->assign(static_cast(width) * static_cast(height), 0); + std::vector regions; + std::vector 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(seed)] != 0) + continue; + ZoneRegion region; + region.direction_index = static_cast(code - 1); + region.label = ++next_label; + (*labels)[static_cast(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(other)] == 0) + { + (*labels)[static_cast(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 compileRegionLanes(const ZoneRegion& region, const std::vector& 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(geometry.width); + const int32_t height = static_cast(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::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(fy) * width + static_cast(fx); + return labels[static_cast(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 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(scan_count); ++i) + scan.push_back(i == 1 ? scan_start + kLaneScanStepM : scan_start + static_cast(i) * scan_delta); + + std::vector> 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(i); + } + else if (!free && begin >= 0) + { + spans.emplace_back(scan[static_cast(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::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 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(2, static_cast(std::ceil((along_hi - along_lo) / kLaneSampleStepM)) + 1); + const double sample_delta = (along_hi - along_lo) / static_cast(samples - 1); + const auto sample = [&](int64_t i) { + return i == samples - 1 ? along_hi : static_cast(i) * sample_delta + along_lo; + }; + + std::vector 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& lanes, double middle, + double offset_step, std::vector* 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::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* 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(grid.geometry.width); + const int32_t height = static_cast(grid.geometry.height); + const double resolution = grid.geometry.resolution; + const std::size_t cell_count = static_cast(width) * static_cast(height); + const uint8_t* cost = grid.cost; + + VoronoiSkeleton result; + result.geometry = grid.geometry; + + std::vector nearest; + if (!nearestFeature(width, height, [cost](int32_t cell) { return cost[cell] == LETHAL_OBSTACLE; }, &nearest, cancel)) + return result; + + std::vector 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(std::ceil(params.min_clearance_m * 1000.0 - 1e-9)); + PaddedMask mask(width, height); + std::vector 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(cell)]; + bool clear_enough = feature >= 0; + if (grid.clearance_mm != nullptr) + { + clearance_mm[static_cast(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(cell)] = + static_cast(std::min(std::floor(metres * 1000.0), static_cast(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(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().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(mask.y(padded)) * static_cast(width) + static_cast(mask.x(padded))] = 1; + result.clearance_mm = std::move(clearance_mm); + return result; +} + +std::vector computeRegionCentreLine(const std::vector& region_mask, const DirectionGeometry& geometry, + const ReferenceGraphParams& params) +{ + checkParams(params); + checkGeometry(geometry); + const int32_t width = static_cast(geometry.width); + const int32_t height = static_cast(geometry.height); + if (region_mask.size() != static_cast(width) * static_cast(height)) + throw std::invalid_argument("reference_graph: region mask size does not match the geometry"); + + std::vector 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(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 crop(static_cast(crop_width) * static_cast(crop_height), 0); + for (int32_t y = 0; y < crop_height; ++y) + for (int32_t x = 0; x < crop_width; ++x) + crop[static_cast(y * crop_width + x)] = + region_mask[static_cast((y + crop_y) * width + x + crop_x)] != 0 ? 1 : 0; + + std::vector nearest; + nearestFeature(crop_width, crop_height, [&crop](int32_t cell) { return crop[static_cast(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 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(cell)] == 0) + continue; + const int32_t feature = nearest[static_cast(cell)]; + const auto separated = [&](int32_t other) { + const int32_t other_feature = nearest[static_cast(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((mask.y(padded) + crop_y) * width + mask.x(padded) + crop_x)] = 1; + return result; +} + +void extractVoronoiEdges(const std::vector& skeleton_mask, const uint8_t* direction_codes, + const DirectionGeometry& geometry, const std::vector* clearance_mm, + std::vector* nodes, std::vector* edges, + const std::atomic* cancel) +{ + checkGeometry(geometry); + if (nodes == nullptr || edges == nullptr) + throw std::invalid_argument("reference_graph: null output"); + const int32_t width = static_cast(geometry.width); + const int32_t height = static_cast(geometry.height); + const std::size_t cell_count = static_cast(width) * static_cast(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 pixels; + for (int32_t y = 0; y < height; ++y) + { + for (int32_t x = 0; x < width; ++x) + { + if (skeleton_mask[static_cast(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 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 node_of; + const auto node_index = [&](int32_t padded) { + const auto inserted = node_of.emplace(padded, static_cast(nodes->size())); + if (inserted.second) + nodes->push_back(world(padded)); + return inserted.first->second; + }; + + std::unordered_set visited; + visited.reserve(pixels.size() * 2); + std::vector 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::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(mask.y(chain[k])) * static_cast(width) + + static_cast(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& footprint, + const ReferenceGraphParams& params, const std::atomic* 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(grid.geometry.width); + const int32_t height = static_cast(grid.geometry.height); + const std::size_t cell_count = static_cast(width) * static_cast(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 labels; + const std::vector 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 candidates = + compileRegionLanes(regions[i], labels, grid.cost, grid.geometry, half_x, half_y, params.lane_offset_step_m, &preferred); + selectLanes(regions[i], static_cast(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 diff --git a/src/reference_graph_worker.cpp b/src/reference_graph_worker.cpp new file mode 100644 index 0000000..8e9169c --- /dev/null +++ b/src/reference_graph_worker.cpp @@ -0,0 +1,297 @@ +#include + +#include +#include +#include +#include +#include +#include + +#ifdef __linux__ +#include +#include +#include +#endif + +#include + +#include + +namespace robot_costmap_2d +{ +namespace +{ + +using Clock = std::chrono::steady_clock; + +// While an input is not ready the thread takes the master mutex this often. It sleeps for good once the graph is ready. +constexpr std::chrono::milliseconds kRetryPeriod(200); +// The NUC has 2 cores, and this thread must not take time from the control loop or the sensors. +constexpr int kThreadNice = 10; + +double msSince(Clock::time_point begin) { return std::chrono::duration(Clock::now() - begin).count(); } + +void lowerThreadPriority() +{ +#ifdef __linux__ + // Without this the graph still comes out, only the control loop may feel it, so a refusal is not an error. + if (setpriority(PRIO_PROCESS, static_cast(syscall(SYS_gettid)), kThreadNice) != 0) + robot::log_warning("ReferenceGraphWorker: could not lower the thread priority\n"); +#endif +} + +bool sameGeometry(const DirectionGeometry& a, const DirectionGeometry& b) +{ + return a.width == b.width && a.height == b.height && a.resolution == b.resolution && a.origin_x == b.origin_x && + a.origin_y == b.origin_y && a.frame_id == b.frame_id; +} + +} // namespace + +std::vector mergeStaticLayers(const std::vector>& layers) +{ + if (layers.empty()) + return {}; + const std::size_t count = layers.front().size(); + for (const std::vector& layer : layers) + if (layer.size() != count) + throw std::invalid_argument("reference_graph: static layers differ in size"); + + std::vector merged(count, NO_INFORMATION); + for (const std::vector& layer : layers) + { + for (std::size_t i = 0; i < count; ++i) + { + if (layer[i] == LETHAL_OBSTACLE) + merged[i] = LETHAL_OBSTACLE; + else if (layer[i] != NO_INFORMATION && merged[i] == NO_INFORMATION) + merged[i] = FREE_SPACE; + } + } + return merged; +} + +ReferenceGraphWorker::ReferenceGraphWorker(Source source, const ReferenceGraphParams& params) + : source_(std::move(source)), params_(params) +{ + const std::string error = validateReferenceGraphParams(params_); + if (!error.empty()) + throw std::invalid_argument("reference_graph: " + error); + if (!source_.capture || !source_.direction) + throw std::invalid_argument("reference_graph: missing source callback"); + snapshot_.state = ReferenceGraphState::kPending; + snapshot_.generation = 1; + thread_ = std::thread(&ReferenceGraphWorker::run, this); +} + +ReferenceGraphWorker::~ReferenceGraphWorker() +{ + { + std::lock_guard lock(mutex_); + stop_ = true; + cancel_.store(true, std::memory_order_relaxed); + } + wake_.notify_all(); + thread_.join(); +} + +void ReferenceGraphWorker::markPendingLocked() +{ + // Drop the old graph at once: it may hold the wrong map or the wrong zones, and the backup planner can run meanwhile. + if (snapshot_.state != ReferenceGraphState::kPending) + { + snapshot_.state = ReferenceGraphState::kPending; + snapshot_.graph.reset(); + ++snapshot_.generation; + } + cancel_.store(true, std::memory_order_relaxed); +} + +void ReferenceGraphWorker::notifyStaticChanged() +{ + { + std::lock_guard lock(mutex_); + ++static_revision_; + markPendingLocked(); + } + wake_.notify_all(); +} + +void ReferenceGraphWorker::notifyDirectionChanged() +{ + { + std::lock_guard lock(mutex_); + ++step2_revision_; + markPendingLocked(); + } + wake_.notify_all(); +} + +void ReferenceGraphWorker::notifyFootprintChanged() { notifyDirectionChanged(); } + +ReferenceGraphSnapshot ReferenceGraphWorker::snapshot() const +{ + std::lock_guard lock(mutex_); + return snapshot_; +} + +ReferenceGraphWorkerStats ReferenceGraphWorker::stats() const +{ + std::lock_guard lock(mutex_); + return stats_; +} + +ReferenceGraphWorker::Outcome ReferenceGraphWorker::compute(uint64_t static_revision, ReferenceGraph* graph) +{ + const bool need_step1 = !skeleton_valid_ || skeleton_revision_ != static_revision; + + ReferenceGraphInput input; + const Clock::time_point capture_began = Clock::now(); + const ReferenceCaptureStatus status = source_.capture(need_step1, &input); + const double capture_ms = msSince(capture_began); + { + std::lock_guard lock(mutex_); + stats_.capture_ms_max = std::max(stats_.capture_ms_max, capture_ms); + } + if (status == ReferenceCaptureStatus::kNoStaticLayer) + { + if (!no_static_logged_) + robot::log_error("ReferenceGraphWorker: reference_graph_enabled is true but no static layer is enabled\n"); + no_static_logged_ = true; + return Outcome::kWait; + } + if (status != ReferenceCaptureStatus::kReady) + return Outcome::kWait; + no_static_logged_ = false; + + ReferenceGridView view; + if (need_step1) + { + skeleton_valid_ = false; + static_cost_ = mergeStaticLayers(input.static_layers); + input.static_layers.clear(); + geometry_ = input.geometry; + view.cost = static_cost_.data(); + view.geometry = geometry_; + const Clock::time_point began = Clock::now(); + skeleton_ = computeVoronoiSkeleton(view, params_, &cancel_); + if (cancel_.load(std::memory_order_relaxed)) + return Outcome::kCancelled; + skeleton_valid_ = true; + skeleton_revision_ = static_revision; + std::lock_guard lock(mutex_); + ++stats_.step1_runs; + stats_.step1_ms_last = msSince(began); + } + + const DirectionFieldSnapshot direction = source_.direction(); + if (direction.state == DirectionFieldState::kPending) + return Outcome::kWait; + std::vector codes; + if (direction.state == DirectionFieldState::kReady && direction.field != nullptr) + { + // A grid for another map layout belongs to the previous map. The new one is on its way. + if (!sameGeometry(direction.field->geometry(), geometry_)) + return Outcome::kWait; + if (direction.field->hasConstraints()) + { + codes.resize(static_cast(geometry_.width) * geometry_.height); + for (uint32_t y = 0; y < geometry_.height; ++y) + { + if (cancel_.load(std::memory_order_relaxed)) + return Outcome::kCancelled; + for (uint32_t x = 0; x < geometry_.width; ++x) + codes[static_cast(y) * geometry_.width + x] = direction.field->code(x, y); + } + } + } + + view.cost = static_cost_.data(); + view.geometry = geometry_; + view.direction_codes = codes.empty() ? nullptr : codes.data(); + const Clock::time_point began = Clock::now(); + *graph = buildReferenceGraph(view, skeleton_, input.footprint, params_, &cancel_); + if (cancel_.load(std::memory_order_relaxed)) + return Outcome::kCancelled; + graph->direction_generation = direction.generation; + std::lock_guard lock(mutex_); + ++stats_.step2_runs; + stats_.step2_ms_last = msSince(began); + return Outcome::kDone; +} + +void ReferenceGraphWorker::run() +{ + lowerThreadPriority(); + while (true) + { + uint64_t static_revision = 0; + uint64_t step2_revision = 0; + { + std::unique_lock lock(mutex_); + wake_.wait(lock, [this]() { return stop_ || static_revision_ != handled_static_ || step2_revision_ != handled_step2_; }); + if (stop_) + return; + static_revision = static_revision_; + step2_revision = step2_revision_; + cancel_.store(false, std::memory_order_relaxed); + } + + ReferenceGraph graph; + Outcome outcome = Outcome::kFailed; + std::string failure; + try + { + outcome = compute(static_revision, &graph); + } + catch (const std::exception& error) + { + failure = error.what(); + } + catch (...) + { + failure = "unknown exception"; + } + // An exception here must not take the whole navigation process down. The planner keeps failing over to its backup. + if (outcome == Outcome::kFailed) + robot::log_error("ReferenceGraphWorker: computation failed, staying pending until the next change: %s\n", failure.c_str()); + + std::unique_lock lock(mutex_); + if (stop_) + return; + if (outcome == Outcome::kFailed) + ++stats_.errors; + if (static_revision_ != static_revision || step2_revision_ != step2_revision) + continue; // Three maps in a row compute only the last one. + if (outcome == Outcome::kCancelled) + continue; + if (outcome == Outcome::kWait) + { + wake_.wait_for(lock, kRetryPeriod, [&]() { + return stop_ || static_revision_ != static_revision || step2_revision_ != step2_revision; + }); + continue; + } + handled_static_ = static_revision; + handled_step2_ = step2_revision; + if (outcome != Outcome::kDone) + continue; + + const std::size_t nodes = graph.nodes.size(); + const std::size_t edges = graph.edges.size(); + const std::size_t lanes = graph.lanes.size(); + snapshot_.state = ReferenceGraphState::kReady; + snapshot_.graph = std::make_shared(std::move(graph)); + ++snapshot_.generation; + ++stats_.published; + const ReferenceGraphWorkerStats stats = stats_; + const uint64_t generation = snapshot_.generation; + lock.unlock(); + if (params_.debug_log) + robot::log_info("[debug] ReferenceGraph ready: generation=%llu nodes=%zu edges=%zu lanes=%zu step1_ms=%.0f step2_ms=%.0f capture_ms_max=%.1f\n", + static_cast(generation), nodes, edges, lanes, stats.step1_ms_last, stats.step2_ms_last, + stats.capture_ms_max); + } +} + +} // namespace robot_costmap_2d diff --git a/test/costmap_common_root_test.cpp b/test/costmap_common_root_test.cpp new file mode 100644 index 0000000..e322313 --- /dev/null +++ b/test/costmap_common_root_test.cpp @@ -0,0 +1,98 @@ +#include + +#include +#include +#include + +#include + +namespace +{ +using robot_costmap_2d::Costmap2DROBOT; + +TEST(CostmapCommonParameters, SelectAndCopySharedValues) +{ + const char* layout = std::getenv("COSTMAP_TEST_LAYOUT"); + ASSERT_NE(layout, nullptr); + const std::string expected_layout(layout); + ASSERT_TRUE(expected_layout == "rooted" || expected_layout == "flat"); + ASSERT_NE(std::getenv("PNKX_NAV_CORE_CONFIG_DIR"), nullptr); + + robot::NodeHandle tree_nh("~"); + EXPECT_EQ(tree_nh.hasParam("root"), expected_layout == "rooted"); + robot::NodeHandle common_nh = Costmap2DROBOT::commonParametersHandle(tree_nh); + + double tolerance = 0.0; + ASSERT_TRUE(common_nh.getParam("transform_tolerance", tolerance)); + EXPECT_DOUBLE_EQ(tolerance, 1.0); + std::string frame; + ASSERT_TRUE(common_nh.getParam("robot_base_frame", frame)); + EXPECT_EQ(frame, "base_link"); + + Costmap2DROBOT::copyParentParameters("local_costmap", "obstacles", "VoxelLayer", common_nh, tree_nh); + Costmap2DROBOT::copyParentParameters("global_costmap", "obstacles", "VoxelLayer", common_nh, tree_nh); + Costmap2DROBOT::copyParentParameters("local_costmap", "forbidden", "StaticLayer", common_nh, tree_nh); + Costmap2DROBOT::copyParentParameters("global_costmap", "preferred", "PreferredLayer", common_nh, tree_nh); + + std::string value; + ASSERT_TRUE(tree_nh.getParam("local_costmap/obstacles/observation_sources", value)); + EXPECT_EQ(value, "f_scan b_scan"); + ASSERT_TRUE(tree_nh.getParam("local_costmap/obstacles/f_scan/topic", value)); + EXPECT_EQ(value, "/f_scan"); + ASSERT_TRUE(tree_nh.getParam("local_costmap/forbidden/map_topic", value)); + EXPECT_EQ(value, "forbidden"); + ASSERT_TRUE(tree_nh.getParam("global_costmap/preferred/map_topic", value)); + EXPECT_EQ(value, "preferred"); + + int voxels = 0; + double resolution = 0.0; + ASSERT_TRUE(tree_nh.getParam("global_costmap/obstacles/z_voxels", voxels)); + EXPECT_EQ(voxels, 10); + ASSERT_TRUE(tree_nh.getParam("global_costmap/obstacles/z_resolution", resolution)); + EXPECT_DOUBLE_EQ(resolution, 0.2); + ASSERT_TRUE(tree_nh.getParam("local_costmap/obstacles/z_voxels", voxels)); + EXPECT_EQ(voxels, 8); + ASSERT_TRUE(tree_nh.getParam("local_costmap/obstacles/z_resolution", resolution)); + EXPECT_DOUBLE_EQ(resolution, 0.15); +} + +TEST(CostmapCommonParameters, PreservesSourceOverridesAndFillsMissingSourceKeys) +{ + robot::NodeHandle tree_nh("~"); + robot::NodeHandle common_nh = Costmap2DROBOT::commonParametersHandle(tree_nh); + Costmap2DROBOT::copyParentParameters("override_costmap", "obstacles", "VoxelLayer", common_nh, tree_nh); + + std::string value; + ASSERT_TRUE(tree_nh.getParam("override_costmap/obstacles/observation_sources", value)); + EXPECT_EQ(value, "b_scan"); + ASSERT_TRUE(tree_nh.getParam("override_costmap/obstacles/b_scan/topic", value)); + EXPECT_EQ(value, "/local_override"); + ASSERT_TRUE(tree_nh.getParam("override_costmap/obstacles/b_scan/data_type", value)); + EXPECT_EQ(value, "LaserScan"); + EXPECT_FALSE(tree_nh.hasParam("override_costmap/obstacles/f_scan/topic")); +} + +TEST(CostmapCommonParameters, RejectsInvalidSharedTypeOnlyWhenCopied) +{ + robot::NodeHandle tree_nh("~"); + robot::NodeHandle common_nh = Costmap2DROBOT::commonParametersHandle(tree_nh); + EXPECT_THROW(Costmap2DROBOT::copyParentParameters("invalid_costmap", "bad_obstacles", "VoxelLayer", + common_nh, tree_nh), std::invalid_argument); + EXPECT_NO_THROW(Costmap2DROBOT::copyParentParameters("protected_costmap", "bad_obstacles", "VoxelLayer", + common_nh, tree_nh)); + int voxels = 0; + ASSERT_TRUE(tree_nh.getParam("protected_costmap/bad_obstacles/z_voxels", voxels)); + EXPECT_EQ(voxels, 12); +} + +TEST(CostmapCommonParameters, CreatesMissingCostmapNamespace) +{ + robot::NodeHandle tree_nh("~"); + robot::NodeHandle common_nh = Costmap2DROBOT::commonParametersHandle(tree_nh); + ASSERT_FALSE(tree_nh.hasParam("missing_costmap")); + Costmap2DROBOT::copyParentParameters("missing_costmap", "forbidden", "StaticLayer", common_nh, tree_nh); + std::string topic; + ASSERT_TRUE(tree_nh.getParam("missing_costmap/forbidden/map_topic", topic)); + EXPECT_EQ(topic, "forbidden"); +} +} // namespace diff --git a/test/data/costmap_common_root/flat/params.yaml b/test/data/costmap_common_root/flat/params.yaml new file mode 100644 index 0000000..042686a --- /dev/null +++ b/test/data/costmap_common_root/flat/params.yaml @@ -0,0 +1,30 @@ +robot_base_frame: base_link +transform_tolerance: 1.0 +footprint_padding: 0.0 +forbidden: + map_topic: forbidden + use_maximum: true +preferred: + map_topic: preferred +obstacles: + z_voxels: 8 + z_resolution: 0.15 + observation_sources: f_scan b_scan + f_scan: {topic: /f_scan, data_type: LaserScan, marking: true} + b_scan: {topic: /b_scan, data_type: LaserScan, clearing: true} +bad_obstacles: + z_voxels: invalid_integer +global_costmap: + obstacles: {enabled: false, z_voxels: 10, z_resolution: 0.2} + preferred: {} +local_costmap: + obstacles: {enabled: true} + forbidden: {} +override_costmap: + obstacles: + observation_sources: b_scan + b_scan: {topic: /local_override} +invalid_costmap: + bad_obstacles: {} +protected_costmap: + bad_obstacles: {z_voxels: 12} diff --git a/test/data/costmap_common_root/rooted/params.yaml b/test/data/costmap_common_root/rooted/params.yaml new file mode 100644 index 0000000..a8b8637 --- /dev/null +++ b/test/data/costmap_common_root/rooted/params.yaml @@ -0,0 +1,35 @@ +root: + robot_base_frame: base_link + transform_tolerance: 1.0 + footprint_padding: 0.0 + forbidden: + map_topic: forbidden + use_maximum: true + preferred: + map_topic: preferred + obstacles: + z_voxels: 8 + z_resolution: 0.15 + observation_sources: f_scan b_scan + f_scan: {topic: /f_scan, data_type: LaserScan, marking: true} + b_scan: {topic: /b_scan, data_type: LaserScan, clearing: true} + bad_obstacles: + z_voxels: invalid_integer +robot_base_frame: ignored_frame +transform_tolerance: 9.0 +footprint_padding: 9.0 +obstacles: {z_voxels: 99} +global_costmap: + obstacles: {enabled: false, z_voxels: 10, z_resolution: 0.2} + preferred: {} +local_costmap: + obstacles: {enabled: true} + forbidden: {} +override_costmap: + obstacles: + observation_sources: b_scan + b_scan: {topic: /local_override} +invalid_costmap: + bad_obstacles: {} +protected_costmap: + bad_obstacles: {z_voxels: 12} diff --git a/test/data/reference_graph/corridor.fixture b/test/data/reference_graph/corridor.fixture new file mode 100644 index 0000000..7cf37b3 --- /dev/null +++ b/test/data/reference_graph/corridor.fixture @@ -0,0 +1,17 @@ +reference_graph_fixture 1 +size 200 60 +resolution 0.05 +origin -2.5 1.25 +params 0.335 0.7 1.0 0.5 0.3 0.3 +cost 3 +254 2000 60 8000 254 2000 +direction 1 +0 12000 +skeleton 200 +5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 +nodes 2 +-2.475 2.725 +7.475000000000001 2.725 +edges 1 +0 1 41 -2.475 2.725 -2.225 2.725 -1.975 2.725 -1.725 2.725 -1.4749999999999999 2.725 -1.2249999999999999 2.725 -0.9749999999999999 2.725 -0.7249999999999999 2.725 -0.4750000000000001 2.725 -0.2250000000000001 2.725 0.025000000000000355 2.725 0.27500000000000036 2.725 0.5250000000000004 2.725 0.7750000000000004 2.725 1.0250000000000004 2.725 1.2750000000000004 2.725 1.5250000000000004 2.725 1.7750000000000004 2.725 2.0250000000000004 2.725 2.2750000000000004 2.725 2.5250000000000004 2.725 2.7750000000000004 2.725 3.0250000000000004 2.725 3.2750000000000004 2.725 3.5250000000000004 2.725 3.7750000000000004 2.725 4.025 2.725 4.275 2.725 4.525 2.725 4.775 2.725 5.025 2.725 5.275 2.725 5.525 2.725 5.775 2.725 6.025 2.725 6.275 2.725 6.525 2.725 6.775 2.725 7.025 2.725 7.275 2.725 7.475000000000001 2.725 +lanes 0 diff --git a/test/data/reference_graph/crop.fixture b/test/data/reference_graph/crop.fixture new file mode 100644 index 0000000..b3c6f1b --- /dev/null +++ b/test/data/reference_graph/crop.fixture @@ -0,0 +1,64 @@ +reference_graph_fixture 1 +size 240 240 +resolution 0.05 +origin -15.050015000000002 -19.100015 +params 0.335 0.7 1.0 0.5 0.3 0.3 +cost 423 +60 11567 254 1 60 11 254 2 60 10 254 3 60 187 254 5 60 7 254 5 60 7 254 5 60 8 254 5 60 7 254 5 60 185 254 2 60 1 254 4 60 5 254 7 60 5 254 3 60 1 254 3 60 6 254 2 60 2 254 3 60 5 254 2 60 3 254 2 60 183 254 2 60 4 254 2 60 5 254 1 60 4 254 2 60 5 254 1 60 5 254 1 60 6 254 1 60 4 254 2 60 5 254 1 60 4 254 2 60 183 254 2 60 4 254 2 60 5 254 1 60 4 254 2 60 5 254 1 60 5 254 1 60 5 254 2 60 4 254 2 60 4 254 2 60 4 254 2 60 183 254 2 60 4 254 2 60 4 254 2 60 4 254 2 60 5 254 1 60 4 254 2 60 5 254 2 60 4 254 1 60 6 254 1 60 4 254 2 60 183 254 3 60 2 254 3 60 5 254 2 60 2 254 3 60 5 254 2 60 2 254 3 60 6 254 2 60 2 254 2 60 6 254 6 60 185 254 6 60 6 254 6 60 7 254 5 60 7 254 6 60 7 254 4 60 187 254 4 60 9 254 3 60 9 254 2 60 11 254 2 60 1210 254 4 60 234 254 2 60 2 254 3 60 233 254 1 60 4 254 2 60 233 254 1 60 4 254 2 60 232 254 2 60 4 254 2 60 233 254 2 60 2 254 3 60 233 254 6 60 235 254 4 60 1197 254 3 60 236 254 2 60 1 254 2 60 234 254 2 60 3 254 2 60 233 254 1 60 4 254 2 60 233 254 1 60 4 254 2 60 233 254 2 60 3 254 2 60 233 254 6 60 235 254 5 60 10797 254 1 60 237 254 5 60 234 254 2 60 1 254 1 60 1 254 2 60 233 254 2 60 1 254 4 60 233 254 2 60 1 254 2 60 1 254 2 60 232 254 2 60 1 254 1 60 1 254 2 60 233 254 7 60 234 254 5 60 236 254 3 60 1197 254 3 60 236 254 6 60 233 254 2 60 1 254 4 60 233 254 2 60 1 254 2 60 1 254 2 60 163 254 10 60 59 254 2 60 1 254 2 60 1 254 2 60 163 254 2 60 6 254 2 60 59 254 2 60 1 254 1 60 1 254 2 60 173 254 2 60 58 254 7 60 173 254 2 60 59 254 5 60 166 254 1 60 7 254 2 60 238 254 2 60 238 254 2 60 238 254 2 60 237 254 3 60 237 254 3 60 60 254 4 60 173 254 3 60 59 254 6 60 173 254 2 60 58 254 2 60 1 254 5 60 171 254 3 60 58 254 2 60 2 254 4 60 172 254 2 60 58 254 2 60 1 254 4 60 172 254 3 60 58 254 7 60 173 254 2 60 59 254 5 60 174 254 2 60 60 254 3 60 174 254 3 60 237 254 3 60 237 254 3 60 237 254 3 60 237 254 3 60 61 254 2 60 174 254 3 60 60 254 5 60 172 254 3 60 58 254 2 60 2 254 3 60 172 254 3 60 58 254 2 60 1 254 5 60 171 254 3 60 58 254 1 60 1 254 1 60 1 254 1 60 1 254 2 60 171 254 3 60 58 254 2 60 1 254 4 60 172 254 3 60 58 254 7 60 173 254 2 60 59 254 5 60 174 254 2 60 61 254 1 60 176 254 2 60 238 254 2 60 237 254 3 60 229 254 10 60 230 254 9 60 63 254 3 60 235 254 6 60 233 254 2 60 2 254 4 60 232 254 2 60 2 254 4 60 232 254 2 60 3 254 3 60 232 254 3 60 1 254 3 60 233 254 7 60 234 254 5 60 1197 254 4 60 234 254 3 60 1 254 3 60 233 254 2 60 3 254 2 60 232 254 2 60 1 254 1 60 2 254 2 60 232 254 2 60 3 254 3 60 232 254 3 60 2 254 3 60 233 254 6 60 235 254 5 60 10724 +direction 1031 +5 77 0 163 5 77 0 163 5 77 0 163 5 77 0 163 5 77 0 163 5 77 0 163 5 77 0 163 5 77 0 163 5 77 0 163 5 77 0 163 5 77 0 163 5 77 0 163 5 77 0 163 5 77 0 163 5 77 0 163 5 77 0 163 5 77 0 163 5 77 0 163 5 77 0 163 5 77 0 163 5 77 0 163 5 77 0 163 5 77 0 163 5 77 0 163 5 77 0 163 5 77 0 163 5 77 0 163 5 77 0 163 5 77 0 163 5 77 0 163 5 77 0 163 5 77 0 163 5 77 0 163 5 77 0 163 5 77 0 163 5 77 0 163 5 77 0 163 5 77 0 163 5 77 0 163 5 77 0 163 5 77 0 163 5 77 0 163 5 77 0 846 3 37 0 203 3 55 0 66 7 114 0 5 3 55 0 66 7 114 0 5 3 55 0 66 7 114 0 5 3 55 0 66 7 114 0 5 3 55 0 66 7 114 0 5 3 55 0 66 7 114 0 5 3 55 0 66 7 114 0 5 3 55 0 66 7 114 0 5 3 55 0 66 7 114 0 5 3 55 0 66 7 114 0 5 3 55 0 66 7 114 0 5 3 55 0 66 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 66 1 12 0 6 7 114 0 5 3 37 0 66 1 12 0 6 7 114 0 5 3 37 0 66 1 12 0 6 7 114 0 5 3 37 0 66 1 12 0 6 7 114 0 5 3 37 0 66 1 12 0 6 7 114 0 5 3 37 0 66 1 12 0 6 7 114 0 5 3 37 0 66 1 12 0 6 7 114 0 5 3 37 0 66 1 12 0 6 7 114 0 5 3 37 0 66 1 12 0 6 7 114 0 5 3 37 0 66 1 12 0 6 7 114 0 5 3 37 0 66 1 12 0 6 7 114 0 5 3 37 0 66 1 12 0 6 7 114 0 5 3 37 0 66 1 12 0 6 7 114 0 5 3 37 0 66 1 12 0 6 7 114 0 5 3 37 0 66 1 12 0 6 7 114 0 5 3 37 0 66 1 12 0 6 7 114 0 5 3 37 0 66 1 12 0 6 7 114 0 5 3 37 0 66 1 12 0 6 7 114 0 5 3 37 0 66 1 12 0 6 7 114 0 5 3 37 0 66 1 12 0 6 7 114 0 5 3 37 0 66 1 12 0 6 7 114 0 5 3 37 0 66 1 12 0 6 7 114 0 5 3 37 0 66 1 12 0 6 7 114 0 5 3 37 0 66 1 12 0 6 7 114 0 5 3 37 0 66 1 12 0 6 7 114 0 5 3 37 0 66 1 12 0 6 7 114 0 5 3 37 0 66 1 12 0 6 7 114 0 5 3 37 0 66 1 12 0 6 7 114 0 5 3 37 0 66 1 12 0 6 7 114 0 5 3 37 0 66 1 12 0 6 7 114 0 5 3 37 0 66 1 12 0 6 7 114 0 5 3 37 0 66 1 12 0 6 7 114 0 5 3 37 0 66 1 12 0 6 7 114 0 5 3 37 0 66 1 12 0 6 7 114 0 5 3 37 0 66 1 12 0 6 7 114 0 5 3 37 0 66 1 12 0 6 7 114 0 5 3 37 0 66 1 12 0 6 7 114 0 5 3 37 0 66 1 12 0 6 7 114 0 5 3 37 0 66 1 12 0 6 7 114 0 5 3 37 0 66 1 12 0 6 7 114 0 5 3 37 0 66 1 12 0 6 7 114 0 5 3 37 0 66 1 12 0 6 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 84 7 114 0 5 3 37 0 66 5 12 0 6 7 114 0 5 3 37 0 66 5 12 0 6 7 114 0 5 3 37 0 66 5 12 0 6 7 114 0 5 3 37 0 66 5 12 0 6 7 114 0 5 3 37 0 66 5 12 0 6 7 114 0 5 3 37 0 66 5 12 0 6 7 114 0 5 3 37 0 66 5 12 0 6 7 114 0 5 3 37 0 66 5 12 0 6 7 114 0 5 3 37 0 66 5 12 0 6 7 114 0 5 3 37 0 66 5 12 0 6 7 114 0 5 3 37 0 66 5 12 0 6 7 114 0 5 3 37 0 66 5 12 0 6 7 114 0 5 3 37 0 66 5 12 0 6 7 114 0 5 3 37 0 66 5 12 0 6 7 114 0 5 3 37 0 66 5 12 0 6 7 114 0 5 3 37 0 66 5 12 0 6 7 114 0 5 3 37 0 66 5 12 0 6 7 114 0 5 3 37 0 66 5 12 0 6 7 114 0 5 3 37 0 66 5 12 0 6 7 114 0 5 3 37 0 66 5 12 0 6 7 114 0 5 3 37 0 66 5 12 0 6 7 114 0 5 3 37 0 66 5 12 0 6 7 114 0 5 3 37 0 66 5 12 0 6 7 114 0 5 3 37 0 66 5 12 0 6 7 114 0 5 3 37 0 66 5 12 0 6 7 114 0 5 3 37 0 66 5 12 0 6 7 114 0 5 3 37 0 66 5 12 0 6 7 114 0 5 3 37 0 66 5 12 0 6 7 114 0 5 3 37 0 66 5 12 0 6 7 114 0 5 3 37 0 66 5 12 0 6 7 114 0 5 3 37 0 66 5 12 0 6 7 114 0 5 3 37 0 66 5 12 0 6 7 114 0 5 3 37 0 66 5 12 0 6 7 114 0 5 3 37 0 66 5 12 0 6 7 114 0 5 3 37 0 66 5 12 0 6 7 114 0 5 3 37 0 66 5 12 0 6 7 114 0 5 3 37 0 66 5 12 0 6 7 114 0 5 3 37 0 66 5 12 0 6 7 114 0 5 3 37 0 66 5 12 0 6 7 114 0 5 3 37 0 66 5 12 0 6 7 114 0 5 3 37 0 66 5 12 0 6 7 114 0 5 3 37 0 66 5 12 0 6 7 114 0 5 3 37 0 66 5 12 0 6 7 114 0 5 3 37 +skeleton 422 +17093 17332 17571 17810 18049 18288 18527 18767 19006 19245 19484 19723 19962 20201 20440 20679 20918 21158 21397 21636 21876 22115 22354 22594 22833 23040 23041 23042 23072 23282 23283 23284 23285 23286 23287 23312 23527 23528 23529 23530 23531 23532 23533 23534 23535 23551 23775 23776 23777 23778 23779 23780 23781 23782 23790 24022 24023 24024 24025 24026 24027 24030 24204 24205 24206 24207 24208 24209 24210 24211 24212 24213 24214 24215 24216 24217 24218 24219 24220 24221 24222 24223 24224 24225 24226 24227 24228 24229 24230 24231 24232 24233 24234 24235 24236 24237 24238 24239 24267 24268 24269 24270 24393 24394 24395 24396 24397 24398 24399 24400 24401 24402 24403 24404 24405 24406 24407 24408 24409 24410 24411 24412 24413 24414 24415 24416 24417 24418 24419 24420 24421 24422 24423 24424 24425 24426 24427 24428 24429 24430 24431 24432 24433 24434 24435 24436 24437 24438 24439 24440 24441 24442 24443 24510 24511 24540 24541 24542 24543 24544 24545 24546 24547 24548 24549 24550 24551 24552 24553 24554 24555 24556 24557 24558 24559 24560 24561 24562 24563 24564 24579 24580 24581 24582 24583 24584 24585 24586 24587 24588 24589 24590 24591 24592 24593 24594 24595 24596 24597 24598 24599 24600 24601 24602 24603 24604 24605 24606 24607 24608 24609 24610 24611 24612 24613 24614 24615 24616 24617 24618 24619 24620 24621 24622 24623 24624 24625 24626 24627 24628 24629 24630 24631 24632 24751 24752 24753 24754 24755 24756 24757 24758 24759 24760 24761 24762 24763 24764 24765 24766 24767 24768 24769 24770 24771 24772 24773 24774 24775 24776 24777 24778 24779 24804 24805 24806 24807 24808 24809 24810 24811 24812 24813 24814 24815 24816 24817 24818 24991 25231 25471 25472 25712 25952 26192 26432 26433 26673 26913 27153 27393 27394 27634 27874 28114 28354 28355 28595 28835 29075 29315 29316 29556 29796 30036 30276 30277 30517 30757 30997 31237 31238 31478 31718 31958 32198 32438 32439 32679 32919 33159 33399 33639 33879 34119 34359 34599 34839 35079 35319 35559 35799 36039 36279 36519 36759 36999 37239 37479 37719 37959 38199 38439 38679 38919 39159 39399 39639 39879 40119 40359 40599 40839 41079 41319 41559 41799 42039 42279 42519 42759 42999 43239 43479 43718 43958 44198 44438 44678 44918 45157 45397 45637 45877 46116 46356 46596 46835 47075 47315 47554 47794 48034 48273 48513 48753 48993 49232 49472 49712 49951 50191 50431 50671 50910 51150 51390 51630 51869 52109 52349 52588 52828 53068 53308 53547 53787 54027 54266 54506 54746 54986 55225 55465 55705 55944 56184 56424 56664 56903 57143 57383 +nodes 16 +-11.725015000000003 -13.975014999999999 +-11.775015000000002 -13.975014999999999 +-11.175015000000002 -13.975014999999999 +-13.475015000000003 -13.925014999999998 +-13.525015000000002 -14.025015 +-13.875015000000001 -7.125014999999998 +-3.0750150000000005 -14.075014999999999 +-4.875015000000001 -14.025015 +-12.375015000000001 -15.525015 +-15.025015000000002 -14.275015 +-4.925015000000002 -14.025015 +-10.825015 -13.975014999999999 +-10.875015000000001 -13.975014999999999 +-5.175015000000002 -14.025015 +-11.125015000000001 -13.975014999999999 +-5.125015000000001 -14.025015 +edges 15 +0 1 2 -11.725015000000003 -13.975014999999999 -11.775015000000002 -13.975014999999999 +0 2 4 -11.725015000000003 -13.975014999999999 -11.475015000000003 -13.975014999999999 -11.225015000000003 -13.975014999999999 -11.175015000000002 -13.975014999999999 +3 4 2 -13.475015000000003 -13.925014999999998 -13.525015000000002 -14.025015 +3 1 8 -13.475015000000003 -13.925014999999998 -13.225015000000003 -13.925014999999998 -12.975015000000003 -13.925014999999998 -12.725015000000003 -13.925014999999998 -12.475015000000003 -13.925014999999998 -12.225015000000003 -13.925014999999998 -11.975015000000003 -13.975014999999999 -11.775015000000002 -13.975014999999999 +3 5 30 -13.475015000000003 -13.925014999999998 -13.425015000000002 -13.725014999999999 -13.375015000000001 -13.525015 -13.325015000000002 -13.325014999999999 -13.275015000000002 -13.125014999999998 -13.225015000000003 -12.925014999999998 -13.175015000000002 -12.725014999999999 -13.125015000000001 -12.525015 -13.075015000000002 -12.325014999999999 -13.075015000000002 -12.075014999999999 -13.075015000000002 -11.825014999999999 -13.075015000000002 -11.575014999999999 -13.075015000000002 -11.325014999999999 -13.075015000000002 -11.075014999999999 -13.075015000000002 -10.825014999999999 -13.075015000000002 -10.575014999999999 -13.075015000000002 -10.325014999999999 -13.075015000000002 -10.075014999999999 -13.125015000000001 -9.825014999999999 -13.175015000000002 -9.575014999999999 -13.275015000000002 -9.325014999999999 -13.325015000000002 -9.075014999999999 -13.425015000000002 -8.825014999999999 -13.475015000000003 -8.575014999999999 -13.525015000000002 -8.325014999999999 -13.625015000000001 -8.075014999999999 -13.675015000000002 -7.825014999999999 -13.775015000000002 -7.575014999999999 -13.825015000000002 -7.325014999999999 -13.875015000000001 -7.125014999999998 +6 7 9 -3.0750150000000005 -14.075014999999999 -3.3250150000000005 -14.075014999999999 -3.5750150000000005 -14.075014999999999 -3.8250150000000005 -14.075014999999999 -4.0750150000000005 -14.075014999999999 -4.3250150000000005 -14.075014999999999 -4.5750150000000005 -14.075014999999999 -4.8250150000000005 -14.075014999999999 -4.875015000000001 -14.025015 +4 8 7 -13.525015000000002 -14.025015 -13.425015000000002 -14.275015 -13.225015000000003 -14.525015 -13.075015000000002 -14.775015 -12.825015000000002 -15.025015 -12.625015000000001 -15.275015 -12.375015000000001 -15.525015 +4 9 8 -13.525015000000002 -14.025015 -13.725015000000003 -14.075014999999999 -13.925015000000002 -14.125014999999998 -14.175015000000002 -14.125014999999998 -14.375015000000001 -14.175014999999998 -14.625015000000001 -14.175014999999998 -14.825015000000002 -14.225014999999999 -15.025015000000002 -14.275015 +7 10 2 -4.875015000000001 -14.025015 -4.925015000000002 -14.025015 +11 12 2 -10.825015 -13.975014999999999 -10.875015000000001 -13.975014999999999 +11 13 24 -10.825015 -13.975014999999999 -10.625015000000001 -13.925014999999998 -10.375015000000001 -13.925014999999998 -10.125015000000001 -13.925014999999998 -9.875015000000001 -13.975014999999999 -9.625015000000001 -13.975014999999999 -9.375015000000001 -13.975014999999999 -9.125015000000001 -13.975014999999999 -8.875015000000001 -13.975014999999999 -8.625015000000001 -13.975014999999999 -8.375015000000001 -13.975014999999999 -8.125015000000001 -13.975014999999999 -7.875015000000001 -13.975014999999999 -7.625015000000001 -13.975014999999999 -7.375015000000001 -14.025015 -7.125015000000001 -14.025015 -6.875015000000001 -14.025015 -6.625015000000001 -14.025015 -6.375015000000001 -14.025015 -6.125015000000001 -14.025015 -5.875015000000001 -14.025015 -5.625015000000001 -14.025015 -5.375015000000001 -14.025015 -5.175015000000002 -14.025015 +14 2 2 -11.125015000000001 -13.975014999999999 -11.175015000000002 -13.975014999999999 +14 12 2 -11.125015000000001 -13.975014999999999 -10.875015000000001 -13.975014999999999 +13 15 2 -5.175015000000002 -14.025015 -5.125015000000001 -14.025015 +10 15 2 -4.925015000000002 -14.025015 -5.125015000000001 -14.025015 +lanes 19 +0 -11.703861153846157 -13.950014999999999 -11.196168846153848 -13.950014999999999 0.5076923076923094 0.0 +0 -11.703861153846157 -14.450014999999999 -11.196168846153848 -14.450014999999999 0.5076923076923094 0.5 +0 -11.703861153846157 -13.450014999999999 -11.196168846153848 -13.450014999999999 0.5076923076923094 0.5 +2 -3.9750150000000017 -16.850015 -3.9750150000000013 -7.448229285714284 9.401785714285715 0.0 +2 -3.4750150000000017 -16.850015 -3.4750150000000013 -7.448229285714284 9.401785714285715 0.5 +2 -4.475015000000002 -16.850015 -4.475015000000002 -7.448229285714284 9.401785714285715 0.5 +2 -14.600015 -16.750014999999998 -14.600015 -16.150015 0.5999999999999979 0.0 +4 -11.200015000000002 -18.025015000000003 -14.700015000000002 -18.025015 3.5 0.0 +4 -11.200015000000002 -17.525015000000003 -14.700015000000002 -17.525015 3.5 0.5 +4 -11.200015000000002 -18.525015000000003 -14.700015000000002 -18.525015 3.5 0.5 +4 -11.200015000000002 -17.025015000000003 -14.700015000000002 -17.025015 3.5 1.0 +4 -11.196168846153848 -8.175014999999998 -11.703861153846159 -8.175014999999998 0.5076923076923112 0.0 +4 -11.196168846153848 -7.675014999999998 -11.703861153846159 -7.675014999999998 0.5076923076923112 0.5 +4 -11.196168846153848 -8.675014999999998 -11.703861153846159 -8.675014999999998 0.5076923076923112 0.5 +6 -8.000015000000001 -7.448210876288656 -8.000015000000003 -16.700272731958762 9.252061855670103 0.0 +6 -8.500015000000001 -7.448210876288656 -8.500015000000003 -16.700272731958762 9.252061855670103 0.5 +6 -7.500015000000001 -7.448210876288656 -7.500015000000002 -16.700272731958762 9.252061855670103 0.5 +6 -9.000015000000001 -7.448210876288656 -9.000015000000003 -16.700272731958762 9.252061855670103 1.0 +6 -7.000015000000001 -7.448210876288657 -7.000015000000002 -16.700272731958762 9.252061855670103 1.0 diff --git a/test/data/reference_graph/cut_zone.fixture b/test/data/reference_graph/cut_zone.fixture new file mode 100644 index 0000000..e73c5c4 --- /dev/null +++ b/test/data/reference_graph/cut_zone.fixture @@ -0,0 +1,28 @@ +reference_graph_fixture 1 +size 200 60 +resolution 0.05 +origin -2.5 1.25 +params 0.335 0.7 1.0 0.5 0.3 0.3 +cost 53 +254 2000 60 95 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 190 254 10 60 3095 254 2000 +direction 81 +0 2050 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 2050 +skeleton 214 +5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6075 6076 6124 6276 6277 6323 6477 6478 6522 6678 6679 6721 6879 6880 6919 6920 7080 7081 7118 7281 7282 7317 7482 7483 7516 7683 7684 7685 7714 7715 7885 7886 7887 7913 8087 8088 8089 8110 8111 8112 8289 8290 8291 8292 8293 8294 8305 8306 8307 8308 8309 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 +nodes 6 +4.9750000000000005 2.725 +0.025000000000000355 2.725 +5.025 2.725 +-0.02499999999999991 2.725 +-2.475 2.725 +7.475000000000001 2.725 +edges 5 +0 1 24 4.9750000000000005 2.725 4.7250000000000005 2.725 4.4750000000000005 2.725 4.2250000000000005 2.725 3.9750000000000005 2.725 3.7250000000000005 2.725 3.5250000000000004 2.975 3.2750000000000004 3.175 3.0250000000000004 3.275 2.7750000000000004 3.325 2.5250000000000004 3.375 2.2750000000000004 3.375 2.075 3.325 1.875 3.275 1.7250000000000005 3.175 1.5750000000000002 3.075 1.475 2.925 1.3250000000000002 2.825 1.1750000000000003 2.725 0.9250000000000003 2.725 0.6750000000000003 2.725 0.42500000000000027 2.725 0.17500000000000027 2.725 0.025000000000000355 2.725 +0 2 2 4.9750000000000005 2.725 5.025 2.725 +3 4 11 -0.02499999999999991 2.725 -0.2749999999999999 2.725 -0.5249999999999999 2.725 -0.7749999999999999 2.725 -1.025 2.725 -1.275 2.725 -1.525 2.725 -1.775 2.725 -2.025 2.725 -2.275 2.725 -2.475 2.725 +3 1 2 -0.02499999999999991 2.725 0.025000000000000355 2.725 +5 2 11 7.475000000000001 2.725 7.225000000000001 2.725 6.975 2.725 6.725 2.725 6.475 2.725 6.225 2.725 5.975 2.725 5.725 2.725 5.4750000000000005 2.725 5.2250000000000005 2.725 5.025 2.725 +lanes 3 +0 3.5388358909926865e-16 3.3500000000000014 4.950495049504951 3.3500000000000014 4.950495049504951 0.0 +0 3.5388358909926865e-16 2.8500000000000014 1.9306930693069315 2.8500000000000014 1.930693069306931 0.5 +0 3.5388358909926865e-16 2.3500000000000014 1.9306930693069315 2.3500000000000014 1.930693069306931 1.0 diff --git a/test/data/reference_graph/one_zone.fixture b/test/data/reference_graph/one_zone.fixture new file mode 100644 index 0000000..73328bc --- /dev/null +++ b/test/data/reference_graph/one_zone.fixture @@ -0,0 +1,28 @@ +reference_graph_fixture 1 +size 200 60 +resolution 0.05 +origin -2.5 1.25 +params 0.335 0.7 1.0 0.5 0.3 0.3 +cost 3 +254 2000 60 8000 254 2000 +direction 81 +0 2050 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 100 1 100 0 2050 +skeleton 200 +5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 +nodes 6 +4.9750000000000005 2.725 +0.025000000000000355 2.725 +5.025 2.725 +-0.02499999999999991 2.725 +-2.475 2.725 +7.475000000000001 2.725 +edges 5 +0 1 21 4.9750000000000005 2.725 4.7250000000000005 2.725 4.4750000000000005 2.725 4.2250000000000005 2.725 3.9750000000000005 2.725 3.7250000000000005 2.725 3.4750000000000005 2.725 3.2250000000000005 2.725 2.9750000000000005 2.725 2.7250000000000005 2.725 2.4750000000000005 2.725 2.2250000000000005 2.725 1.9750000000000005 2.725 1.7250000000000005 2.725 1.475 2.725 1.225 2.725 0.9750000000000001 2.725 0.7250000000000001 2.725 0.4750000000000001 2.725 0.2250000000000001 2.725 0.025000000000000355 2.725 +0 2 2 4.9750000000000005 2.725 5.025 2.725 +3 4 11 -0.02499999999999991 2.725 -0.2749999999999999 2.725 -0.5249999999999999 2.725 -0.7749999999999999 2.725 -1.025 2.725 -1.275 2.725 -1.525 2.725 -1.775 2.725 -2.025 2.725 -2.275 2.725 -2.475 2.725 +3 1 2 -0.02499999999999991 2.725 0.025000000000000355 2.725 +5 2 11 7.475000000000001 2.725 7.225000000000001 2.725 6.975 2.725 6.725 2.725 6.475 2.725 6.225 2.725 5.975 2.725 5.725 2.725 5.4750000000000005 2.725 5.2250000000000005 2.725 5.025 2.725 +lanes 3 +0 3.5388358909926865e-16 2.75 4.950495049504951 2.75 4.950495049504951 0.0 +0 3.5388358909926865e-16 2.25 4.950495049504951 2.25 4.950495049504951 0.5 +0 3.5388358909926865e-16 3.25 4.950495049504951 3.25 4.950495049504951 0.5 diff --git a/test/data/reference_graph/ring.fixture b/test/data/reference_graph/ring.fixture new file mode 100644 index 0000000..c37d3ed --- /dev/null +++ b/test/data/reference_graph/ring.fixture @@ -0,0 +1,14 @@ +reference_graph_fixture 1 +size 120 120 +resolution 0.05 +origin -2.5 1.25 +params 0.335 0.7 1.0 0.5 0.3 0.3 +cost 241 +254 1253 60 14 254 101 60 24 254 92 60 32 254 86 60 36 254 81 60 42 254 76 60 46 254 72 60 50 254 69 60 52 254 66 60 56 254 63 60 58 254 60 60 62 254 57 60 64 254 55 60 66 254 53 60 68 254 51 60 70 254 49 60 72 254 47 60 74 254 45 60 76 254 43 60 78 254 41 60 80 254 40 60 80 254 39 60 82 254 37 60 84 254 36 60 84 254 35 60 86 254 33 60 88 254 32 60 88 254 31 60 90 254 30 60 90 254 29 60 92 254 28 60 92 254 28 60 92 254 27 60 94 254 26 60 94 254 25 60 96 254 24 60 96 254 24 60 96 254 24 60 96 254 23 60 98 254 22 60 98 254 22 60 46 254 6 60 46 254 22 60 44 254 10 60 44 254 22 60 42 254 14 60 42 254 21 60 42 254 16 60 42 254 20 60 42 254 16 60 42 254 20 60 41 254 18 60 41 254 20 60 41 254 18 60 41 254 20 60 40 254 20 60 40 254 20 60 40 254 20 60 40 254 20 60 40 254 20 60 40 254 20 60 40 254 20 60 40 254 20 60 40 254 20 60 40 254 20 60 40 254 20 60 40 254 20 60 41 254 18 60 41 254 20 60 41 254 18 60 41 254 20 60 42 254 16 60 42 254 20 60 42 254 16 60 42 254 21 60 42 254 14 60 42 254 22 60 44 254 10 60 44 254 22 60 46 254 6 60 46 254 22 60 98 254 22 60 98 254 23 60 96 254 24 60 96 254 24 60 96 254 24 60 96 254 25 60 94 254 26 60 94 254 27 60 92 254 28 60 92 254 28 60 92 254 29 60 90 254 30 60 90 254 31 60 88 254 32 60 88 254 33 60 86 254 35 60 84 254 36 60 84 254 37 60 82 254 39 60 80 254 40 60 80 254 41 60 78 254 43 60 76 254 45 60 74 254 47 60 72 254 49 60 70 254 51 60 68 254 53 60 66 254 55 60 64 254 57 60 62 254 60 60 58 254 63 60 56 254 66 60 52 254 69 60 50 254 72 60 46 254 76 60 42 254 81 60 36 254 86 60 32 254 92 60 24 254 101 60 14 254 1253 +direction 1 +0 14400 +skeleton 205 +3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3651 3652 3653 3654 3664 3665 3666 3667 3668 3768 3769 3770 3788 3789 3790 3791 3886 3887 3911 3912 3913 4004 4005 4033 4034 4035 4123 4155 4156 4241 4242 4276 4277 4278 4360 4398 4399 4479 4519 4520 4598 4640 4641 4717 4761 4762 4836 4882 4883 4955 5003 5075 5123 5124 5194 5244 5245 5313 5365 5433 5485 5486 5552 5606 5672 5726 5727 5791 5847 5911 5967 6031 6087 6088 6150 6208 6270 6328 6390 6448 6510 6568 6569 6629 6689 6749 6809 6869 6929 6989 7049 7109 7169 7229 7289 7349 7409 7469 7529 7589 7649 7709 7710 7769 7830 7888 7950 8008 8070 8128 8190 8191 8248 8311 8367 8431 8487 8551 8552 8607 8672 8726 8792 8793 8846 8913 8965 9033 9034 9085 9154 9155 9204 9275 9323 9395 9396 9443 9516 9517 9562 9637 9638 9681 9758 9759 9800 9879 9880 9919 10000 10001 10002 10037 10038 10122 10123 10156 10243 10244 10245 10274 10275 10365 10366 10367 10392 10393 10487 10488 10489 10490 10509 10510 10511 10610 10611 10612 10613 10614 10625 10626 10627 10628 10734 10735 10736 10737 10738 10739 10740 10741 10742 10743 10744 +nodes 0 +edges 0 +lanes 0 diff --git a/test/data/reference_graph/t_junction.fixture b/test/data/reference_graph/t_junction.fixture new file mode 100644 index 0000000..4c461e0 --- /dev/null +++ b/test/data/reference_graph/t_junction.fixture @@ -0,0 +1,21 @@ +reference_graph_fixture 1 +size 200 120 +resolution 0.05 +origin -2.5 1.25 +params 0.335 0.7 1.0 0.5 0.3 0.3 +cost 143 +254 2000 60 8000 254 80 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 160 60 40 254 80 +direction 1 +0 24000 +skeleton 290 +5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6085 6086 6087 6088 6089 6090 6109 6110 6111 6112 6113 6290 6291 6292 6293 6306 6307 6308 6493 6494 6495 6504 6505 6695 6696 6697 6698 6701 6702 6703 6898 6899 6900 7099 7299 7499 7699 7899 8099 8299 8499 8699 8899 9099 9299 9499 9699 9899 10099 10299 10499 10699 10899 11099 11299 11499 11699 11899 12099 12299 12499 12699 12899 13099 13299 13499 13699 13899 14099 14299 14499 14699 14899 15099 15299 15499 15699 15899 16099 16299 16499 16699 16899 17099 17299 17499 17699 17899 18099 18299 18499 18699 18899 19099 19299 19499 19699 19899 20099 20299 20499 20699 20899 21099 21299 21499 21699 21899 22099 22299 22499 22699 22899 23099 23299 23499 23699 23899 +nodes 4 +2.4750000000000005 2.975 +-2.475 2.725 +7.475000000000001 2.725 +2.4750000000000005 7.2250000000000005 +edges 3 +0 1 22 2.4750000000000005 2.975 2.2750000000000004 2.925 2.125 2.825 1.9249999999999998 2.7750000000000004 1.7250000000000005 2.725 1.475 2.725 1.225 2.725 0.9750000000000001 2.725 0.7250000000000001 2.725 0.4750000000000001 2.725 0.2250000000000001 2.725 -0.02499999999999991 2.725 -0.2749999999999999 2.725 -0.5249999999999999 2.725 -0.7749999999999999 2.725 -1.025 2.725 -1.275 2.725 -1.525 2.725 -1.775 2.725 -2.025 2.725 -2.275 2.725 -2.475 2.725 +0 2 21 2.4750000000000005 2.975 2.7250000000000005 2.875 2.9750000000000005 2.7750000000000004 3.2250000000000005 2.725 3.4750000000000005 2.725 3.7250000000000005 2.725 3.9750000000000005 2.725 4.2250000000000005 2.725 4.4750000000000005 2.725 4.7250000000000005 2.725 4.9750000000000005 2.725 5.2250000000000005 2.725 5.4750000000000005 2.725 5.725 2.725 5.975 2.725 6.225 2.725 6.475 2.725 6.725 2.725 6.975 2.725 7.225000000000001 2.725 7.475000000000001 2.725 +0 3 18 2.4750000000000005 2.975 2.4750000000000005 3.225 2.4750000000000005 3.475 2.4750000000000005 3.725 2.4750000000000005 3.975 2.4750000000000005 4.225 2.4750000000000005 4.475 2.4750000000000005 4.725 2.4750000000000005 4.975 2.4750000000000005 5.225 2.4750000000000005 5.4750000000000005 2.4750000000000005 5.7250000000000005 2.4750000000000005 5.9750000000000005 2.4750000000000005 6.2250000000000005 2.4750000000000005 6.4750000000000005 2.4750000000000005 6.7250000000000005 2.4750000000000005 6.9750000000000005 2.4750000000000005 7.2250000000000005 +lanes 0 diff --git a/test/data/reference_graph/two_zones.fixture b/test/data/reference_graph/two_zones.fixture new file mode 100644 index 0000000..0978031 --- /dev/null +++ b/test/data/reference_graph/two_zones.fixture @@ -0,0 +1,37 @@ +reference_graph_fixture 1 +size 200 60 +resolution 0.05 +origin -2.5 1.25 +params 0.335 0.7 1.0 0.5 0.3 0.3 +cost 3 +254 2000 60 8000 254 2000 +direction 121 +0 2040 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 80 1 60 2 60 0 2040 +skeleton 200 +5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 +nodes 8 +2.5250000000000004 2.725 +2.4750000000000005 2.725 +5.4750000000000005 2.725 +-0.5249999999999999 2.725 +-2.475 2.725 +-0.4750000000000001 2.725 +7.475000000000001 2.725 +5.525 2.725 +edges 7 +0 1 2 2.5250000000000004 2.725 2.4750000000000005 2.725 +0 2 13 2.5250000000000004 2.725 2.7750000000000004 2.725 3.0250000000000004 2.725 3.2750000000000004 2.725 3.5250000000000004 2.725 3.7750000000000004 2.725 4.025 2.725 4.275 2.725 4.525 2.725 4.775 2.725 5.025 2.725 5.275 2.725 5.4750000000000005 2.725 +3 4 9 -0.5249999999999999 2.725 -0.7749999999999999 2.725 -1.025 2.725 -1.275 2.725 -1.525 2.725 -1.775 2.725 -2.025 2.725 -2.275 2.725 -2.475 2.725 +3 5 2 -0.5249999999999999 2.725 -0.4750000000000001 2.725 +6 7 9 7.475000000000001 2.725 7.225000000000001 2.725 6.975 2.725 6.725 2.725 6.475 2.725 6.225 2.725 5.975 2.725 5.725 2.725 5.525 2.725 +7 2 2 5.525 2.725 5.4750000000000005 2.725 +1 5 13 2.4750000000000005 2.725 2.2250000000000005 2.725 1.9750000000000005 2.725 1.7250000000000005 2.725 1.475 2.725 1.225 2.725 0.9750000000000001 2.725 0.7250000000000001 2.725 0.4750000000000001 2.725 0.2250000000000001 2.725 -0.02499999999999991 2.725 -0.2749999999999999 2.725 -0.4750000000000001 2.725 +lanes 8 +0 -0.5000000000000001 2.75 2.4508196721311477 2.75 2.9508196721311477 0.0 +0 -0.5000000000000001 2.25 2.4508196721311477 2.25 2.9508196721311477 0.5 +0 -0.5000000000000001 3.25 2.4508196721311477 3.25 2.9508196721311477 0.5 +1 3.454225352112677 2.2042253521126765 4.545774647887324 3.2957746478873235 1.5436838180833075 0.0 +1 4.159891418762288 2.20278463757574 5.251440714536936 3.294333933350387 1.5436838180833075 0.5 +1 2.7485592854630645 2.205666066649612 3.8401085812377125 3.29721536242426 1.543683818083308 0.5 +1 4.8655574854119 2.201343923038804 5.499360302313308 2.835146739940213 0.8963325395322439 1.0 +1 2.500639697686692 2.664853260059787 3.134442514588101 3.2986560769611954 0.8963325395322439 1.0 diff --git a/test/data/reference_graph/unknown_block.fixture b/test/data/reference_graph/unknown_block.fixture new file mode 100644 index 0000000..f50c752 --- /dev/null +++ b/test/data/reference_graph/unknown_block.fixture @@ -0,0 +1,20 @@ +reference_graph_fixture 1 +size 200 60 +resolution 0.05 +origin -2.5 1.25 +params 0.335 0.7 1.0 0.5 0.3 0.3 +cost 83 +254 2000 60 90 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 180 255 20 60 90 254 2000 +direction 1 +0 12000 +skeleton 180 +5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 +nodes 4 +3.0250000000000004 2.725 +7.475000000000001 2.725 +1.9750000000000005 2.725 +-2.475 2.725 +edges 2 +0 1 19 3.0250000000000004 2.725 3.2750000000000004 2.725 3.5250000000000004 2.725 3.7750000000000004 2.725 4.025 2.725 4.275 2.725 4.525 2.725 4.775 2.725 5.025 2.725 5.275 2.725 5.525 2.725 5.775 2.725 6.025 2.725 6.275 2.725 6.525 2.725 6.775 2.725 7.025 2.725 7.275 2.725 7.475000000000001 2.725 +2 3 19 1.9750000000000005 2.725 1.7250000000000005 2.725 1.475 2.725 1.225 2.725 0.9750000000000001 2.725 0.7250000000000001 2.725 0.4750000000000001 2.725 0.2250000000000001 2.725 -0.02499999999999991 2.725 -0.2749999999999999 2.725 -0.5249999999999999 2.725 -0.7749999999999999 2.725 -1.025 2.725 -1.275 2.725 -1.525 2.725 -1.775 2.725 -2.025 2.725 -2.275 2.725 -2.475 2.725 +lanes 0 diff --git a/test/reference_graph_test.cpp b/test/reference_graph_test.cpp new file mode 100644 index 0000000..ea8e2f4 --- /dev/null +++ b/test/reference_graph_test.cpp @@ -0,0 +1,569 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +using namespace robot_costmap_2d; + +namespace +{ + +constexpr double kExactM = 1e-9; + +/** Expected output written by the Python prototype, oneway_eval/r12_export_cpp_text.py. */ +struct Fixture +{ + DirectionGeometry geometry{}; + ReferenceGraphParams params; + double half_x = 0.0, half_y = 0.0; + std::vector cost, direction; + std::vector skeleton; + std::vector nodes; + struct Edge + { + uint32_t from, to; + std::vector points; + }; + std::vector edges; + std::vector lanes; +}; + +std::vector readRuns(std::istream& in, const std::string& name) +{ + std::string key; + std::size_t runs = 0; + in >> key >> runs; + if (key != name) + throw std::runtime_error("expected " + name + ", got " + key); + std::vector out; + for (std::size_t i = 0; i < runs; ++i) + { + int value = 0; + std::size_t count = 0; + in >> value >> count; + out.insert(out.end(), count, static_cast(value)); + } + return out; +} + +Fixture loadFixture(const std::string& path) +{ + std::ifstream in(path); + if (!in) + throw std::runtime_error("cannot open " + path); + Fixture f; + std::string key; + int version = 0; + in >> key >> version; + if (key != "reference_graph_fixture" || version != 1) + throw std::runtime_error("bad fixture header in " + path); + f.geometry.frame_id = "map"; + in >> key >> f.geometry.width >> f.geometry.height; + in >> key >> f.geometry.resolution; + in >> key >> f.geometry.origin_x >> f.geometry.origin_y; + in >> key >> f.params.min_clearance_m >> f.params.ridge_min_separation_m >> f.params.spur_min_length_m >> + f.params.lane_offset_step_m >> f.half_x >> f.half_y; + f.cost = readRuns(in, "cost"); + f.direction = readRuns(in, "direction"); + std::size_t count = 0; + in >> key >> count; + f.skeleton.resize(count); + for (int64_t& cell : f.skeleton) + in >> cell; + in >> key >> count; + f.nodes.resize(count); + for (ReferencePoint& node : f.nodes) + in >> node.x >> node.y; + in >> key >> count; + f.edges.resize(count); + for (Fixture::Edge& edge : f.edges) + { + std::size_t points = 0; + in >> edge.from >> edge.to >> points; + edge.points.resize(points); + for (ReferencePoint& point : edge.points) + in >> point.x >> point.y; + } + in >> key >> count; + f.lanes.resize(count); + for (ReferenceLane& lane : f.lanes) + { + int direction = 0; + in >> direction >> lane.entry.x >> lane.entry.y >> lane.exit.x >> lane.exit.y >> lane.length_m >> + lane.offset_from_centre_m; + lane.direction_index = static_cast(direction); + } + if (!in) + throw std::runtime_error("truncated fixture " + path); + return f; +} + +std::vector rectangle(double half_x, double half_y) +{ + std::vector out(4); + out[0].x = half_x, out[0].y = half_y; + out[1].x = -half_x, out[1].y = half_y; + out[2].x = -half_x, out[2].y = -half_y; + out[3].x = half_x, out[3].y = -half_y; + return out; +} + +ReferenceGridView viewOf(const Fixture& f) +{ + ReferenceGridView view; + view.cost = f.cost.data(); + view.geometry = f.geometry; + const bool zones = std::any_of(f.direction.begin(), f.direction.end(), [](uint8_t code) { return code != 0; }); + view.direction_codes = zones ? f.direction.data() : nullptr; + return view; +} + +double pointToSegment(const ReferencePoint& p, const ReferencePoint& a, const ReferencePoint& b) +{ + const double dx = b.x - a.x, dy = b.y - a.y; + const double squared = dx * dx + dy * dy; + const double t = squared <= 0.0 ? 0.0 : std::min(1.0, std::max(0.0, ((p.x - a.x) * dx + (p.y - a.y) * dy) / squared)); + return std::hypot(p.x - a.x - t * dx, p.y - a.y - t * dy); +} + +double pointToPolyline(const ReferencePoint& p, const std::vector& line) +{ + double best = std::numeric_limits::infinity(); + for (std::size_t i = 0; i + 1 < line.size(); ++i) + best = std::min(best, pointToSegment(p, line[i], line[i + 1])); + return best; +} + +double polylineLength(const std::vector& line) +{ + double total = 0.0; + for (std::size_t i = 0; i + 1 < line.size(); ++i) + total += std::hypot(line[i + 1].x - line[i].x, line[i + 1].y - line[i].y); + return total; +} + +std::vector> sortedPoints(const std::vector& points) +{ + std::vector> out; + out.reserve(points.size()); + for (const ReferencePoint& point : points) + out.emplace_back(point.x, point.y); + std::sort(out.begin(), out.end()); + return out; +} + +/** Both sides read the same chain of cells, but a walk from the other end keeps different cells. + * So edges are matched by end nodes and compared as polylines, within one and a half cells. */ +void expectEdgesMatch(const Fixture& f, const ReferenceGraph& graph) +{ + using Ends = std::tuple; + const auto ends = [](const ReferencePoint& a, const ReferencePoint& b) { + return a.x < b.x || (a.x == b.x && a.y < b.y) ? Ends(a.x, a.y, b.x, b.y) : Ends(b.x, b.y, a.x, a.y); + }; + std::vector> expected, actual; + for (std::size_t i = 0; i < f.edges.size(); ++i) + expected.emplace_back(ends(f.nodes[f.edges[i].from], f.nodes[f.edges[i].to]), i); + for (std::size_t i = 0; i < graph.edges.size(); ++i) + actual.emplace_back(ends(graph.nodes[graph.edges[i].from], graph.nodes[graph.edges[i].to]), i); + std::sort(expected.begin(), expected.end()); + std::sort(actual.begin(), actual.end()); + ASSERT_EQ(expected.size(), actual.size()); + + const double tolerance = 1.5 * f.geometry.resolution; + for (std::size_t i = 0; i < expected.size(); ++i) + { + ASSERT_EQ(expected[i].first, actual[i].first) << "edge end nodes differ at sorted position " << i; + // Parallel edges share their end nodes: pick the closest one among them. + const Fixture::Edge& python = f.edges[expected[i].second]; + double best = std::numeric_limits::infinity(); + for (std::size_t j = i; j < actual.size() && actual[j].first == expected[i].first; ++j) + { + double worst = 0.0; + for (const ReferencePoint& point : graph.edges[actual[j].second].points) + worst = std::max(worst, pointToPolyline(point, python.points)); + best = std::min(best, worst); + } + EXPECT_LE(best, tolerance) << "edge " << i << " leaves the Python polyline"; + const VoronoiEdge& edge = graph.edges[actual[i].second]; + EXPECT_NEAR(edge.length_m, polylineLength(edge.points), kExactM); + } +} + +void expectLanesMatch(const Fixture& f, const ReferenceGraph& graph) +{ + const auto order = [](const ReferenceLane& a, const ReferenceLane& b) { + return std::make_tuple(a.direction_index, a.entry.x, a.entry.y) < std::make_tuple(b.direction_index, b.entry.x, b.entry.y); + }; + std::vector expected = f.lanes, actual = graph.lanes; + std::sort(expected.begin(), expected.end(), order); + std::sort(actual.begin(), actual.end(), order); + ASSERT_EQ(expected.size(), actual.size()); + for (std::size_t i = 0; i < expected.size(); ++i) + { + EXPECT_EQ(expected[i].direction_index, actual[i].direction_index); + EXPECT_NEAR(expected[i].entry.x, actual[i].entry.x, kExactM); + EXPECT_NEAR(expected[i].entry.y, actual[i].entry.y, kExactM); + EXPECT_NEAR(expected[i].exit.x, actual[i].exit.x, kExactM); + EXPECT_NEAR(expected[i].exit.y, actual[i].exit.y, kExactM); + EXPECT_NEAR(expected[i].length_m, actual[i].length_m, kExactM); + EXPECT_NEAR(expected[i].offset_from_centre_m, actual[i].offset_from_centre_m, kExactM); + } +} + +/** Run steps 1 and 2 on a fixture and compare every stage. Returns step times [ms] for the timing test. */ +std::pair expectParity(const Fixture& f) +{ + const ReferenceGridView view = viewOf(f); + const auto t0 = std::chrono::steady_clock::now(); + const VoronoiSkeleton skeleton = computeVoronoiSkeleton(view, f.params); + const auto t1 = std::chrono::steady_clock::now(); + const ReferenceGraph graph = buildReferenceGraph(view, skeleton, rectangle(f.half_x, f.half_y), f.params); + const auto t2 = std::chrono::steady_clock::now(); + + std::vector cells; + for (std::size_t i = 0; i < skeleton.mask.size(); ++i) + if (skeleton.mask[i] != 0) + cells.push_back(static_cast(i)); + std::vector only_cpp, only_python; + std::set_difference(cells.begin(), cells.end(), f.skeleton.begin(), f.skeleton.end(), std::back_inserter(only_cpp)); + std::set_difference(f.skeleton.begin(), f.skeleton.end(), cells.begin(), cells.end(), std::back_inserter(only_python)); + EXPECT_TRUE(only_cpp.empty()) << only_cpp.size() << " skeleton cells only in C++"; + EXPECT_TRUE(only_python.empty()) << only_python.size() << " skeleton cells only in Python"; + + const std::vector> expected_nodes = sortedPoints(f.nodes), actual_nodes = sortedPoints(graph.nodes); + EXPECT_EQ(expected_nodes.size(), actual_nodes.size()); + for (std::size_t i = 0; i < std::min(expected_nodes.size(), actual_nodes.size()); ++i) + { + EXPECT_NEAR(expected_nodes[i].first, actual_nodes[i].first, kExactM); + EXPECT_NEAR(expected_nodes[i].second, actual_nodes[i].second, kExactM); + } + expectEdgesMatch(f, graph); + expectLanesMatch(f, graph); + EXPECT_EQ(graph.static_cost, f.cost); + EXPECT_EQ(graph.clearance_mm, skeleton.clearance_mm); + + const auto ms = [](std::chrono::steady_clock::time_point a, std::chrono::steady_clock::time_point b) { + return std::chrono::duration(b - a).count(); + }; + return { ms(t0, t1), ms(t1, t2) }; +} + +std::string packagedFixture(const std::string& name) +{ + return std::string(ROBOT_COSTMAP_2D_DIR) + "/test/data/reference_graph/" + name + ".fixture"; +} + +DirectionGeometry geometryOf(uint32_t width, uint32_t height) +{ + return { width, height, 0.05, 0.0, 0.0, "map" }; +} + +/** Free corridor 2 m wide between two lethal walls, as in the corridor fixture. */ +std::vector corridorCost(uint32_t width, uint32_t height) +{ + std::vector cost(static_cast(width) * height, FREE_SPACE); + for (uint32_t y = 0; y < height; ++y) + if (y < 10 || y >= height - 10) + std::fill_n(cost.begin() + static_cast(y * width), width, LETHAL_OBSTACLE); + return cost; +} + +} // namespace + +// Exact answers from the Python prototype, one scene per behaviour. +TEST(ReferenceGraphParity, Corridor) +{ + const Fixture f = loadFixture(packagedFixture("corridor")); + expectParity(f); + EXPECT_EQ(f.nodes.size(), 2u); + EXPECT_EQ(f.edges.size(), 1u); +} + +TEST(ReferenceGraphParity, TJunction) +{ + const Fixture f = loadFixture(packagedFixture("t_junction")); + expectParity(f); + EXPECT_EQ(f.nodes.size(), 4u); + EXPECT_EQ(f.edges.size(), 3u); +} + +TEST(ReferenceGraphParity, ClosedRingHasNoNode) +{ + const Fixture f = loadFixture(packagedFixture("ring")); + expectParity(f); + EXPECT_FALSE(f.skeleton.empty()); + EXPECT_TRUE(f.nodes.empty()); +} + +TEST(ReferenceGraphParity, UnknownCellsSplitTheRidge) +{ + const Fixture f = loadFixture(packagedFixture("unknown_block")); + expectParity(f); + EXPECT_EQ(f.edges.size(), 2u); + for (int64_t cell : f.skeleton) + EXPECT_NE(f.cost[static_cast(cell)], NO_INFORMATION); +} + +TEST(ReferenceGraphParity, OneZoneSplitsEdgesAndAddsLanes) +{ + const Fixture f = loadFixture(packagedFixture("one_zone")); + expectParity(f); + EXPECT_EQ(f.edges.size(), 5u); + ASSERT_EQ(f.lanes.size(), 3u); + for (const ReferenceLane& lane : f.lanes) + { + EXPECT_EQ(lane.direction_index, 0); + EXPECT_GT(lane.exit.x, lane.entry.x); + } +} + +TEST(ReferenceGraphParity, TwoZones) +{ + expectParity(loadFixture(packagedFixture("two_zones"))); +} + +TEST(ReferenceGraphParity, ZoneCutByObstacle) +{ + expectParity(loadFixture(packagedFixture("cut_zone"))); +} + +TEST(ReferenceGraphParity, MapCropWithZones) +{ + expectParity(loadFixture(packagedFixture("crop"))); +} + +// The whole-map fixtures stay outside the repo. Point REFERENCE_GRAPH_FIXTURE_DIR at them to run these. +TEST(ReferenceGraphParity, WholeMaps) +{ + const char* directory = std::getenv("REFERENCE_GRAPH_FIXTURE_DIR"); + if (directory == nullptr) + { + // The installed gtest predates GTEST_SKIP. + std::cout << "[ SKIPPED ] REFERENCE_GRAPH_FIXTURE_DIR is not set" << std::endl; + return; + } + for (const char* name : { "kit", "sehc" }) + { + SCOPED_TRACE(name); + const std::pair times = expectParity(loadFixture(std::string(directory) + "/" + name + ".fixture")); + std::cout << "[ TIMING ] " << name << " step 1 " << times.first << " ms, step 2 " << times.second << " ms" << std::endl; +#ifdef NDEBUG + // Pass condition of the plan on the dev machine. The workspace builds Debug by default, where it means nothing. + EXPECT_LT(times.first + times.second, 5000.0); +#endif + } +} + +TEST(ReferenceGraphGrid, EmptyGridHasNoSkeleton) +{ + const DirectionGeometry geometry = geometryOf(40, 30); + const std::vector cost(1200, FREE_SPACE); + ReferenceGridView view; + view.cost = cost.data(); + view.geometry = geometry; + const ReferenceGraphParams params; + const VoronoiSkeleton skeleton = computeVoronoiSkeleton(view, params); + ASSERT_EQ(skeleton.mask.size(), 1200u); + EXPECT_EQ(std::count(skeleton.mask.begin(), skeleton.mask.end(), 1), 0); + EXPECT_EQ(skeleton.clearance_mm, std::vector(1200, 65535)); + const ReferenceGraph graph = buildReferenceGraph(view, skeleton, {}, params); + EXPECT_TRUE(graph.nodes.empty()); + EXPECT_TRUE(graph.edges.empty()); + EXPECT_TRUE(graph.lanes.empty()); +} + +TEST(ReferenceGraphGrid, AllLethalHasNoSkeleton) +{ + const std::vector cost(1200, LETHAL_OBSTACLE); + ReferenceGridView view; + view.cost = cost.data(); + view.geometry = geometryOf(40, 30); + const VoronoiSkeleton skeleton = computeVoronoiSkeleton(view, ReferenceGraphParams()); + EXPECT_EQ(std::count(skeleton.mask.begin(), skeleton.mask.end(), 1), 0); + EXPECT_EQ(skeleton.clearance_mm, std::vector(1200, 0)); +} + +TEST(ReferenceGraphGrid, ClearanceIsInMillimetres) +{ + const std::vector cost = corridorCost(100, 60); + ReferenceGridView view; + view.cost = cost.data(); + view.geometry = geometryOf(100, 60); + const VoronoiSkeleton skeleton = computeVoronoiSkeleton(view, ReferenceGraphParams()); + // Row 10 touches the wall at row 9, one cell away. Row 29 is 20 cells from the wall at row 9. + EXPECT_EQ(skeleton.clearance_mm[10 * 100 + 50], 50); + EXPECT_EQ(skeleton.clearance_mm[29 * 100 + 50], 1000); + EXPECT_EQ(skeleton.clearance_mm[5 * 100 + 50], 0); +} + +TEST(ReferenceGraphGrid, InflatedCellsNeverJoinTheSkeleton) +{ + std::vector cost = corridorCost(100, 60); + // A band of inflation across the middle of the corridor, as a master costmap crop would hold. + for (uint32_t y = 25; y < 35; ++y) + std::fill_n(cost.begin() + y * 100, 100, INSCRIBED_INFLATED_OBSTACLE); + ReferenceGridView view; + view.cost = cost.data(); + view.geometry = geometryOf(100, 60); + const VoronoiSkeleton skeleton = computeVoronoiSkeleton(view, ReferenceGraphParams()); + for (std::size_t i = 0; i < cost.size(); ++i) + if (skeleton.mask[i] != 0) + EXPECT_LT(cost[i], INSCRIBED_INFLATED_OBSTACLE) << "cell " << i; +} + +TEST(ReferenceGraphGrid, SuppliedClearanceReplacesTheComputedOne) +{ + const std::vector cost = corridorCost(100, 60); + ReferenceGridView view; + view.cost = cost.data(); + view.geometry = geometryOf(100, 60); + + // An obstacle just outside a window crop: clearance from the full map rules out every cell. + const std::vector tight(6000, 100); + view.clearance_mm = tight.data(); + VoronoiSkeleton skeleton = computeVoronoiSkeleton(view, ReferenceGraphParams()); + EXPECT_EQ(std::count(skeleton.mask.begin(), skeleton.mask.end(), 1), 0); + EXPECT_EQ(skeleton.clearance_mm, tight); + + const std::vector wide(6000, 2000); + view.clearance_mm = wide.data(); + skeleton = computeVoronoiSkeleton(view, ReferenceGraphParams()); + EXPECT_GT(std::count(skeleton.mask.begin(), skeleton.mask.end(), 1), 0); + EXPECT_EQ(skeleton.clearance_mm, wide); +} + +TEST(ReferenceGraphGrid, RepeatedRunsGiveTheSameGraph) +{ + const Fixture f = loadFixture(packagedFixture("two_zones")); + const ReferenceGridView view = viewOf(f); + const VoronoiSkeleton a = computeVoronoiSkeleton(view, f.params); + const VoronoiSkeleton b = computeVoronoiSkeleton(view, f.params); + EXPECT_EQ(a.mask, b.mask); + const ReferenceGraph first = buildReferenceGraph(view, a, rectangle(f.half_x, f.half_y), f.params); + const ReferenceGraph second = buildReferenceGraph(view, b, rectangle(f.half_x, f.half_y), f.params); + ASSERT_EQ(first.nodes.size(), second.nodes.size()); + ASSERT_EQ(first.edges.size(), second.edges.size()); + ASSERT_EQ(first.lanes.size(), second.lanes.size()); + for (std::size_t i = 0; i < first.edges.size(); ++i) + EXPECT_EQ(first.edges[i].points.size(), second.edges[i].points.size()); +} + +TEST(ReferenceGraphGrid, BiggerFootprintDropsLanes) +{ + const Fixture f = loadFixture(packagedFixture("one_zone")); + const ReferenceGridView view = viewOf(f); + const VoronoiSkeleton skeleton = computeVoronoiSkeleton(view, f.params); + const ReferenceGraph fits = buildReferenceGraph(view, skeleton, rectangle(f.half_x, f.half_y), f.params); + // Half width 1.1 m does not fit the 2 m corridor. + const ReferenceGraph blocked = buildReferenceGraph(view, skeleton, rectangle(f.half_x, 1.1), f.params); + EXPECT_FALSE(fits.lanes.empty()); + EXPECT_TRUE(blocked.lanes.empty()); + EXPECT_EQ(fits.edges.size(), blocked.edges.size()); +} + +TEST(ReferenceGraphGrid, RegionCentreLineMatchesPython) +{ + const DirectionGeometry geometry = geometryOf(100, 40); + std::vector mask(4000, 0); + for (uint32_t y = 16; y < 24; ++y) + std::fill_n(mask.begin() + y * 100 + 10, 80, 1); + const std::vector line = computeRegionCentreLine(mask, geometry, ReferenceGraphParams()); + EXPECT_EQ(std::count(line.begin(), line.end(), 1), 81); + uint32_t x_min = 100, x_max = 0; + for (uint32_t y = 0; y < 40; ++y) + { + for (uint32_t x = 0; x < 100; ++x) + { + if (line[y * 100 + x] == 0) + continue; + EXPECT_NE(mask[y * 100 + x], 0) << "centre line left the region"; + x_min = std::min(x_min, x); + x_max = std::max(x_max, x); + } + } + EXPECT_EQ(x_min, 10u); + EXPECT_EQ(x_max, 89u); + + const std::vector nothing(4000, 0); + const std::vector empty_line = computeRegionCentreLine(nothing, geometry, ReferenceGraphParams()); + EXPECT_EQ(std::count(empty_line.begin(), empty_line.end(), 1), 0); +} + +TEST(ReferenceGraphInput, BadParametersAreRefused) +{ + const std::vector cost(100, FREE_SPACE); + ReferenceGridView view; + view.cost = cost.data(); + view.geometry = geometryOf(10, 10); + + ReferenceGraphParams params; + params.min_clearance_m = -0.1; + EXPECT_FALSE(validateReferenceGraphParams(params).empty()); + EXPECT_THROW(computeVoronoiSkeleton(view, params), std::invalid_argument); + params = ReferenceGraphParams(); + params.ridge_min_separation_m = 0.0; + EXPECT_THROW(computeVoronoiSkeleton(view, params), std::invalid_argument); + params = ReferenceGraphParams(); + params.spur_min_length_m = std::numeric_limits::quiet_NaN(); + EXPECT_THROW(computeVoronoiSkeleton(view, params), std::invalid_argument); + params = ReferenceGraphParams(); + params.lane_offset_step_m = -1.0; + EXPECT_THROW(computeVoronoiSkeleton(view, params), std::invalid_argument); + EXPECT_TRUE(validateReferenceGraphParams(ReferenceGraphParams()).empty()); +} + +TEST(ReferenceGraphInput, BadGridsAreRefused) +{ + const std::vector cost(100, FREE_SPACE); + ReferenceGridView view; + view.geometry = geometryOf(10, 10); + EXPECT_THROW(computeVoronoiSkeleton(view, ReferenceGraphParams()), std::invalid_argument); + view.cost = cost.data(); + view.geometry.resolution = 0.0; + EXPECT_THROW(computeVoronoiSkeleton(view, ReferenceGraphParams()), std::invalid_argument); + view.geometry = geometryOf(0, 10); + EXPECT_THROW(computeVoronoiSkeleton(view, ReferenceGraphParams()), std::invalid_argument); + view.geometry = geometryOf(10, 10); + VoronoiSkeleton wrong_size; + EXPECT_THROW(buildReferenceGraph(view, wrong_size, {}, ReferenceGraphParams()), std::invalid_argument); +} + +TEST(ReferenceGraphInput, ZonesNeedAFootprint) +{ + const Fixture f = loadFixture(packagedFixture("one_zone")); + const ReferenceGridView view = viewOf(f); + const VoronoiSkeleton skeleton = computeVoronoiSkeleton(view, f.params); + EXPECT_THROW(buildReferenceGraph(view, skeleton, {}, f.params), std::invalid_argument); + EXPECT_THROW(buildReferenceGraph(view, skeleton, rectangle(0.0, 0.0), f.params), std::invalid_argument); +} + +TEST(ReferenceGraphCancel, CancelGivesAnEmptyResult) +{ + const Fixture f = loadFixture(packagedFixture("one_zone")); + const ReferenceGridView view = viewOf(f); + const VoronoiSkeleton skeleton = computeVoronoiSkeleton(view, f.params); + std::atomic cancel(true); + EXPECT_TRUE(computeVoronoiSkeleton(view, f.params, &cancel).mask.empty()); + const ReferenceGraph graph = buildReferenceGraph(view, skeleton, rectangle(f.half_x, f.half_y), f.params, &cancel); + EXPECT_TRUE(graph.static_cost.empty()); + EXPECT_TRUE(graph.nodes.empty()); + EXPECT_TRUE(graph.edges.empty()); + EXPECT_TRUE(graph.lanes.empty()); +} diff --git a/test/reference_graph_worker_test.cpp b/test/reference_graph_worker_test.cpp new file mode 100644 index 0000000..68dde58 --- /dev/null +++ b/test/reference_graph_worker_test.cpp @@ -0,0 +1,670 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include + +using namespace robot_costmap_2d; + +namespace +{ + +using Clock = std::chrono::steady_clock; + +constexpr double kResolution = 0.05; + +bool waitUntil(const std::function& condition, double seconds = 60.0) +{ + const Clock::time_point end = Clock::now() + std::chrono::duration_cast(std::chrono::duration(seconds)); + while (Clock::now() < end) + { + if (condition()) + return true; + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + return condition(); +} + +DirectionGeometry geometryOf(uint32_t width, uint32_t height) { return { width, height, kResolution, 0.0, 0.0, "map" }; } + +/** Free map with a lethal border, so its ridge runs along the middle. */ +std::vector corridor(uint32_t width, uint32_t height) +{ + std::vector cost(static_cast(width) * height, FREE_SPACE); + for (uint32_t x = 0; x < width; ++x) + cost[x] = cost[static_cast(height - 1) * width + x] = LETHAL_OBSTACLE; + for (uint32_t y = 0; y < height; ++y) + cost[static_cast(y) * width] = cost[static_cast(y) * width + width - 1] = LETHAL_OBSTACLE; + return cost; +} + +std::vector rectangle(double half_x, double half_y) +{ + std::vector footprint(4); + const double xs[4] = { half_x, -half_x, -half_x, half_x }; + const double ys[4] = { half_y, half_y, -half_y, -half_y }; + for (int i = 0; i < 4; ++i) + { + footprint[static_cast(i)].x = xs[i]; + footprint[static_cast(i)].y = ys[i]; + } + return footprint; +} + +/** Zone with direction +X over a band in the middle of the map. */ +DirectionFieldSnapshot bandZone(uint32_t width, uint32_t height, uint64_t generation) +{ + robot_nav_msgs::OccupancyGrid grid; + grid.header.frame_id = "map"; + grid.info.width = width; + grid.info.height = height; + grid.info.resolution = kResolution; + grid.data.assign(static_cast(width) * height, 0); + for (uint32_t y = height / 3; y < 2 * height / 3; ++y) + for (uint32_t x = width / 4; x < 3 * width / 4; ++x) + grid.data[static_cast(y) * width + x] = 1; + DirectionFieldSnapshot snapshot; + snapshot.state = DirectionFieldState::kReady; + snapshot.field = DirectionField::create(grid, geometryOf(width, height), 1.5); + snapshot.generation = generation; + return snapshot; +} + +ReferenceGraphParams quietParams() +{ + ReferenceGraphParams params; + params.debug_log = false; + return params; +} + +/** A costmap stand-in the test controls from its own thread. */ +class FakeCostmap +{ +public: + FakeCostmap(uint32_t width, uint32_t height) : geometry_(geometryOf(width, height)), grid_(corridor(width, height)), footprint_(rectangle(0.3, 0.3)) {} + + ReferenceGraphWorker::Source source() + { + ReferenceGraphWorker::Source out; + out.capture = [this](bool with_grid, ReferenceGraphInput* input) { + ++captures; + if (on_capture) + on_capture(); + std::lock_guard lock(mutex_); + if (status_ != ReferenceCaptureStatus::kReady) + return status_; + input->geometry = geometry_; + input->footprint = footprint_; + if (with_grid) + { + ++grid_captures; + input->static_layers.push_back(grid_); + } + return ReferenceCaptureStatus::kReady; + }; + out.direction = [this]() { + std::lock_guard lock(mutex_); + return direction_; + }; + return out; + } + + void setGrid(std::vector grid) + { + std::lock_guard lock(mutex_); + grid_ = std::move(grid); + } + void setStatus(ReferenceCaptureStatus status) + { + std::lock_guard lock(mutex_); + status_ = status; + } + void setDirection(DirectionFieldSnapshot direction) + { + std::lock_guard lock(mutex_); + direction_ = std::move(direction); + } + + std::atomic captures{ 0 }; + std::atomic grid_captures{ 0 }; + std::function on_capture; ///< Set before the worker starts. + +private: + std::mutex mutex_; + DirectionGeometry geometry_; + std::vector grid_; + std::vector footprint_; + ReferenceCaptureStatus status_ = ReferenceCaptureStatus::kReady; + DirectionFieldSnapshot direction_; +}; + +bool ready(const ReferenceGraphWorker& worker) { return worker.snapshot().state == ReferenceGraphState::kReady; } + +/** Holds the worker inside a capture until the test lets it go. */ +class Gate +{ +public: + void hold() + { + std::unique_lock lock(mutex_); + reached_ = true; + changed_.notify_all(); + changed_.wait(lock, [this]() { return open_; }); + } + void waitReached() + { + std::unique_lock lock(mutex_); + changed_.wait(lock, [this]() { return reached_; }); + } + void open() + { + std::lock_guard lock(mutex_); + open_ = true; + changed_.notify_all(); + } + +private: + std::mutex mutex_; + std::condition_variable changed_; + bool reached_ = false; + bool open_ = false; +}; + +class FakeLayer : public CostmapLayer +{ +public: + explicit FakeLayer(LayerType type, bool current = true) : type_(type) + { + enabled_ = true; + current_ = current; + } + LayerType getType() const override { return type_; } + void setCurrent(bool current) { current_ = current; } + void write(const std::vector& cost) { std::copy(cost.begin(), cost.end(), getCharMap()); } + +protected: + void handleImpl(const void*, const std::type_info&, const std::string&) override {} + +private: + LayerType type_; +}; + +class FakeDirectionLayer : public Layer, public DirectionFieldProvider +{ +public: + FakeDirectionLayer() { enabled_ = true; current_ = true; } + LayerType getType() const override { return LayerType::DIRECTIONAL_LAYER; } + DirectionFieldSnapshot directionSnapshot() const override + { + std::lock_guard lock(mutex_); + return snapshot_; + } + void publish(DirectionFieldSnapshot snapshot) + { + std::lock_guard lock(mutex_); + snapshot_ = std::move(snapshot); + layered_costmap_->notifyDirectionFieldChanged(); + } + +protected: + void handleImpl(const void*, const std::type_info&, const std::string&) override {} + +private: + mutable std::mutex mutex_; + DirectionFieldSnapshot snapshot_; +}; + +/** A LayeredCostmap with one static layer that already holds a map. */ +struct Costmap +{ + Costmap(uint32_t width, uint32_t height) : layered("map", false, true), layer(boost::make_shared(LayerType::STATIC_LAYER)) + { + layer->initialize(&layered, "static", nullptr); + layered.addPlugin(layer); + layered.resizeMap(width, height, kResolution, 0.0, 0.0); + layer->write(corridor(width, height)); + layered.setFootprint(rectangle(0.3, 0.3)); + } + bool ready() const { return layered.getReferenceGraphSnapshot().state == ReferenceGraphState::kReady; } + + LayeredCostmap layered; + boost::shared_ptr layer; +}; + +} // namespace + +TEST(MergeStaticLayers, LethalWinsAndUnknownNeedsEveryLayer) +{ + const std::vector merged = mergeStaticLayers({ { FREE_SPACE, LETHAL_OBSTACLE, NO_INFORMATION, NO_INFORMATION, INSCRIBED_INFLATED_OBSTACLE }, + { LETHAL_OBSTACLE, FREE_SPACE, FREE_SPACE, NO_INFORMATION, NO_INFORMATION } }); + EXPECT_EQ(merged, (std::vector{ LETHAL_OBSTACLE, LETHAL_OBSTACLE, FREE_SPACE, NO_INFORMATION, FREE_SPACE })); + EXPECT_TRUE(mergeStaticLayers({}).empty()); + EXPECT_THROW(mergeStaticLayers({ { FREE_SPACE }, { FREE_SPACE, FREE_SPACE } }), std::invalid_argument); +} + +TEST(ReferenceGraphWorker, BadInputIsRefused) +{ + FakeCostmap costmap(40, 40); + ReferenceGraphParams bad = quietParams(); + bad.spur_min_length_m = -1.0; + EXPECT_THROW(ReferenceGraphWorker(costmap.source(), bad), std::invalid_argument); + EXPECT_THROW(ReferenceGraphWorker(ReferenceGraphWorker::Source{}, quietParams()), std::invalid_argument); +} + +TEST(ReferenceGraphWorker, GoesFromPendingToReadyAndSleeps) +{ + FakeCostmap costmap(120, 60); + Gate gate; + costmap.on_capture = [&gate]() { gate.hold(); }; + ReferenceGraphWorker worker(costmap.source(), quietParams()); + gate.waitReached(); + const ReferenceGraphSnapshot pending = worker.snapshot(); + EXPECT_EQ(pending.state, ReferenceGraphState::kPending); + EXPECT_EQ(pending.graph, nullptr); + gate.open(); + + ASSERT_TRUE(waitUntil([&]() { return ready(worker); })); + const ReferenceGraphSnapshot done = worker.snapshot(); + ASSERT_NE(done.graph, nullptr); + EXPECT_NE(done.generation, pending.generation); + EXPECT_FALSE(done.graph->edges.empty()); + EXPECT_EQ(done.graph->static_cost, mergeStaticLayers({ corridor(120, 60) })); + EXPECT_EQ(done.graph->clearance_mm.size(), 120U * 60U); + EXPECT_EQ(done.graph->geometry.frame_id, "map"); + + // A ready worker does no work at all, so it costs nothing on a 2-core robot. + const int captures = costmap.captures; + std::this_thread::sleep_for(std::chrono::milliseconds(450)); + EXPECT_EQ(costmap.captures, captures); + EXPECT_EQ(worker.snapshot().generation, done.generation); +} + +TEST(ReferenceGraphWorker, RetainedSnapshotSurvivesTheNextChange) +{ + FakeCostmap costmap(120, 60); + ReferenceGraphWorker worker(costmap.source(), quietParams()); + ASSERT_TRUE(waitUntil([&]() { return ready(worker); })); + const ReferenceGraphSnapshot held = worker.snapshot(); + costmap.setGrid(corridor(120, 60)); + worker.notifyStaticChanged(); + EXPECT_EQ(worker.snapshot().graph == held.graph, false); + ASSERT_TRUE(waitUntil([&]() { return ready(worker); })); + EXPECT_FALSE(held.graph->static_cost.empty()); +} + +TEST(ReferenceGraphWorker, WaitsForTheStaticLayer) +{ + FakeCostmap costmap(120, 60); + costmap.setStatus(ReferenceCaptureStatus::kWait); + ReferenceGraphWorker worker(costmap.source(), quietParams()); + ASSERT_TRUE(waitUntil([&]() { return costmap.captures >= 2; })); + EXPECT_EQ(worker.snapshot().state, ReferenceGraphState::kPending); + EXPECT_EQ(worker.stats().step1_runs, 0U); + costmap.setStatus(ReferenceCaptureStatus::kReady); + EXPECT_TRUE(waitUntil([&]() { return ready(worker); })); +} + +TEST(ReferenceGraphWorker, NoStaticLayerStaysPending) +{ + FakeCostmap costmap(120, 60); + costmap.setStatus(ReferenceCaptureStatus::kNoStaticLayer); + ReferenceGraphWorker worker(costmap.source(), quietParams()); + ASSERT_TRUE(waitUntil([&]() { return costmap.captures >= 2; })); + EXPECT_EQ(worker.snapshot().state, ReferenceGraphState::kPending); +} + +TEST(ReferenceGraphWorker, WaitsForTheDirectionGridThenRunsOnlyStep2) +{ + FakeCostmap costmap(200, 120); + DirectionFieldSnapshot pending; + pending.state = DirectionFieldState::kPending; + costmap.setDirection(pending); + ReferenceGraphWorker worker(costmap.source(), quietParams()); + ASSERT_TRUE(waitUntil([&]() { return worker.stats().step1_runs == 1; })); + ASSERT_TRUE(waitUntil([&]() { return costmap.captures >= 2; })); + EXPECT_EQ(worker.snapshot().state, ReferenceGraphState::kPending); + EXPECT_EQ(worker.stats().step2_runs, 0U); + + costmap.setDirection(bandZone(200, 120, 7)); + worker.notifyDirectionChanged(); + ASSERT_TRUE(waitUntil([&]() { return ready(worker); })); + const ReferenceGraphSnapshot done = worker.snapshot(); + EXPECT_EQ(done.graph->direction_generation, 7U); + EXPECT_FALSE(done.graph->lanes.empty()); + EXPECT_EQ(worker.stats().step1_runs, 1U); + EXPECT_EQ(costmap.grid_captures, 1); +} + +TEST(ReferenceGraphWorker, GridOfTheOldMapIsNotUsed) +{ + FakeCostmap costmap(200, 120); + costmap.setDirection(bandZone(100, 60, 3)); + ReferenceGraphWorker worker(costmap.source(), quietParams()); + ASSERT_TRUE(waitUntil([&]() { return costmap.captures >= 2; })); + EXPECT_EQ(worker.snapshot().state, ReferenceGraphState::kPending); + costmap.setDirection(bandZone(200, 120, 4)); + worker.notifyDirectionChanged(); + ASSERT_TRUE(waitUntil([&]() { return ready(worker); })); + EXPECT_EQ(worker.snapshot().graph->direction_generation, 4U); +} + +TEST(ReferenceGraphWorker, DirectionAndFootprintChangesRunOnlyStep2) +{ + FakeCostmap costmap(120, 60); + ReferenceGraphWorker worker(costmap.source(), quietParams()); + ASSERT_TRUE(waitUntil([&]() { return ready(worker); })); + ASSERT_EQ(worker.stats().step1_runs, 1U); + + worker.notifyDirectionChanged(); + EXPECT_EQ(worker.snapshot().state, ReferenceGraphState::kPending); + EXPECT_EQ(worker.snapshot().graph, nullptr); + ASSERT_TRUE(waitUntil([&]() { return ready(worker); })); + + worker.notifyFootprintChanged(); + EXPECT_EQ(worker.snapshot().state, ReferenceGraphState::kPending); + ASSERT_TRUE(waitUntil([&]() { return ready(worker); })); + + const ReferenceGraphWorkerStats stats = worker.stats(); + EXPECT_EQ(stats.step1_runs, 1U); + EXPECT_EQ(stats.step2_runs, 3U); + EXPECT_EQ(stats.published, 3U); + EXPECT_EQ(costmap.grid_captures, 1); +} + +TEST(ReferenceGraphWorker, StaticChangeRunsBothSteps) +{ + FakeCostmap costmap(120, 60); + ReferenceGraphWorker worker(costmap.source(), quietParams()); + ASSERT_TRUE(waitUntil([&]() { return ready(worker); })); + worker.notifyStaticChanged(); + ASSERT_TRUE(waitUntil([&]() { return ready(worker); })); + EXPECT_EQ(worker.stats().step1_runs, 2U); + EXPECT_EQ(worker.stats().step2_runs, 2U); +} + +TEST(ReferenceGraphWorker, ThreeMapsInARowPublishOnlyTheLast) +{ + FakeCostmap costmap(120, 60); + Gate gate; + costmap.on_capture = [&gate]() { gate.hold(); }; + ReferenceGraphWorker worker(costmap.source(), quietParams()); + gate.waitReached(); + std::vector last = corridor(120, 60); + for (int i = 0; i < 3; ++i) + { + last[static_cast(30 * 120 + 10 + i)] = LETHAL_OBSTACLE; + costmap.setGrid(last); + worker.notifyStaticChanged(); + } + gate.open(); + ASSERT_TRUE(waitUntil([&]() { return ready(worker); })); + EXPECT_EQ(worker.snapshot().graph->static_cost, mergeStaticLayers({ last })); + EXPECT_EQ(worker.stats().published, 1U); +} + +TEST(ReferenceGraphWorker, MapDuringAComputationRestartsIt) +{ + const uint32_t size = 1500; + FakeCostmap costmap(size, size); + std::atomic first{ true }; + ReferenceGraphWorker* worker_ptr = nullptr; + std::vector changed = corridor(size, size); + changed[static_cast(size / 2) * size + size / 2] = LETHAL_OBSTACLE; + std::mutex started_mutex; + std::condition_variable started; + bool started_flag = false; + costmap.on_capture = [&]() { + if (first.exchange(false)) + { + std::lock_guard lock(started_mutex); + started_flag = true; + started.notify_all(); + } + }; + ReferenceGraphWorker worker(costmap.source(), quietParams()); + worker_ptr = &worker; + { + std::unique_lock lock(started_mutex); + started.wait(lock, [&]() { return started_flag; }); + } + costmap.setGrid(changed); + worker_ptr->notifyStaticChanged(); + ASSERT_TRUE(waitUntil([&]() { return ready(worker); })); + EXPECT_EQ(worker.snapshot().graph->static_cost, mergeStaticLayers({ changed })); + EXPECT_EQ(worker.stats().published, 1U); +} + +TEST(ReferenceGraphWorker, ExceptionStaysPendingUntilTheNextChange) +{ + FakeCostmap costmap(120, 60); + std::atomic fail{ true }; + costmap.on_capture = [&fail]() { + if (fail) + throw std::runtime_error("injected"); + }; + ReferenceGraphWorker worker(costmap.source(), quietParams()); + ASSERT_TRUE(waitUntil([&]() { return worker.stats().errors == 1; })); + EXPECT_EQ(worker.snapshot().state, ReferenceGraphState::kPending); + const int captures = costmap.captures; + std::this_thread::sleep_for(std::chrono::milliseconds(450)); + EXPECT_EQ(costmap.captures, captures); + + fail = false; + worker.notifyStaticChanged(); + EXPECT_TRUE(waitUntil([&]() { return ready(worker); })); +} + +TEST(ReferenceGraphWorker, StopsQuicklyDuringAComputation) +{ + const uint32_t size = 3000; + FakeCostmap costmap(size, size); + std::unique_ptr worker(new ReferenceGraphWorker(costmap.source(), quietParams())); + ASSERT_TRUE(waitUntil([&]() { return costmap.grid_captures >= 1; })); + // Let it get well into step 1, where the map is largest. + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + const Clock::time_point began = Clock::now(); + worker.reset(); + const double ms = std::chrono::duration(Clock::now() - began).count(); + std::printf("stopped in %.1f ms\n", ms); + EXPECT_LT(ms, 100.0); +} + +TEST(LayeredCostmapReferenceGraph, DisabledHasNoWork) +{ + Costmap costmap(120, 60); + EXPECT_EQ(costmap.layered.getReferenceGraphSnapshot().state, ReferenceGraphState::kDisabled); + costmap.layered.notifyStaticMapChanged(LayerType::STATIC_LAYER); + costmap.layered.notifyDirectionFieldChanged(); + costmap.layered.setFootprint(rectangle(0.4, 0.4)); + EXPECT_EQ(costmap.layered.getReferenceGraphSnapshot().state, ReferenceGraphState::kDisabled); + EXPECT_EQ(costmap.layered.getStaticMapRevision(LayerType::STATIC_LAYER), 1U); +} + +TEST(LayeredCostmapReferenceGraph, RollingCostmapIsRefused) +{ + LayeredCostmap rolling("map", true, true); + EXPECT_FALSE(rolling.enableReferenceGraph(quietParams())); + EXPECT_EQ(rolling.getReferenceGraphSnapshot().state, ReferenceGraphState::kDisabled); +} + +TEST(LayeredCostmapReferenceGraph, BadParametersAndASecondCallAreRefused) +{ + Costmap costmap(120, 60); + ReferenceGraphParams bad = quietParams(); + bad.min_clearance_m = -1.0; + EXPECT_FALSE(costmap.layered.enableReferenceGraph(bad)); + EXPECT_TRUE(costmap.layered.enableReferenceGraph(quietParams())); + EXPECT_FALSE(costmap.layered.enableReferenceGraph(quietParams())); +} + +TEST(LayeredCostmapReferenceGraph, MapThatArrivedBeforeEnablingCounts) +{ + Costmap costmap(120, 60); + ASSERT_TRUE(costmap.layered.enableReferenceGraph(quietParams())); + ASSERT_TRUE(waitUntil([&]() { return costmap.ready(); })); + const auto graph = costmap.layered.getReferenceGraphSnapshot().graph; + EXPECT_EQ(graph->geometry.width, 120U); + EXPECT_EQ(graph->direction_generation, 0U); + EXPECT_TRUE(graph->lanes.empty()); +} + +TEST(LayeredCostmapReferenceGraph, WaitsUntilTheLayerWroteItsMap) +{ + Costmap costmap(120, 60); + costmap.layer->setCurrent(false); + ASSERT_TRUE(costmap.layered.enableReferenceGraph(quietParams())); + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + EXPECT_EQ(costmap.layered.getReferenceGraphSnapshot().state, ReferenceGraphState::kPending); + { + boost::unique_lock lock(*costmap.layered.getCostmap()->getMutex()); + costmap.layer->setCurrent(true); + } + EXPECT_TRUE(waitUntil([&]() { return costmap.ready(); })); +} + +TEST(LayeredCostmapReferenceGraph, NoStaticLayerStaysPending) +{ + LayeredCostmap layered("map", false, true); + layered.resizeMap(120, 60, kResolution, 0.0, 0.0); + ASSERT_TRUE(layered.enableReferenceGraph(quietParams())); + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + EXPECT_EQ(layered.getReferenceGraphSnapshot().state, ReferenceGraphState::kPending); +} + +TEST(LayeredCostmapReferenceGraph, OtherLayerTypesOnlyCountARevision) +{ + Costmap costmap(120, 60); + ASSERT_TRUE(costmap.layered.enableReferenceGraph(quietParams())); + ASSERT_TRUE(waitUntil([&]() { return costmap.ready(); })); + const ReferenceGraphSnapshot before = costmap.layered.getReferenceGraphSnapshot(); + costmap.layered.notifyStaticMapChanged(LayerType::PREFERRED_LAYER); + costmap.layered.notifyStaticMapChanged(LayerType::UNPREFERRED_LAYER); + costmap.layered.notifyStaticMapChanged(LayerType::CRITICAL_LAYER); + const ReferenceGraphSnapshot after = costmap.layered.getReferenceGraphSnapshot(); + EXPECT_EQ(after.state, ReferenceGraphState::kReady); + EXPECT_EQ(after.generation, before.generation); + EXPECT_EQ(costmap.layered.getStaticMapRevision(LayerType::PREFERRED_LAYER), 1U); + EXPECT_EQ(costmap.layered.getStaticMapRevision(LayerType::STATIC_LAYER), 0U); + + costmap.layered.notifyStaticMapChanged(LayerType::STATIC_LAYER); + EXPECT_EQ(costmap.layered.getStaticMapRevision(LayerType::STATIC_LAYER), 1U); + EXPECT_EQ(costmap.layered.getReferenceGraphSnapshot().state, ReferenceGraphState::kPending); + EXPECT_TRUE(waitUntil([&]() { return costmap.ready(); })); +} + +TEST(LayeredCostmapReferenceGraph, MergesStaticLayersAndIgnoresSoftOnes) +{ + Costmap costmap(120, 60); + auto walls = boost::make_shared(LayerType::STATIC_LAYER); + auto preferred = boost::make_shared(LayerType::PREFERRED_LAYER); + for (const auto& layer : { walls, preferred }) + { + layer->initialize(&costmap.layered, "extra", nullptr); + costmap.layered.addPlugin(layer); + layer->matchSize(); + } + std::vector wall_cost(120 * 60, NO_INFORMATION); + wall_cost[30 * 120 + 60] = LETHAL_OBSTACLE; + walls->write(wall_cost); + std::vector soft_cost(120 * 60, NO_INFORMATION); + soft_cost[20 * 120 + 40] = LETHAL_OBSTACLE; + preferred->write(soft_cost); + + ASSERT_TRUE(costmap.layered.enableReferenceGraph(quietParams())); + ASSERT_TRUE(waitUntil([&]() { return costmap.ready(); })); + const auto graph = costmap.layered.getReferenceGraphSnapshot().graph; + EXPECT_EQ(graph->static_cost[30 * 120 + 60], LETHAL_OBSTACLE); + EXPECT_EQ(graph->static_cost[20 * 120 + 40], FREE_SPACE); + EXPECT_EQ(graph->static_cost[0], LETHAL_OBSTACLE); +} + +TEST(LayeredCostmapReferenceGraph, OnlyARealFootprintChangeRecomputes) +{ + Costmap costmap(120, 60); + ASSERT_TRUE(costmap.layered.enableReferenceGraph(quietParams())); + ASSERT_TRUE(waitUntil([&]() { return costmap.ready(); })); + const uint64_t generation = costmap.layered.getReferenceGraphSnapshot().generation; + costmap.layered.setFootprint(rectangle(0.3, 0.3)); + EXPECT_EQ(costmap.layered.getReferenceGraphSnapshot().generation, generation); + costmap.layered.setFootprint(rectangle(0.35, 0.3)); + EXPECT_NE(costmap.layered.getReferenceGraphSnapshot().generation, generation); + EXPECT_TRUE(waitUntil([&]() { return costmap.ready(); })); +} + +TEST(LayeredCostmapReferenceGraph, ReadsTheDirectionProviderAndFollowsIt) +{ + Costmap costmap(200, 120); + auto direction = boost::make_shared(); + direction->initialize(&costmap.layered, "direction", nullptr); + costmap.layered.addPlugin(direction); + DirectionFieldSnapshot pending; + pending.state = DirectionFieldState::kPending; + direction->publish(pending); + + ASSERT_TRUE(costmap.layered.enableReferenceGraph(quietParams())); + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + EXPECT_EQ(costmap.layered.getReferenceGraphSnapshot().state, ReferenceGraphState::kPending); + + direction->publish(bandZone(200, 120, 11)); + ASSERT_TRUE(waitUntil([&]() { return costmap.ready(); })); + const auto graph = costmap.layered.getReferenceGraphSnapshot().graph; + EXPECT_EQ(graph->direction_generation, 11U); + EXPECT_FALSE(graph->lanes.empty()); + + direction->publish(bandZone(200, 120, 12)); + ASSERT_TRUE(waitUntil([&]() { + const auto now = costmap.layered.getReferenceGraphSnapshot(); + return now.state == ReferenceGraphState::kReady && now.graph->direction_generation == 12U; + })); +} + +TEST(LayeredCostmapReferenceGraph, MasterMutexStaysFreeWhileComputing) +{ + // SEHC-sized map. The costmap update must not feel the graph, so the master mutex may be held only for the copy. + const uint32_t size = 3060; + Costmap costmap(size, size); + ASSERT_TRUE(costmap.layered.enableReferenceGraph(quietParams())); + double worst_ms = 0.0; + const Clock::time_point end = Clock::now() + std::chrono::seconds(120); + while (!costmap.ready() && Clock::now() < end) + { + const Clock::time_point began = Clock::now(); + { + boost::unique_lock lock(*costmap.layered.getCostmap()->getMutex()); + } + worst_ms = std::max(worst_ms, std::chrono::duration(Clock::now() - began).count()); + std::this_thread::sleep_for(std::chrono::microseconds(200)); + } + ASSERT_TRUE(costmap.ready()); + std::printf("longest wait for the master mutex %.2f ms\n", worst_ms); + EXPECT_LT(worst_ms, 10.0); +} + +TEST(LayeredCostmapReferenceGraph, DestroyedDuringAComputation) +{ + const uint32_t size = 2000; + std::unique_ptr costmap(new Costmap(size, size)); + ASSERT_TRUE(costmap->layered.enableReferenceGraph(quietParams())); + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + const Clock::time_point began = Clock::now(); + costmap.reset(); + const double ms = std::chrono::duration(Clock::now() - began).count(); + EXPECT_LT(ms, 100.0); +}