From 84c83786bab575ff8ac5c2c61211a6a4a574a3ef Mon Sep 17 00:00:00 2001 From: duongtd Date: Thu, 20 Aug 2026 20:19:33 +0700 Subject: [PATCH] =?UTF-8?q?feat:=20snapshot=20API=20cho=20reader=20?= =?UTF-8?q?=E2=80=94=20planner=20solve=20tr=C3=AAn=20b=E1=BA=A3n=20copy,?= =?UTF-8?q?=20h=E1=BA=BFt=20ch=E1=BA=B7n=20map-update?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Costmap2D::copyFrom: copy metadata + grid, chỉ realloc khi size đổi (operator= delete/new mỗi lần — không hợp copy định kỳ 30 Hz). Caller giữ mutex nguồn. Costmap2DROBOT: key config snapshot_for_readers (mặc định false = nguyên trạng); refreshSnapshot() khoá master mutex đúng bằng thời gian memcpy; getCostmapForRead() trả snapshot khi bật / lưới live khi tắt. Object snapshot ổn định địa chỉ, refresh tại chỗ — không tái tạo con trỏ (bài học DOUBLE_FREE_BUG_FIX_REPORT). Hợp đồng single-consumer: refresh + đọc cùng thread control loop. Kèm: load debug_level (commit trước) + fix priv_nh(priv_nh, name) tự khởi tạo từ chính nó — đổi thành (nh, name), cùng kết quả namespace, hết UB-adjacent. Verify: test_costmap 10/10 (3 test copyFrom mới), sim mission — lock_wait local 53 ms max -> 13 us, p99 cycle 21.4 -> 3.4 ms, local costmap chạy được 10 Hz với 1.2% một core. Co-Authored-By: Claude Fable 5 --- include/robot_costmap_2d/costmap_2d.h | 12 +++++ include/robot_costmap_2d/costmap_2d_robot.h | 34 ++++++++++++++ src/costmap_2d.cpp | 22 +++++++++ src/costmap_2d_robot.cpp | 44 +++++++++++++++++- test/coordinates_test.cpp | 51 +++++++++++++++++++++ 5 files changed, 161 insertions(+), 2 deletions(-) diff --git a/include/robot_costmap_2d/costmap_2d.h b/include/robot_costmap_2d/costmap_2d.h index 1740281..89d7c08 100755 --- a/include/robot_costmap_2d/costmap_2d.h +++ b/include/robot_costmap_2d/costmap_2d.h @@ -86,6 +86,18 @@ public: */ Costmap2D& operator=(const Costmap2D& map); + /** + * @brief Copy metadata and grid from another costmap, reusing the existing + * buffer when the size is unchanged (no delete/new per call). + * + * Built for periodic snapshotting (readers copy the master grid every + * control cycle): operator= reallocates on every call, this only when the + * grid size actually changed. The caller must hold the source map's mutex — + * this method does not lock the source. + * @param map The costmap to copy from + */ + void copyFrom(const Costmap2D& map); + /** * @brief Turn this costmap into a copy of a window of a costmap passed in * @param map The costmap to copy diff --git a/include/robot_costmap_2d/costmap_2d_robot.h b/include/robot_costmap_2d/costmap_2d_robot.h index 442c0c8..e84ffce 100755 --- a/include/robot_costmap_2d/costmap_2d_robot.h +++ b/include/robot_costmap_2d/costmap_2d_robot.h @@ -157,6 +157,35 @@ public: return layered_costmap_->getCostmap(); } + /** @brief Whether readers should work on a snapshot copy instead of the + * live master grid (config key "snapshot_for_readers", default false). + * + * With snapshots on, a reader calls refreshSnapshot() once per cycle and + * then reads getCostmapForRead() without holding the master mutex during + * its whole computation — the mutex is only held for the memcpy inside + * refreshSnapshot(). With snapshots off, getCostmapForRead() returns the + * live master grid and the reader must keep the legacy long lock. */ + inline bool isSnapshotEnabled() const noexcept + { + return snapshot_enabled_; + } + + /** @brief Re-copy the master grid into the internal snapshot. + * + * Locks the master mutex only for the duration of the copy. Single-consumer + * contract: refreshSnapshot() and reads of getCostmapForRead() must happen + * on the same thread (the control loop) — the snapshot itself is not + * additionally locked. No-op while snapshots are disabled. */ + void refreshSnapshot(); + + /** @brief Grid a reader should compute on: the snapshot when enabled, + * otherwise the live master costmap. + * + * The returned pointer stays stable for the lifetime of this object — + * the snapshot buffer is reused between refreshes, never reallocated as an + * object. Never returns null. */ + Costmap2D* getCostmapForRead(); + /** * @brief Returns the global frame of the costmap * @return The global frame of the costmap @@ -290,6 +319,11 @@ private: robot_geometry_msgs::PolygonStamped footprint_; float footprint_padding_; + // Reader-side snapshot of the master grid (see getCostmapForRead()). + // Stable object: refreshed in place, so readers may hold the pointer. + Costmap2D costmap_snapshot_; + bool snapshot_enabled_ = false; + private: void getParams(const std::string& config_file_name,const std::string& name, robot::NodeHandle& nh); }; diff --git a/src/costmap_2d.cpp b/src/costmap_2d.cpp index 134cb57..e7dc7f7 100755 --- a/src/costmap_2d.cpp +++ b/src/costmap_2d.cpp @@ -165,6 +165,28 @@ Costmap2D::Costmap2D(const Costmap2D& map) : *this = map; } +void Costmap2D::copyFrom(const Costmap2D& map) +{ + if (this == &map) + return; + + boost::unique_lock lock(*access_); + if (costmap_ == NULL || size_x_ != map.size_x_ || size_y_ != map.size_y_) + { + delete[] costmap_; + costmap_ = new unsigned char[static_cast(map.size_x_) * map.size_y_]; + size_x_ = map.size_x_; + size_y_ = map.size_y_; + } + + resolution_ = map.resolution_; + origin_x_ = map.origin_x_; + origin_y_ = map.origin_y_; + default_value_ = map.default_value_; + memcpy(costmap_, map.costmap_, + static_cast(size_x_) * size_y_ * sizeof(unsigned char)); +} + // just initialize everything to NULL by default Costmap2D::Costmap2D() : size_x_(0), size_y_(0), resolution_(0.0), origin_x_(0.0), origin_y_(0.0), costmap_(NULL) diff --git a/src/costmap_2d_robot.cpp b/src/costmap_2d_robot.cpp index 58a5313..906b444 100644 --- a/src/costmap_2d_robot.cpp +++ b/src/costmap_2d_robot.cpp @@ -105,7 +105,7 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name,const std::st YAML::Node config = YAML::LoadFile(path_source); YAML::Node layer = config["robot_costmap_2d"]; - robot::NodeHandle priv_nh(priv_nh, name); + robot::NodeHandle priv_nh(nh, name); std::string global_frame = loadParam(layer, "global_frame", std::string("map")); @@ -164,11 +164,27 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name,const std::st if (priv_nh.hasParam("performance_metrics_period")) priv_nh.getParam("performance_metrics_period", performance_metrics_period); + int debug_level = loadParam(layer, "debug_level", 0); + if (priv_nh.hasParam("debug_level")) + priv_nh.getParam("debug_level", debug_level); + + bool snapshot_for_readers = loadParam(layer, "snapshot_for_readers", false); + if (priv_nh.hasParam("snapshot_for_readers")) + priv_nh.getParam("snapshot_for_readers", snapshot_for_readers); + snapshot_enabled_ = snapshot_for_readers; + if (debug_level < 0 || debug_level > 2) + { + robot::log_warning("costmap '%s': debug_level %d out of [0, 2], clamped\n", + name_.c_str(), debug_level); + debug_level = std::max(0, std::min(debug_level, 2)); + } + if (priv_nh.hasParam("library_path")) path_plugins = loader.findLibraryPath(name_); layered_costmap_ = new LayeredCostmap(global_frame_, rolling_window, track_unknown_space); layered_costmap_->setPerformanceMetrics( performance_metrics_enabled, performance_metrics_period); + layered_costmap_->setDebugLevel(debug_level); // find size parameters double map_width_meters = loadParam(layer, "width", 0.0); @@ -524,10 +540,34 @@ void Costmap2DROBOT::copyParentParameters(const std::string& costmap_name, } void Costmap2DROBOT::setUnpaddedRobotFootprintPolygon(const robot_geometry_msgs::Polygon& footprint) -{ +{ setUnpaddedRobotFootprint(toPointVector(footprint)); } +void Costmap2DROBOT::refreshSnapshot() +{ + if (!snapshot_enabled_ || layered_costmap_ == NULL) + return; + + Costmap2D* master = layered_costmap_->getCostmap(); + // Master mutex held only for the copy (~us for a local-costmap grid), not + // for the reader's whole computation — that is the entire point. + boost::unique_lock lock(*(master->getMutex())); + costmap_snapshot_.copyFrom(*master); +} + +Costmap2D* Costmap2DROBOT::getCostmapForRead() +{ + if (!snapshot_enabled_) + return getCostmap(); + + // First read before any refresh (e.g. planner initialize probing the grid): + // fill the snapshot once so the reader never sees an empty map. + if (costmap_snapshot_.getCharMap() == NULL) + refreshSnapshot(); + return &costmap_snapshot_; +} + Costmap2DROBOT::~Costmap2DROBOT() { map_update_thread_shutdown_ = true; diff --git a/test/coordinates_test.cpp b/test/coordinates_test.cpp index db0b83c..3bb440f 100644 --- a/test/coordinates_test.cpp +++ b/test/coordinates_test.cpp @@ -224,6 +224,57 @@ TEST(CostmapPerformanceRegression, inflation_buckets_preserve_radial_costs) EXPECT_EQ(master.getCost(6, 3), FREE_SPACE); } +TEST(CostmapSnapshot, copy_from_copies_grid_and_metadata) +{ + Costmap2D src(10, 8, 0.05, 1.0, 2.0, FREE_SPACE); + src.setCost(3, 4, LETHAL_OBSTACLE); + src.setCost(9, 7, 42); + + Costmap2D dst; + dst.copyFrom(src); + + EXPECT_EQ(dst.getSizeInCellsX(), 10u); + EXPECT_EQ(dst.getSizeInCellsY(), 8u); + EXPECT_DOUBLE_EQ(dst.getResolution(), 0.05); + EXPECT_DOUBLE_EQ(dst.getOriginX(), 1.0); + EXPECT_DOUBLE_EQ(dst.getOriginY(), 2.0); + EXPECT_EQ(dst.getCost(3, 4), LETHAL_OBSTACLE); + EXPECT_EQ(dst.getCost(9, 7), 42); + EXPECT_EQ(dst.getCost(0, 0), FREE_SPACE); +} + +TEST(CostmapSnapshot, copy_from_reuses_buffer_when_size_unchanged) +{ + Costmap2D src(6, 6, 0.05, 0.0, 0.0, FREE_SPACE); + Costmap2D dst; + dst.copyFrom(src); + unsigned char* first_buffer = dst.getCharMap(); + + src.setCost(2, 2, LETHAL_OBSTACLE); + dst.copyFrom(src); + + // Same size: the buffer must be reused (this is the whole point of + // copyFrom vs operator=), and the fresh cell must arrive. + EXPECT_EQ(dst.getCharMap(), first_buffer); + EXPECT_EQ(dst.getCost(2, 2), LETHAL_OBSTACLE); +} + +TEST(CostmapSnapshot, copy_from_reallocates_on_resize) +{ + Costmap2D src(4, 4, 0.05, 0.0, 0.0, FREE_SPACE); + Costmap2D dst; + dst.copyFrom(src); + + Costmap2D bigger(12, 9, 0.1, -1.0, -2.0, NO_INFORMATION); + bigger.setCost(11, 8, LETHAL_OBSTACLE); + dst.copyFrom(bigger); + + EXPECT_EQ(dst.getSizeInCellsX(), 12u); + EXPECT_EQ(dst.getSizeInCellsY(), 9u); + EXPECT_EQ(dst.getCost(11, 8), LETHAL_OBSTACLE); + EXPECT_EQ(dst.getCost(0, 0), NO_INFORMATION); +} + int main(int argc, char** argv) { testing::InitGoogleTest( &argc, argv );