diff --git a/README.md b/README.md index 19710ac..e7a005d 100644 --- a/README.md +++ b/README.md @@ -50,6 +50,8 @@ This repository is organized into several ROS 2 packages: - Displays surfaces and layers. - Optional per-cell normal rendering. - Layer-based coloring. + - Optional NavCel edges (*Draw Edges*, *Edge Color*), to see the triangles of the mesh. + - Large maps drawn in chunks; geometry patches (*Patch Topic*) rebuild only the chunks they touch. - **`navmap_tools/`** Tools and utilities for building and testing NavMaps (mesh import/export, conversions, etc.) @@ -387,6 +389,21 @@ navmap::NavMap nm2 = navmap_ros::from_msg(msg); `navmap_ros::to_layer_update_msg(nm, "obstacles")` publishes only what changed since the layer's last `clear_changes()`: a sparse `NavMapLayer` (`indices` + values) when few NavCels changed, the full layer otherwise. Every `NavMap` and `NavMapLayer` message carries the map's `geometry_id`, so `from_msg` (and RViz2) reject updates meant for another geometry. +### Geometry patches + +A map whose geometry changes in a few places (e.g. a simplified copy that merges and splits NavCels) can send only those changes instead of the whole map. `navmap_ros::to_patch_msg(nm, base_geometry_id, first_vertex, navcels, surfaces)` builds a `NavMapPatch` with the new vertices (from `first_vertex` on), the rewritten NavCels (with their vertices and the value of every layer) and the replaced surfaces; links are always sent whole. The receiver applies it to the last map it has with `navmap_ros::apply_patch(patch, msg)`, which returns `false` and leaves `msg` untouched if `msg` is not the patch's base map (`geometry_id != base_geometry_id`) or the patch does not fit it: then it must wait for a full map. The RViz2 NavMap display subscribes to `_patch` by default (*Patch Topic*). + +```cpp +// publisher: the whole map the first time, patches afterwards +auto patch = navmap_ros::to_patch_msg(nm, last_sent_geometry_id, first_new_vertex, + changed_navcels, changed_surfaces, header); +patch_pub->publish(patch); +last_sent_geometry_id = nm.geometry_id(); + +// receiver +if (!navmap_ros::apply_patch(*patch, last_map_msg)) { /* wait for a full map */ } +``` + --- ## 9. Save and load from disk diff --git a/navmap_core/include/navmap_core/NavMap.hpp b/navmap_core/include/navmap_core/NavMap.hpp index 87732e1..e8f139d 100644 --- a/navmap_core/include/navmap_core/NavMap.hpp +++ b/navmap_core/include/navmap_core/NavMap.hpp @@ -584,6 +584,21 @@ class NavMap */ void rebuild_geometry_accels(); + /** + * \brief As rebuild_geometry_accels(), keeping what the caller already filled. + * + * A builder that knows the topology or a hierarchy of its NavCels (a mesh made from a tree, + * say) can fill NavCel::neighbor and each Surface's aabb / bvh / prim_indices itself, in linear + * time, and skip the sorts of the generic builders. + * \param rebuild_adjacency false: NavCel::neighbor is kept as given. + * \param rebuild_bvh false: every Surface's aabb, bvh (root at index 0) and prim_indices are + * kept as given. + * \param recompute_normals false: NavCel::normal and NavCel::area are kept as given (a builder + * that edits a few NavCels of a big map sets theirs). + */ + void rebuild_geometry_accels( + bool rebuild_adjacency, bool rebuild_bvh, bool recompute_normals = true); + /** * \brief Copy assignment optimized to avoid geometry duplication. * diff --git a/navmap_core/src/navmap_core/NavMap.cpp b/navmap_core/src/navmap_core/NavMap.cpp index 2401242..283f6c6 100644 --- a/navmap_core/src/navmap_core/NavMap.cpp +++ b/navmap_core/src/navmap_core/NavMap.cpp @@ -438,10 +438,17 @@ inline float box_sq_dist(const AABB & box, const Vec3 & p) // ----------------------------------------------------------------------------- void NavMap::rebuild_geometry_accels() +{ + rebuild_geometry_accels(true, true); +} + +void NavMap::rebuild_geometry_accels( + bool rebuild_adjacency, bool rebuild_bvh, bool recompute_normals) { geometry_dirty_ = true; // Normals and areas. for (auto & c : navcels) { + if (!recompute_normals) {break;} Vec3 a = positions.at(c.v[0]); Vec3 b = positions.at(c.v[1]); Vec3 d = positions.at(c.v[2]); @@ -450,11 +457,13 @@ void NavMap::rebuild_geometry_accels() } // Topological neighbors. - build_adjacency(); + if (rebuild_adjacency) {build_adjacency();} // Per-surface BVH and seed grid. - for (auto & s : surfaces) { - build_surface_bvh(s); + if (rebuild_bvh) { + for (auto & s : surfaces) { + build_surface_bvh(s); + } } build_navcel_surface_index_(); build_surface_tree_(); diff --git a/navmap_ros/include/navmap_ros/conversions.hpp b/navmap_ros/include/navmap_ros/conversions.hpp index c916979..725a7ee 100644 --- a/navmap_ros/include/navmap_ros/conversions.hpp +++ b/navmap_ros/include/navmap_ros/conversions.hpp @@ -36,7 +36,9 @@ * The reverse conversion reuses that layer when present. */ +#include #include +#include #include "Eigen/Core" #include "pcl/point_cloud.h" @@ -45,6 +47,7 @@ #include "sensor_msgs/msg/point_cloud2.hpp" #include "navmap_ros_interfaces/msg/nav_map.hpp" #include "navmap_ros_interfaces/msg/nav_map_layer.hpp" +#include "navmap_ros_interfaces/msg/nav_map_patch.hpp" #include "nav_msgs/msg/occupancy_grid.hpp" #include "navmap_core/Costs.hpp" #include "navmap_core/NavMap.hpp" @@ -152,6 +155,29 @@ navmap_ros_interfaces::msg::NavMapLayer to_layer_update_msg( const std_msgs::msg::Header & header = std_msgs::msg::Header(), float max_sparse_fraction = 0.25f); +/** + * @brief Patch with what changed in @p nm since a map with geometry @p base_geometry_id was sent. + * + * The caller knows what changed: the vertices from @p first_vertex on are new, the NavCels in + * @p navcels were rewritten (they carry their vertices and the value of every layer) and the + * surfaces in @p surfaces were replaced. Links are always sent whole. + */ +navmap_ros_interfaces::msg::NavMapPatch to_patch_msg( + const navmap::NavMap & nm, std::uint64_t base_geometry_id, std::uint32_t first_vertex, + const std::vector & navcels, const std::vector & surfaces, + const std_msgs::msg::Header & header = std_msgs::msg::Header()); + +/** + * @brief Applies @p patch to the NavMap message @p msg (the map a receiver keeps). + * + * @return false, leaving @p msg untouched, if @p msg is not the patch's base map + * (geometry_id != base_geometry_id) or the patch does not fit it (missing vertices, + * indices out of range, layers of another type): the receiver must wait for a full map. + */ +bool apply_patch( + const navmap_ros_interfaces::msg::NavMapPatch & patch, + navmap_ros_interfaces::msg::NavMap & msg); + /** * @brief Import a single NavMapLayer message into a NavMap. * diff --git a/navmap_ros/src/navmap_ros/conversions.cpp b/navmap_ros/src/navmap_ros/conversions.cpp index b185cbb..8f0584a 100644 --- a/navmap_ros/src/navmap_ros/conversions.cpp +++ b/navmap_ros/src/navmap_ros/conversions.cpp @@ -253,6 +253,231 @@ NavMap to_msg(const navmap::NavMap & nm) return to_msg(nm, std_msgs::msg::Header()); } +navmap_ros_interfaces::msg::NavMapPatch to_patch_msg( + const navmap::NavMap & nm, std::uint64_t base_geometry_id, std::uint32_t first_vertex, + const std::vector & navcels, const std::vector & surfaces, + const std_msgs::msg::Header & header) +{ + navmap_ros_interfaces::msg::NavMapPatch p; + p.header = header; + p.base_geometry_id = base_geometry_id; + p.geometry_id = nm.geometry_id(); + + const std::size_t nv = nm.positions.x.size(); + p.first_vertex = std::min(first_vertex, static_cast(nv)); + p.positions_x.assign(nm.positions.x.begin() + p.first_vertex, nm.positions.x.end()); + p.positions_y.assign(nm.positions.y.begin() + p.first_vertex, nm.positions.y.end()); + p.positions_z.assign(nm.positions.z.begin() + p.first_vertex, nm.positions.z.end()); + if (nm.colors.has_value()) { + p.colors_r.assign(nm.colors->r.begin() + p.first_vertex, nm.colors->r.end()); + p.colors_g.assign(nm.colors->g.begin() + p.first_vertex, nm.colors->g.end()); + p.colors_b.assign(nm.colors->b.begin() + p.first_vertex, nm.colors->b.end()); + p.colors_a.assign(nm.colors->a.begin() + p.first_vertex, nm.colors->a.end()); + } + + p.navcels_size = static_cast(nm.navcels.size()); + p.navcel_indices.reserve(navcels.size()); + p.navcels_v0.reserve(navcels.size()); + p.navcels_v1.reserve(navcels.size()); + p.navcels_v2.reserve(navcels.size()); + for (const auto c : navcels) { + if (c >= nm.navcels.size()) {continue;} + p.navcel_indices.push_back(c); + p.navcels_v0.push_back(nm.navcels[c].v[0]); + p.navcels_v1.push_back(nm.navcels[c].v[1]); + p.navcels_v2.push_back(nm.navcels[c].v[2]); + } + + for (const auto & name : nm.layers.list()) { + auto base = nm.layers.get(name); + if (!base) {continue;} + NavMapLayer l; + l.name = name; + l.type = static_cast(base->type()); + l.geometry_id = p.geometry_id; + if (const auto meta = nm.get_layer_meta(name)) { + l.description = meta->description; + l.unit = meta->unit; + l.has_unknown = meta->unknown.has_value(); + l.unknown_value = meta->unknown.value_or(0.0); + } + l.indices = p.navcel_indices; + auto gather = [&](const auto & data, auto & out) { + out.reserve(p.navcel_indices.size()); + for (const auto c : p.navcel_indices) { + using T = typename std::decay_t::value_type; + out.push_back(c < data.size() ? data[c] : T{}); + } + }; + switch (base->type()) { + case navmap::LayerType::U8: + gather(static_cast &>(*base).data(), l.data_u8); + break; + case navmap::LayerType::F32: + gather(static_cast &>(*base).data(), l.data_f32); + break; + case navmap::LayerType::F64: + gather(static_cast &>(*base).data(), l.data_f64); + break; + case navmap::LayerType::I16: + gather(static_cast &>(*base).data(), l.data_i16); + break; + } + p.layers.push_back(std::move(l)); + } + + for (const auto i : surfaces) { + if (i >= nm.surfaces.size()) {continue;} + p.surface_indices.push_back(static_cast(i)); + NavMapSurface smsg; + smsg.frame_id = nm.surfaces[i].frame_id; + smsg.navcels.assign(nm.surfaces[i].navcels.begin(), nm.surfaces[i].navcels.end()); + p.surfaces.push_back(std::move(smsg)); + } + + p.links.reserve(nm.links().size()); + for (const auto & l : nm.links()) { + navmap_ros_interfaces::msg::NavMapLink lm; + lm.from_navcel = l.from; + lm.to_navcel = l.to; + lm.type = static_cast(l.type); + lm.length = l.length; + lm.bidirectional = l.bidirectional; + p.links.push_back(lm); + } + return p; +} + +bool apply_patch(const navmap_ros_interfaces::msg::NavMapPatch & p, NavMap & msg) +{ + // Checks first: msg is left untouched if the patch does not fit it + if (msg.geometry_id != p.base_geometry_id) {return false;} + if (p.first_vertex > msg.positions_x.size()) {return false;} + const std::size_t nv = p.first_vertex + p.positions_x.size(); + if (p.positions_y.size() != p.positions_x.size() || + p.positions_z.size() != p.positions_x.size()) + { + return false; + } + const std::size_t k = p.navcel_indices.size(); + if (p.navcels_v0.size() != k || p.navcels_v1.size() != k || p.navcels_v2.size() != k) { + return false; + } + for (std::size_t i = 0; i < k; ++i) { + if (p.navcel_indices[i] >= p.navcels_size || p.navcels_v0[i] >= nv || + p.navcels_v1[i] >= nv || p.navcels_v2[i] >= nv) + { + return false; + } + } + for (const auto & l : p.layers) { + if (l.indices.size() != k) {return false;} + const std::size_t n = l.type == NavMapLayer::U8 ? l.data_u8.size() : + l.type == NavMapLayer::F32 ? l.data_f32.size() : + l.type == NavMapLayer::F64 ? l.data_f64.size() : + l.type == NavMapLayer::I16 ? l.data_i16.size() : k + 1; + if (n != k) {return false;} + for (const auto & ml : msg.layers) { + if (ml.name == l.name && ml.type != l.type) {return false;} + } + } + if (p.surfaces.size() != p.surface_indices.size()) {return false;} + + // Vertices: those up to first_vertex are kept, the rest are the patch's + auto set_tail = [&](auto & dst, const auto & src) { + dst.resize(p.first_vertex); + dst.insert(dst.end(), src.begin(), src.end()); + }; + set_tail(msg.positions_x, p.positions_x); + set_tail(msg.positions_y, p.positions_y); + set_tail(msg.positions_z, p.positions_z); + if (msg.has_vertex_rgba) { + const bool colours = p.colors_r.size() == p.positions_x.size() && + p.colors_g.size() == p.positions_x.size() && p.colors_b.size() == p.positions_x.size(); + if (colours) { + set_tail(msg.colors_r, p.colors_r); + set_tail(msg.colors_g, p.colors_g); + set_tail(msg.colors_b, p.colors_b); + if (p.colors_a.size() == p.positions_x.size()) { + set_tail(msg.colors_a, p.colors_a); + } else { + msg.colors_a.resize(nv, 255); + } + } else { + msg.colors_r.resize(nv, 0); + msg.colors_g.resize(nv, 0); + msg.colors_b.resize(nv, 0); + msg.colors_a.resize(nv, 255); + } + } + + // NavCels: the new size (new ones degenerate until written), then the rewritten ones + msg.navcels_v0.resize(p.navcels_size, 0); + msg.navcels_v1.resize(p.navcels_size, 0); + msg.navcels_v2.resize(p.navcels_size, 0); + for (std::size_t i = 0; i < k; ++i) { + const auto c = p.navcel_indices[i]; + msg.navcels_v0[c] = p.navcels_v0[i]; + msg.navcels_v1[c] = p.navcels_v1[i]; + msg.navcels_v2[c] = p.navcels_v2[i]; + } + + // Layers: every one at the new size; the patch's values on its NavCels + auto resize_layer = [&](NavMapLayer & l) { + switch (l.type) { + case NavMapLayer::U8: l.data_u8.resize(p.navcels_size, 0); break; + case NavMapLayer::F32: l.data_f32.resize(p.navcels_size, 0.0f); break; + case NavMapLayer::F64: l.data_f64.resize(p.navcels_size, 0.0); break; + case NavMapLayer::I16: l.data_i16.resize(p.navcels_size, 0); break; + default: break; + } + l.geometry_id = p.geometry_id; + }; + for (auto & l : msg.layers) { + resize_layer(l); + } + for (const auto & pl : p.layers) { + NavMapLayer * dst = nullptr; + for (auto & ml : msg.layers) { + if (ml.name == pl.name) {dst = &ml;} + } + if (!dst) { + NavMapLayer nl; + nl.name = pl.name; + nl.type = pl.type; + nl.description = pl.description; + nl.unit = pl.unit; + nl.has_unknown = pl.has_unknown; + nl.unknown_value = pl.unknown_value; + msg.layers.push_back(nl); + dst = &msg.layers.back(); + resize_layer(*dst); + } + auto scatter = [&](auto & d, const auto & src) { + for (std::size_t i = 0; i < k; ++i) { + d[pl.indices[i]] = src[i]; + } + }; + switch (pl.type) { + case NavMapLayer::U8: scatter(dst->data_u8, pl.data_u8); break; + case NavMapLayer::F32: scatter(dst->data_f32, pl.data_f32); break; + case NavMapLayer::F64: scatter(dst->data_f64, pl.data_f64); break; + case NavMapLayer::I16: scatter(dst->data_i16, pl.data_i16); break; + default: break; + } + } + + for (std::size_t i = 0; i < p.surface_indices.size(); ++i) { + const auto s = p.surface_indices[i]; + if (s >= msg.surfaces.size()) {msg.surfaces.resize(s + 1);} + msg.surfaces[s] = p.surfaces[i]; + } + msg.links = p.links; + msg.header = p.header; + msg.geometry_id = p.geometry_id; + return true; +} + navmap::NavMap from_msg(const NavMap & msg, std_msgs::msg::Header & header) { header = msg.header; diff --git a/navmap_ros/tests/CMakeLists.txt b/navmap_ros/tests/CMakeLists.txt index 76b8446..a571706 100644 --- a/navmap_ros/tests/CMakeLists.txt +++ b/navmap_ros/tests/CMakeLists.txt @@ -21,3 +21,6 @@ ament_add_gtest(test_layer_metadata_and_migration test_layer_metadata_and_migrat target_link_libraries(test_layer_metadata_and_migration ${PROJECT_NAME} ) + +ament_add_gtest(test_patch test_patch.cpp) +target_link_libraries(test_patch ${PROJECT_NAME}) diff --git a/navmap_ros/tests/test_patch.cpp b/navmap_ros/tests/test_patch.cpp new file mode 100644 index 0000000..f5199e7 --- /dev/null +++ b/navmap_ros/tests/test_patch.cpp @@ -0,0 +1,213 @@ +// Copyright 2026 Intelligent Robotics Lab +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include +#include + +#include "gtest/gtest.h" +#include "nav_msgs/msg/occupancy_grid.hpp" +#include "navmap_core/NavMap.hpp" +#include "navmap_ros/conversions.hpp" + +using navmap_ros_interfaces::msg::NavMap; + +namespace +{ + +navmap::NavMap grid_map(int cells = 8) +{ + nav_msgs::msg::OccupancyGrid g; + g.header.frame_id = "map"; + g.info.resolution = 0.5; + g.info.width = cells; + g.info.height = cells; + g.info.origin.orientation.w = 1.0; + g.data.assign(cells * cells, 0); + auto nm = navmap_ros::from_occupancy_grid(g); + for (std::size_t c = 0; c < nm.navcels.size(); ++c) { + nm.layer_set("height", static_cast(c), 0.1f * c); + } + return nm; +} + +// What a receiver keeps must be what a full conversion of the map gives. +void expect_same(const NavMap & a, const NavMap & b) +{ + EXPECT_EQ(a.geometry_id, b.geometry_id); + EXPECT_EQ(a.positions_x, b.positions_x); + EXPECT_EQ(a.positions_y, b.positions_y); + EXPECT_EQ(a.positions_z, b.positions_z); + EXPECT_EQ(a.navcels_v0, b.navcels_v0); + EXPECT_EQ(a.navcels_v1, b.navcels_v1); + EXPECT_EQ(a.navcels_v2, b.navcels_v2); + ASSERT_EQ(a.surfaces.size(), b.surfaces.size()); + for (std::size_t i = 0; i < a.surfaces.size(); ++i) { + EXPECT_EQ(a.surfaces[i].navcels, b.surfaces[i].navcels) << i; + } + ASSERT_EQ(a.layers.size(), b.layers.size()); + for (const auto & la : a.layers) { + bool found = false; + for (const auto & lb : b.layers) { + if (lb.name != la.name) {continue;} + found = true; + EXPECT_EQ(la.type, lb.type); + EXPECT_EQ(la.data_u8, lb.data_u8) << la.name; + EXPECT_EQ(la.data_f32, lb.data_f32) << la.name; + EXPECT_EQ(la.data_f64, lb.data_f64) << la.name; + EXPECT_EQ(la.data_i16, lb.data_i16) << la.name; + } + EXPECT_TRUE(found) << la.name; + } +} + +// Rewrites NavCel c onto three new vertices around (x, y), as an in-place edit does. +void rewrite(navmap::NavMap & nm, navmap::NavCelId c, float x, float y) +{ + const auto a = nm.add_vertex(Eigen::Vector3f(x, y, 0.0f)); + const auto b = nm.add_vertex(Eigen::Vector3f(x + 0.3f, y, 0.0f)); + const auto d = nm.add_vertex(Eigen::Vector3f(x, y + 0.3f, 0.0f)); + nm.navcels[c].v[0] = a; + nm.navcels[c].v[1] = b; + nm.navcels[c].v[2] = d; + nm.rebuild_geometry_accels(false, false, false); +} + +} // namespace + +TEST(NavMapPatch, ApplyingItGivesTheFullMap) +{ + auto nm = grid_map(); + auto kept = navmap_ros::to_msg(nm); + const auto base = kept.geometry_id; + const auto nv = static_cast(nm.positions.x.size()); + + rewrite(nm, 5, 10.0f, 10.0f); + nm.layer_set("occupancy", 5, 200); + nm.layer_set("height", 5, 7.0f); + nm.layer_set("occupancy", 9, 33); // a value only + + const auto p = navmap_ros::to_patch_msg(nm, base, nv, {5, 9}, {0}); + EXPECT_EQ(p.navcel_indices.size(), 2u); + EXPECT_EQ(p.positions_x.size(), 3u) << "only the new vertices"; + ASSERT_TRUE(navmap_ros::apply_patch(p, kept)); + expect_same(kept, navmap_ros::to_msg(nm)); +} + +TEST(NavMapPatch, TheMapCanGrow) +{ + auto nm = grid_map(); + auto kept = navmap_ros::to_msg(nm); + const auto base = kept.geometry_id; + const auto nv = static_cast(nm.positions.x.size()); + const auto n0 = static_cast(nm.navcels.size()); + + // Three NavCels more at the end: one written, two degenerate (as a slack of an in-place map) + const auto a = nm.add_vertex(Eigen::Vector3f(20.0f, 20.0f, 0.0f)); + const auto b = nm.add_vertex(Eigen::Vector3f(21.0f, 20.0f, 0.0f)); + const auto c = nm.add_vertex(Eigen::Vector3f(20.0f, 21.0f, 0.0f)); + nm.add_navcel(a, b, c); + nm.add_navcel(0, 0, 0); + nm.add_navcel(0, 0, 0); + nm.rebuild_geometry_accels(false, false, false); + nm.layers.resize_all(nm.navcels.size()); + nm.layer_set("occupancy", n0, 42); + + const auto p = navmap_ros::to_patch_msg(nm, base, nv, {n0, n0 + 1, n0 + 2}, {}); + ASSERT_TRUE(navmap_ros::apply_patch(p, kept)); + expect_same(kept, navmap_ros::to_msg(nm)); +} + +TEST(NavMapPatch, PatchesInAChain) +{ + auto nm = grid_map(); + auto kept = navmap_ros::to_msg(nm); + for (int k = 0; k < 4; ++k) { + const auto base = nm.geometry_id(); + const auto nv = static_cast(nm.positions.x.size()); + const auto c = static_cast(10 + k); + rewrite(nm, c, 30.0f + k, 30.0f); + nm.layer_set("height", c, -1.0f * k); + ASSERT_TRUE(navmap_ros::apply_patch(navmap_ros::to_patch_msg(nm, base, nv, {c}, {}), kept)); + } + expect_same(kept, navmap_ros::to_msg(nm)); +} + +TEST(NavMapPatch, AnotherBaseIsRejectedAndNothingChanges) +{ + auto nm = grid_map(); + auto kept = navmap_ros::to_msg(nm); + const auto before = kept; + const auto nv = static_cast(nm.positions.x.size()); + rewrite(nm, 3, 5.0f, 5.0f); + auto p = navmap_ros::to_patch_msg(nm, before.geometry_id + 1, nv, {3}, {}); + EXPECT_FALSE(navmap_ros::apply_patch(p, kept)); + EXPECT_EQ(kept, before); +} + +TEST(NavMapPatch, AMalformedPatchIsRejectedAndNothingChanges) +{ + auto nm = grid_map(); + auto kept = navmap_ros::to_msg(nm); + const auto before = kept; + const auto nv = static_cast(nm.positions.x.size()); + rewrite(nm, 3, 5.0f, 5.0f); + const auto good = navmap_ros::to_patch_msg(nm, before.geometry_id, nv, {3}, {}); + + auto p = good; + p.navcel_indices[0] = p.navcels_size; // out of range + EXPECT_FALSE(navmap_ros::apply_patch(p, kept)); + p = good; + p.navcels_v0[0] = 1000000; // a vertex nobody has + EXPECT_FALSE(navmap_ros::apply_patch(p, kept)); + p = good; + p.first_vertex = nv + 5; // vertices missing in between + EXPECT_FALSE(navmap_ros::apply_patch(p, kept)); + p = good; + p.layers[0].data_u8.clear(); // values missing + p.layers[0].data_f32.clear(); + EXPECT_FALSE(navmap_ros::apply_patch(p, kept)); + EXPECT_EQ(kept, before); +} + +TEST(NavMapPatch, ANewLayerIsCreated) +{ + auto nm = grid_map(); + auto kept = navmap_ros::to_msg(nm); + const auto base = kept.geometry_id; + const auto nv = static_cast(nm.positions.x.size()); + nm.add_layer("costs", "", "", 0); + nm.layer_set("costs", 4, 99); + // Same geometry: only a layer value; every NavCel listed so the new layer is complete + std::vector all(nm.navcels.size()); + for (std::size_t c = 0; c < all.size(); ++c) { + all[c] = static_cast(c); + } + ASSERT_TRUE(navmap_ros::apply_patch(navmap_ros::to_patch_msg(nm, base, nv, all, {}), kept)); + expect_same(kept, navmap_ros::to_msg(nm)); +} + +TEST(NavMapPatch, SurfacesAreReplaced) +{ + auto nm = grid_map(); + auto kept = navmap_ros::to_msg(nm); + const auto base = kept.geometry_id; + const auto nv = static_cast(nm.positions.x.size()); + nm.surfaces[0].navcels.resize(10); + nm.create_surface("map"); + nm.surfaces[1].navcels = {11, 12}; + ASSERT_TRUE(navmap_ros::apply_patch(navmap_ros::to_patch_msg(nm, base, nv, {}, {0, 1}), kept)); + ASSERT_EQ(kept.surfaces.size(), 2u); + EXPECT_EQ(kept.surfaces[0].navcels.size(), 10u); + EXPECT_EQ(kept.surfaces[1].navcels, (std::vector{11, 12})); +} diff --git a/navmap_ros_interfaces/CMakeLists.txt b/navmap_ros_interfaces/CMakeLists.txt index c2f70a4..51b7127 100644 --- a/navmap_ros_interfaces/CMakeLists.txt +++ b/navmap_ros_interfaces/CMakeLists.txt @@ -19,6 +19,7 @@ rosidl_generate_interfaces(${PROJECT_NAME} "msg/NavMapSurface.msg" "msg/NavMapLayer.msg" "msg/NavMapLink.msg" + "msg/NavMapPatch.msg" "msg/NavMapV1.msg" "msg/NavMapLayerV1.msg" DEPENDENCIES builtin_interfaces std_msgs diff --git a/navmap_ros_interfaces/msg/NavMapPatch.msg b/navmap_ros_interfaces/msg/NavMapPatch.msg new file mode 100644 index 0000000..25c1b7f --- /dev/null +++ b/navmap_ros_interfaces/msg/NavMapPatch.msg @@ -0,0 +1,38 @@ +# Changes to a NavMap already sent: the map with geometry_id = base_geometry_id becomes the one +# with geometry_id. A receiver whose map is not the base ignores it and waits for a full NavMap. +# +# Vertices are only added (from first_vertex on). The NavCels in navcel_indices are rewritten +# (vertices and the value of every layer); the map ends with navcels_size NavCels (new ones not +# listed are degenerate: vertices 0, 0, 0). Surfaces in surface_indices are replaced. Neighbours +# are not sent (as in NavMap): a receiver that needs them rebuilds the adjacency. + +std_msgs/Header header + +uint64 base_geometry_id +uint64 geometry_id + +uint32 first_vertex +float32[] positions_x +float32[] positions_y +float32[] positions_z + +# Colours of the new vertices, when the map has vertex colours +uint8[] colors_r +uint8[] colors_g +uint8[] colors_b +uint8[] colors_a + +uint32 navcels_size +uint32[] navcel_indices +uint32[] navcels_v0 +uint32[] navcels_v1 +uint32[] navcels_v2 + +# Every layer, sparse: indices = navcel_indices +navmap_ros_interfaces/NavMapLayer[] layers + +uint32[] surface_indices +navmap_ros_interfaces/NavMapSurface[] surfaces + +# All the links of the map (they are few) +navmap_ros_interfaces/NavMapLink[] links diff --git a/navmap_rviz_plugin/include/navmap_rviz_plugin/NavMapDisplay.hpp b/navmap_rviz_plugin/include/navmap_rviz_plugin/NavMapDisplay.hpp index 191dd60..67b6bfe 100644 --- a/navmap_rviz_plugin/include/navmap_rviz_plugin/NavMapDisplay.hpp +++ b/navmap_rviz_plugin/include/navmap_rviz_plugin/NavMapDisplay.hpp @@ -20,6 +20,7 @@ #include #include #include +#include #include "QObject" #include "OgreHardwareVertexBuffer.h" @@ -28,6 +29,7 @@ #include "rclcpp/subscription.hpp" #include "rviz_common/message_filter_display.hpp" #include "rviz_common/properties/bool_property.hpp" +#include "rviz_common/properties/color_property.hpp" #include "rviz_common/properties/enum_property.hpp" #include "rviz_common/properties/float_property.hpp" #include "rviz_common/properties/qos_profile_property.hpp" @@ -36,7 +38,9 @@ #include "rviz_common/display_context.hpp" #include "navmap_ros_interfaces/msg/nav_map.hpp" #include "navmap_ros_interfaces/msg/nav_map_layer.hpp" +#include "navmap_ros_interfaces/msg/nav_map_patch.hpp" #include "navmap_core/NavMap.hpp" +#include "navmap_ros/conversions.hpp" #if defined _WIN32 || defined __CYGWIN__ #ifdef __GNUC__ @@ -73,6 +77,20 @@ namespace navmap_rviz_plugin { inline navmap::NavMap received_navmap; +/// The last map a NavMapDisplay showed, and whether received_navmap is older than it. +inline navmap_ros_interfaces::msg::NavMap::SharedPtr received_msg; +inline bool received_stale{false}; + +/// The NavMap last shown (for the tools: raycast on click), built from it when first needed: a +/// map or patch that arrives costs nothing here. +inline navmap::NavMap & current_received_navmap() +{ + if (received_stale && received_msg) { + received_navmap = navmap_ros::from_msg(*received_msg); + received_stale = false; + } + return received_navmap; +} class NAVMAP_RVIZ_PLUGIN_PUBLIC NavMapDisplay : public rviz_common::MessageFilterDisplay @@ -82,6 +100,7 @@ class NAVMAP_RVIZ_PLUGIN_PUBLIC NavMapDisplay using MFDClass = rviz_common::MessageFilterDisplay; using NavMapMsg = navmap_ros_interfaces::msg::NavMap; using NavMapLayerMsg = navmap_ros_interfaces::msg::NavMapLayer; + using NavMapPatchMsg = navmap_ros_interfaces::msg::NavMapPatch; public: NavMapDisplay(); @@ -97,8 +116,10 @@ class NAVMAP_RVIZ_PLUGIN_PUBLIC NavMapDisplay private Q_SLOTS: void updateLayerUpdateTopic(); + void updatePatchTopic(); void onLayerSelectionChanged(); void onDrawNormalsChanged(); + void onDrawEdgesChanged(); void onDrawLinksChanged(); void onAlphaChanged(); void onNormalScaleChanged(); @@ -109,6 +130,9 @@ private Q_SLOTS: void subscribeToLayerTopic(); void unsubscribeToLayerTopic(); void incomingLayer(const NavMapLayerMsg::ConstSharedPtr & msg); + void subscribeToPatchTopic(); + void unsubscribeToPatchTopic(); + void incomingPatch(const NavMapPatchMsg::ConstSharedPtr & msg); // Data helpers void rebuildLayerIndex_(); @@ -119,13 +143,40 @@ private Q_SLOTS: // Rendering void updateGeometry_(); // Build geometry (first time) and update colors. void updateNormals_(); // Rebuild normals debug object. + void updateEdges_(); // Rebuild the edges of the NavCels (one line per edge). void updateLinks_(); // Rebuild the links between non-adjacent NavCels. void updateColorSchemeOptions_(); // Refresh color-scheme choices for current layer. - // Mesh/Entity path (Option B) - void ensureMeshBuilt_(); // Build static mesh once from last_msg_. - void destroyMesh_(); // Destroy entity/mesh and related buffers. - void updateColorsOnly_(); // Overwrite color buffer (fast path, no geometry rebuild). + // The mesh, in chunks of kChunkCels NavCels: a patch rebuilds only the chunks it touches. + // Each chunk: a static mesh, its entity, a dynamic colour buffer and its edges. + struct Chunk + { + Ogre::Entity * entity{nullptr}; + Ogre::SharedPtr mesh; + Ogre::HardwareVertexBufferSharedPtr colour; + Ogre::ManualObject * edges{nullptr}; + }; + static constexpr std::size_t kChunkCels = 65536; + + // How the selected layer is coloured, computed once for all the chunks + struct ColourCtx + { + const NavMapLayerMsg * layer{nullptr}; + bool vertex_colours{false}; + bool is_u8{false}; + bool logodds{false}; + bool rainbow{false}; + float min_val{0.0f}, max_val{0.0f}, alpha{1.0f}; + }; + + void ensureMeshBuilt_(); // Builds the chunks missing from last_msg_. + void destroyMesh_(); // Destroys every chunk. + void buildChunk_(std::size_t k); // (Re)builds the geometry of chunk k. + void destroyChunk_(Chunk & chunk); + ColourCtx colourContext_() const; + void colourChunk_(std::size_t k, const ColourCtx & ctx); + void edgesChunk_(std::size_t k); + void updateColorsOnly_(); // Recolours every chunk (no geometry rebuild). private: // ---- RViz properties ---- @@ -135,6 +186,8 @@ private Q_SLOTS: rviz_common::properties::EnumProperty * color_scheme_property_{nullptr}; rviz_common::properties::BoolProperty * draw_normals_property_{nullptr}; rviz_common::properties::BoolProperty * draw_links_property_{nullptr}; + rviz_common::properties::BoolProperty * draw_edges_property_{nullptr}; + rviz_common::properties::ColorProperty * edge_color_property_{nullptr}; rviz_common::properties::FloatProperty * normal_scale_property_{nullptr}; rviz_common::properties::FloatProperty * alpha_property_{nullptr}; rviz_common::properties::StringProperty * info_property_{nullptr}; @@ -143,6 +196,9 @@ private Q_SLOTS: rclcpp::QoS layer_profile_{rclcpp::QoS(5)}; rclcpp::Subscription::SharedPtr layer_subscription_; rclcpp::Time layer_subscription_start_time_; + rviz_common::properties::RosTopicProperty * patch_topic_property_{nullptr}; + rclcpp::Subscription::SharedPtr patch_subscription_; + std::uint64_t patch_count_{0}; // ---- Status counters ---- std::uint64_t navmap_msg_count_{0}; @@ -159,12 +215,8 @@ private Q_SLOTS: Ogre::ManualObject * normals_obj_{nullptr}; Ogre::ManualObject * links_obj_{nullptr}; - // Option B: static mesh + entity + dynamic colour buffer - Ogre::Entity * entity_{nullptr}; - Ogre::SharedPtr mesh_; // Ogre::MeshPtr - Ogre::HardwareVertexBufferSharedPtr colour_vbuf_; - uint16_t colour_vbuf_source_{0}; // which stream holds VES_DIFFUSE - bool mesh_built_{false}; + std::vector chunks_; + std::string material_; ///< vertex-colour material shared by the chunks }; } // namespace navmap_rviz_plugin diff --git a/navmap_rviz_plugin/src/navmap_rviz_plugin/NavMapDisplay.cpp b/navmap_rviz_plugin/src/navmap_rviz_plugin/NavMapDisplay.cpp index 4d3ef6d..2804741 100644 --- a/navmap_rviz_plugin/src/navmap_rviz_plugin/NavMapDisplay.cpp +++ b/navmap_rviz_plugin/src/navmap_rviz_plugin/NavMapDisplay.cpp @@ -18,6 +18,8 @@ #include #include #include +#include +#include #include #include @@ -125,6 +127,13 @@ NavMapDisplay::NavMapDisplay() layer_profile_property_ = new rviz_common::properties::QosProfileProperty( layer_topic_property_, layer_profile_); + patch_topic_property_ = new rviz_common::properties::RosTopicProperty( + "Patch Topic", "", + rosidl_generator_traits::name(), + "Topic of type navmap_ros_interfaces/NavMapPatch: changes to the map since the last one, " + "applied to it (only the changed parts of the mesh are rebuilt). Empty: _patch.", + this, SLOT(updatePatchTopic())); + color_scheme_property_ = new rviz_common::properties::EnumProperty( "Color Scheme", "Heat", "Color mapping for the active layer. U8: Occupancy. Float: Heat or Rainbow.", @@ -137,6 +146,14 @@ NavMapDisplay::NavMapDisplay() "Draw the links between non-adjacent NavCels (stairs, elevators, doors...), coloured by type.", this, SLOT(onDrawLinksChanged())); + draw_edges_property_ = new rviz_common::properties::BoolProperty( + "Draw Edges", false, + "Draw the edges of every NavCel (once each), to see the triangles of the mesh.", + this, SLOT(onDrawEdgesChanged())); + edge_color_property_ = new rviz_common::properties::ColorProperty( + "Edge Color", QColor(255, 255, 255), "Colour of the NavCel edges.", draw_edges_property_, + SLOT(onDrawEdgesChanged()), this); + normal_scale_property_ = new rviz_common::properties::FloatProperty( "Normal Scale", 0.15f, "Scale of the per-triangle normal arrow/line.", this, SLOT(onNormalScaleChanged())); @@ -211,6 +228,7 @@ void NavMapDisplay::reset() navmap_msg_count_ = 0; layer_update_count_ = 0; + patch_count_ = 0; last_navmap_stamp_ = rclcpp::Time(0, 0, RCL_ROS_TIME); last_layer_stamp_ = rclcpp::Time(0, 0, RCL_ROS_TIME); setStatus(rviz_common::properties::StatusProperty::Ok, "NavMap Topic", "waiting for messages…"); @@ -218,6 +236,7 @@ void NavMapDisplay::reset() destroyMesh_(); updateNormals_(); + updateEdges_(); updateLinks_(); } @@ -225,11 +244,13 @@ void NavMapDisplay::onEnable() { MFDClass::onEnable(); subscribeToLayerTopic(); + subscribeToPatchTopic(); } void NavMapDisplay::onDisable() { unsubscribeToLayerTopic(); + unsubscribeToPatchTopic(); MFDClass::onDisable(); } @@ -250,8 +271,17 @@ void NavMapDisplay::processMessage(const NavMapMsg::ConstSharedPtr msg) root_node_->setPosition(position); root_node_->setOrientation(orientation); + // A map with other geometry (same number of NavCels or not: a map edited in place keeps it) + // needs its mesh built again; the same geometry only needs new colours + const bool same_geometry = last_msg_ && + last_msg_->positions_x == msg->positions_x && last_msg_->positions_y == msg->positions_y && + last_msg_->positions_z == msg->positions_z && last_msg_->navcels_v0 == msg->navcels_v0 && + last_msg_->navcels_v1 == msg->navcels_v1 && last_msg_->navcels_v2 == msg->navcels_v2; + if (!same_geometry) {destroyMesh_();} + last_msg_ = std::make_shared(*msg); - received_navmap = navmap_ros::from_msg(*last_msg_); + received_msg = last_msg_; // the tools build their NavMap from it when they need it + received_stale = true; ++navmap_msg_count_; last_navmap_stamp_ = rviz_ros_node_.lock()->get_raw_node()->now(); @@ -277,11 +307,16 @@ void NavMapDisplay::processMessage(const NavMapMsg::ConstSharedPtr msg) layer_topic_property_->setStdString(topic_property_->getTopicStd() + "_layers"); updateLayerUpdateTopic(); } + if (patch_topic_property_->isEmpty() && !topic_property_->isEmpty()) { + patch_topic_property_->setStdString(topic_property_->getTopicStd() + "_patch"); + updatePatchTopic(); + } // Build/refresh mesh and color buffer ensureMeshBuilt_(); updateColorsOnly_(); updateNormals_(); + if (!same_geometry) {updateEdges_();} updateLinks_(); context_->queueRender(); @@ -344,6 +379,96 @@ void NavMapDisplay::updateLayerUpdateTopic() context_->queueRender(); } +void NavMapDisplay::subscribeToPatchTopic() +{ + if (!isEnabled() || patch_topic_property_->isEmpty()) {return;} + try { + auto node = rviz_ros_node_.lock()->get_raw_node(); + patch_subscription_ = node->create_subscription( + patch_topic_property_->getTopicStd(), rclcpp::QoS(10).reliable(), + [this](NavMapPatchMsg::ConstSharedPtr msg) {incomingPatch(msg);}); + setStatus(rviz_common::properties::StatusProperty::Ok, "Patch Topic", "OK"); + } catch (const std::exception & e) { + setStatus(rviz_common::properties::StatusProperty::Error, + "Patch Topic", QString("Failed to subscribe: ") + e.what()); + } +} + +void NavMapDisplay::unsubscribeToPatchTopic() +{ + patch_subscription_.reset(); +} + +void NavMapDisplay::updatePatchTopic() +{ + unsubscribeToPatchTopic(); + subscribeToPatchTopic(); + context_->queueRender(); +} + +// Changes to the map shown: applied to it, and only the chunks of the mesh they touch are built +// again. A patch for another map is ignored until the next whole map arrives. +void NavMapDisplay::incomingPatch(const NavMapPatchMsg::ConstSharedPtr & msg) +{ + if (!last_msg_) { + setStatus(rviz_common::properties::StatusProperty::Warn, "Patch Topic", + "Patch before any NavMap: waiting for a whole map"); + return; + } + const std::size_t old_cels = last_msg_->navcels_v0.size(); + const std::size_t old_layers = last_msg_->layers.size(); + if (!navmap_ros::apply_patch(*msg, *last_msg_)) { + setStatus(rviz_common::properties::StatusProperty::Warn, "Patch Topic", + "A patch for another map: waiting for the next whole map"); + return; + } + received_stale = true; + rebuildLayerIndex_(); + if (last_msg_->layers.size() != old_layers) { + repopulateLayerEnum_(); + updateColorSchemeOptions_(); + } + + // Chunks touched: those of the rewritten NavCels, and the new ones at the end + const std::size_t n = last_msg_->navcels_v0.size(); + const std::size_t nchunks = (n + kChunkCels - 1) / kChunkCels; + std::vector touched(nchunks, 0); + for (const auto c : msg->navcel_indices) { + if (c < n) {touched[c / kChunkCels] = 1;} + } + if (n != old_cels) { + for (std::size_t k = std::min(old_cels, n) / kChunkCels; k < nchunks; ++k) { + touched[k] = 1; + } + } + while (chunks_.size() > nchunks) { + destroyChunk_(chunks_.back()); + chunks_.pop_back(); + } + chunks_.resize(nchunks); + const auto ctx = colourContext_(); + std::size_t rebuilt = 0; + for (std::size_t k = 0; k < nchunks; ++k) { + if (!touched[k] && chunks_[k].entity) {continue;} + buildChunk_(k); + colourChunk_(k, ctx); + edgesChunk_(k); + ++rebuilt; + } + if (draw_normals_property_->getBool()) {updateNormals_();} + updateLinks_(); + + ++patch_count_; + info_property_->setStdString( + "Surfaces: " + std::to_string(last_msg_->surfaces.size()) + + " | Triangles: " + std::to_string(n)); + setStatus(rviz_common::properties::StatusProperty::Ok, "Patch Topic", + QString("OK — patches: %1 | last: %2 NavCels, %3 of %4 chunks rebuilt") + .arg(qulonglong(patch_count_)).arg(qulonglong(msg->navcel_indices.size())) + .arg(qulonglong(rebuilt)).arg(qulonglong(nchunks))); + context_->queueRender(); +} + void NavMapDisplay::incomingLayer(const NavMapLayerMsg::ConstSharedPtr & msg) { if (!last_msg_) { @@ -553,11 +678,40 @@ void NavMapDisplay::onColorSchemeChanged() context_->queueRender(); } -// ----- Mesh/Entity: build once, recolor fast ----- +// ----- Mesh in chunks: built once, recoloured fast; a patch rebuilds only its chunks ----- void NavMapDisplay::ensureMeshBuilt_() { - if (mesh_built_ || !context_ || !last_msg_) {return;} + if (!context_ || !last_msg_) {return;} + const std::size_t n = last_msg_->navcels_v0.size(); + if (n == 0 || last_msg_->positions_x.empty()) {return;} + const std::size_t nchunks = (n + kChunkCels - 1) / kChunkCels; + while (chunks_.size() > nchunks) { + destroyChunk_(chunks_.back()); + chunks_.pop_back(); + } + chunks_.resize(nchunks); + for (std::size_t k = 0; k < nchunks; ++k) { + if (!chunks_[k].entity) {buildChunk_(k);} + } +} + +void NavMapDisplay::buildChunk_(std::size_t k) +{ + if (!context_ || !last_msg_ || k >= chunks_.size()) {return;} + auto * sm = context_->getSceneManager(); + Chunk & ch = chunks_[k]; + // the geometry again; the edges are rebuilt apart (edgesChunk_) + if (ch.entity) { + ch.entity->detachFromParent(); + sm->destroyEntity(ch.entity); + ch.entity = nullptr; + } + if (ch.mesh) { + Ogre::MeshManager::getSingleton().remove(ch.mesh->getHandle()); + ch.mesh.reset(); + } + ch.colour.reset(); const auto & X = last_msg_->positions_x; const auto & Y = last_msg_->positions_y; @@ -565,292 +719,267 @@ void NavMapDisplay::ensureMeshBuilt_() const auto & V0 = last_msg_->navcels_v0; const auto & V1 = last_msg_->navcels_v1; const auto & V2 = last_msg_->navcels_v2; + const std::size_t first = k * kChunkCels; + const std::size_t last = std::min(V0.size(), first + kChunkCels); + if (first >= last) {return;} + const std::size_t nv = X.size(); - if (X.empty() || Y.empty() || Z.empty() || V0.empty() || V1.empty() || V2.empty()) { - return; - } - - // 1) Build a ManualObject once to get vertex/index streams, with a neutral colour - Ogre::ManualObject * mo = context_->getSceneManager()->createManualObject(); + // 1) Positions (one vertex per corner: colours are per NavCel), with a neutral colour + Ogre::ManualObject * mo = sm->createManualObject(); mo->setDynamic(false); mo->begin("BaseWhiteNoLighting", Ogre::RenderOperation::OT_TRIANGLE_LIST); - const Ogre::ColourValue neutral(0.7f, 0.7f, 0.7f, alpha_property_->getFloat()); - for (size_t t = 0; t < V0.size(); ++t) { - const uint32_t i0 = V0[t], i1 = V1[t], i2 = V2[t]; - mo->position(X[i0], Y[i0], Z[i0]); mo->colour(neutral); - mo->position(X[i1], Y[i1], Z[i1]); mo->colour(neutral); - mo->position(X[i2], Y[i2], Z[i2]); mo->colour(neutral); + for (std::size_t t = first; t < last; ++t) { + for (const uint32_t i : {V0[t], V1[t], V2[t]}) { + if (i < nv) {mo->position(X[i], Y[i], Z[i]);} else {mo->position(0.0f, 0.0f, 0.0f);} + mo->colour(neutral); + } } mo->end(); - // 2) Convert to Mesh and create Entity static int mesh_counter = 0; const std::string mesh_name = "NavMapMesh_" + std::to_string(++mesh_counter); - Ogre::MeshPtr m = mo->convertToMesh(mesh_name); - - // Material with vertex-colour tracking - Ogre::MaterialPtr base = Ogre::MaterialManager::getSingleton().getByName("BaseWhiteNoLighting"); - Ogre::MaterialPtr mat = base->clone(mesh_name + "/mat"); - mat->setLightingEnabled(false); - // For alpha < 1 you may uncomment: - // auto * pass = mat->getTechnique(0)->getPass(0); - // pass->setSceneBlending(Ogre::SBT_TRANSPARENT_ALPHA); - // pass->setDepthWriteEnabled(false); - mat->getTechnique(0)->getPass(0)->setVertexColourTracking(Ogre::TVC_AMBIENT | Ogre::TVC_DIFFUSE); - - // Destroy temp ManualObject + ch.mesh = mo->convertToMesh(mesh_name); mo->detachFromParent(); - context_->getSceneManager()->destroyManualObject(mo); + sm->destroyManualObject(mo); + + // Material with vertex-colour tracking, shared by the chunks + if (material_.empty()) { + Ogre::MaterialPtr base = + Ogre::MaterialManager::getSingleton().getByName("BaseWhiteNoLighting"); + Ogre::MaterialPtr mat = base->clone(mesh_name + "/mat"); + mat->setLightingEnabled(false); + mat->getTechnique(0)->getPass(0)->setVertexColourTracking( + Ogre::TVC_AMBIENT | Ogre::TVC_DIFFUSE); + material_ = mat->getName(); + } - // Create entity and attach to our node - entity_ = context_->getSceneManager()->createEntity(mesh_name); - entity_->setMaterialName(mat->getName()); + ch.entity = sm->createEntity(mesh_name); + ch.entity->setMaterialName(material_); if (!root_node_) { - root_node_ = context_->getSceneManager()->getRootSceneNode()->createChildSceneNode(); + root_node_ = sm->getRootSceneNode()->createChildSceneNode(); } - root_node_->attachObject(entity_); + root_node_->attachObject(ch.entity); - // Keep mesh/shared pointers - mesh_ = m; - - // 3) Move VES_DIFFUSE to its own vertex buffer (dedicated colour stream) - Ogre::SubMesh * sub = mesh_->getSubMesh(0); - Ogre::VertexData * vdata = sub->useSharedVertices ? mesh_->sharedVertexData : sub->vertexData; + // 2) The colour in its own dynamic vertex buffer, rewritten without touching the positions + Ogre::SubMesh * sub = ch.mesh->getSubMesh(0); + Ogre::VertexData * vdata = sub->useSharedVertices ? ch.mesh->sharedVertexData : sub->vertexData; Ogre::VertexDeclaration * decl = vdata->vertexDeclaration; Ogre::VertexBufferBinding * bind = vdata->vertexBufferBinding; - - const size_t vertex_count = vdata->vertexCount; - - // Remove any existing colour element (usually in source 0). Some Ogre builds provide - // removeElement by semantic; if not, rebuild via iteration—here we try semantic removal first. if (decl->findElementBySemantic(Ogre::VES_DIFFUSE)) { -#if OGRE_VERSION_MAJOR > 1 || (OGRE_VERSION_MAJOR == 1 && (OGRE_VERSION_MINOR > 12 || \ - (OGRE_VERSION_MINOR == 12 && OGRE_VERSION_PATCH >= 0))) - // Many vendors carry removeElement(VES_DIFFUSE) decl->removeElement(Ogre::VES_DIFFUSE); -#else - // Fallback: rebuild declaration without VES_DIFFUSE - Ogre::VertexDeclaration * newDecl = context_->getSceneManager()->createVertexDeclaration(); - for (uint16_t s = 0; s < decl->getElementCount(); ++s) { - const Ogre::VertexElement & e = decl->getElement(s); - if (e.getSemantic() == Ogre::VES_DIFFUSE) {continue;} - newDecl->addElement(e.getSource(), e.getOffset(), e.getType(), e.getSemantic(), e.getIndex()); - } - // Copy back - *decl = *newDecl; -#endif } - - // Choose a free binding source for colours (avoid clashing with positions/normals) - uint16_t COLOR_SRC = 1; - while (bind->isBufferBound(COLOR_SRC)) {++COLOR_SRC;} - - // Create the dynamic colour buffer (one 32-bit colour per vertex) + uint16_t src = 1; + while (bind->isBufferBound(src)) {++src;} // the render system's own packing (ABGR with OpenGL, ARGB with D3D): a fixed ARGB swaps red and // blue where it is not the native one const Ogre::VertexElementType col_type = nativeColourType_(); - decl->addElement(COLOR_SRC, /*offset=*/0, col_type, Ogre::VES_DIFFUSE); - - Ogre::HardwareVertexBufferSharedPtr colour_vbuf = - Ogre::HardwareBufferManager::getSingleton().createVertexBuffer( - Ogre::VertexElement::getTypeSize(col_type), // should be 4 - vertex_count, - Ogre::HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY_DISCARDABLE); - - bind->setBinding(COLOR_SRC, colour_vbuf); - - // Store for fast recolour - colour_vbuf_ = colour_vbuf; - colour_vbuf_source_ = COLOR_SRC; - - mesh_built_ = true; + decl->addElement(src, 0, col_type, Ogre::VES_DIFFUSE); + ch.colour = Ogre::HardwareBufferManager::getSingleton().createVertexBuffer( + Ogre::VertexElement::getTypeSize(col_type), vdata->vertexCount, + Ogre::HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY_DISCARDABLE); + bind->setBinding(src, ch.colour); } -void NavMapDisplay::destroyMesh_() +void NavMapDisplay::destroyChunk_(Chunk & ch) { if (!context_) {return;} - - if (entity_) { - entity_->detachFromParent(); - context_->getSceneManager()->destroyEntity(entity_); - entity_ = nullptr; + auto * sm = context_->getSceneManager(); + if (ch.entity) { + ch.entity->detachFromParent(); + sm->destroyEntity(ch.entity); + ch.entity = nullptr; + } + if (ch.mesh) { + Ogre::MeshManager::getSingleton().remove(ch.mesh->getHandle()); + ch.mesh.reset(); } - if (mesh_) { - Ogre::MeshManager::getSingleton().remove(mesh_->getHandle()); - mesh_.reset(); + ch.colour.reset(); + if (ch.edges) { + ch.edges->detachFromParent(); + sm->destroyManualObject(ch.edges); + ch.edges = nullptr; } - colour_vbuf_.reset(); - mesh_built_ = false; } -void NavMapDisplay::updateColorsOnly_() +void NavMapDisplay::destroyMesh_() { - if (!mesh_built_ || !last_msg_ || !entity_ || !mesh_) {return;} - - const auto & V0 = last_msg_->navcels_v0; - const auto & V1 = last_msg_->navcels_v1; - const auto & V2 = last_msg_->navcels_v2; - if (V0.empty() || V1.empty() || V2.empty()) {return;} + for (auto & ch : chunks_) { + destroyChunk_(ch); + } + chunks_.clear(); +} - // Resolve active layer and scheme +NavMapDisplay::ColourCtx NavMapDisplay::colourContext_() const +{ + ColourCtx ctx; + if (!last_msg_) {return ctx;} + const std::size_t n = last_msg_->navcels_v0.size(); + ctx.alpha = alpha_property_->getFloat(); + ctx.rainbow = (color_scheme_property_->getStdString() == "Rainbow"); const std::string sel = currentSelectedLayer_(); - const float alpha = alpha_property_->getFloat(); - const bool use_rainbow = (color_scheme_property_->getStdString() == "Rainbow"); - - const NavMapLayerMsg * selected_layer = nullptr; - bool vertex_color_mode = false; - auto it = layers_by_name_.find(sel); if (it != layers_by_name_.end()) { - selected_layer = it->second; + ctx.layer = it->second; } else if (sel == kVertexColorLayerName) { - vertex_color_mode = last_msg_->has_vertex_rgba && + ctx.vertex_colours = last_msg_->has_vertex_rgba && last_msg_->colors_r.size() == last_msg_->positions_x.size() && last_msg_->colors_g.size() == last_msg_->positions_x.size() && last_msg_->colors_b.size() == last_msg_->positions_x.size(); } - - float max_val = 0.0f, min_val = 0.0f; - bool is_u8 = false; - if (selected_layer) { - const auto & L = *selected_layer; - if (L.type == NavMapLayerMsg::U8 && L.data_u8.size() == V0.size()) { - is_u8 = true; - } else if (L.type == NavMapLayerMsg::I16 && L.data_i16.size() == V0.size()) { + if (ctx.layer) { + const auto & L = *ctx.layer; + if (L.type == NavMapLayerMsg::U8 && L.data_u8.size() == n) { + ctx.is_u8 = true; + } else if (L.type == NavMapLayerMsg::I16 && L.data_i16.size() == n) { if (!L.data_i16.empty()) { const auto [lo, hi] = std::minmax_element(L.data_i16.begin(), L.data_i16.end()); - min_val = *lo; - max_val = *hi; + ctx.min_val = *lo; + ctx.max_val = *hi; } - } else if (L.type == NavMapLayerMsg::F32 && L.data_f32.size() == V0.size()) { + ctx.logodds = isLogoddsLayer(L); + } else if (L.type == NavMapLayerMsg::F32 && L.data_f32.size() == n) { for (float v : L.data_f32) { - max_val = std::max(max_val, v); + ctx.max_val = std::max(ctx.max_val, v); } - } else if (L.type == NavMapLayerMsg::F64 && L.data_f64.size() == V0.size()) { + } else if (L.type == NavMapLayerMsg::F64 && L.data_f64.size() == n) { for (double v : L.data_f64) { - max_val = std::max(max_val, static_cast(v)); + ctx.max_val = std::max(ctx.max_val, static_cast(v)); } } else { - selected_layer = nullptr; // fallback to neutral grey - } - } - - // Access our dedicated colour buffer - if (!colour_vbuf_) {return;} - - const size_t expected_vertices = V0.size() * 3; - - // If geometry changed, rebuild mesh & buffers - { - Ogre::SubMesh * sub = mesh_->getSubMesh(0); - Ogre::VertexData * vdata = sub->useSharedVertices ? mesh_->sharedVertexData : sub->vertexData; - if (vdata->vertexCount != expected_vertices) { - destroyMesh_(); - ensureMeshBuilt_(); - if (!mesh_built_ || !colour_vbuf_) {return;} + ctx.layer = nullptr; // neutral grey } } + return ctx; +} - // Lock and write one packed colour per vertex (buffer is colour-only → stride is 4) - unsigned char * base = static_cast( - colour_vbuf_->lock(Ogre::HardwareBuffer::HBL_DISCARD)); - uint32_t * p = reinterpret_cast(base); +void NavMapDisplay::colourChunk_(std::size_t k, const ColourCtx & ctx) +{ + if (!last_msg_ || k >= chunks_.size() || !chunks_[k].colour) {return;} + const auto & V0 = last_msg_->navcels_v0; + const auto & V1 = last_msg_->navcels_v1; + const auto & V2 = last_msg_->navcels_v2; + const std::size_t first = k * kChunkCels; + const std::size_t last = std::min(V0.size(), first + kChunkCels); + if (first >= last || chunks_[k].colour->getNumVertices() != 3 * (last - first)) {return;} - auto packARGB = [&](const Ogre::ColourValue & c) -> uint32_t { - // Pack in the render system's colour format, the one the buffer was created with + auto pack = [](const Ogre::ColourValue & c) -> uint32_t { + // the render system's colour format, the one the buffer was created with return Ogre::VertexElement::convertColourValue(c, nativeColourType_()); }; - - if (vertex_color_mode) { - const auto & R = last_msg_->colors_r; - const auto & G = last_msg_->colors_g; - const auto & B = last_msg_->colors_b; - const auto & A = last_msg_->colors_a; - - for (size_t t = 0; t < V0.size(); ++t) { - const uint32_t i0 = V0[t], i1 = V1[t], i2 = V2[t]; - - const Ogre::ColourValue c0( - R[i0] / 255.f, G[i0] / 255.f, B[i0] / 255.f, - (A.empty() ? alpha : (A[i0] / 255.f) * alpha)); - const Ogre::ColourValue c1( - R[i1] / 255.f, G[i1] / 255.f, B[i1] / 255.f, - (A.empty() ? alpha : (A[i1] / 255.f) * alpha)); - const Ogre::ColourValue c2( - R[i2] / 255.f, G[i2] / 255.f, B[i2] / 255.f, - (A.empty() ? alpha : (A[i2] / 255.f) * alpha)); - - *p++ = packARGB(c0); - *p++ = packARGB(c1); - *p++ = packARGB(c2); - } - } else if (selected_layer) { - if (is_u8) { - for (size_t t = 0; t < V0.size(); ++t) { - const Ogre::ColourValue col = colorFromU8(selected_layer->data_u8[t], alpha); - const uint32_t packed = packARGB(col); - *p++ = packed; *p++ = packed; *p++ = packed; - } - } else if (selected_layer->type == NavMapLayerMsg::F32) { - for (size_t t = 0; t < V0.size(); ++t) { - const Ogre::ColourValue col = use_rainbow ? - colorFromRainbow(selected_layer->data_f32[t], max_val, alpha) : - colorFromHeat (selected_layer->data_f32[t], max_val, alpha); - const uint32_t packed = packARGB(col); - *p++ = packed; *p++ = packed; *p++ = packed; + const float alpha = ctx.alpha; + const auto * L = ctx.layer; + auto colour_of = [&](std::size_t t) -> Ogre::ColourValue { + if (L->type == NavMapLayerMsg::U8) {return colorFromU8(L->data_u8[t], alpha);} + if (L->type == NavMapLayerMsg::I16) { + const int16_t v = L->data_i16[t]; + const float shifted = static_cast(v) - ctx.min_val; // the scales start at 0 + return ctx.logodds ? colorFromLogodds(v, alpha) : + (ctx.rainbow ? colorFromRainbow(shifted, ctx.max_val - ctx.min_val, alpha) : + colorFromHeat(shifted, ctx.max_val - ctx.min_val, alpha)); } - } else if (selected_layer->type == NavMapLayerMsg::I16) { - const bool logodds = isLogoddsLayer(*selected_layer); - for (size_t t = 0; t < V0.size(); ++t) { - const int16_t v = selected_layer->data_i16[t]; - const float shifted = static_cast(v) - min_val; // the scales start at 0 - const Ogre::ColourValue col = logodds ? colorFromLogodds(v, alpha) : - (use_rainbow ? colorFromRainbow(shifted, max_val - min_val, alpha) : - colorFromHeat(shifted, max_val - min_val, alpha)); - const uint32_t packed = packARGB(col); - *p++ = packed; *p++ = packed; *p++ = packed; - } - } else { // F64 - for (size_t t = 0; t < V0.size(); ++t) { - const float v = static_cast(selected_layer->data_f64[t]); - const Ogre::ColourValue col = use_rainbow ? - colorFromRainbow(v, max_val, alpha) : - colorFromHeat (v, max_val, alpha); - const uint32_t packed = packARGB(col); - *p++ = packed; *p++ = packed; *p++ = packed; - } - } - // Cells holding the layer's unknown value: translucent grey (U8 keeps its own mapping) - if (!is_u8 && selected_layer->has_unknown) { - const double u = selected_layer->unknown_value; - const uint32_t grey = packARGB(Ogre::ColourValue(0.5f, 0.5f, 0.5f, 0.35f * alpha)); - uint32_t * q = reinterpret_cast(base); - for (size_t t = 0; t < V0.size(); ++t, q += 3) { - double v = 0.0; - if (selected_layer->type == NavMapLayerMsg::I16) { - v = selected_layer->data_i16[t]; - } else if (selected_layer->type == NavMapLayerMsg::F32) { - v = selected_layer->data_f32[t]; - } else { - v = selected_layer->data_f64[t]; - } - if ((std::isnan(u) && std::isnan(v)) || v == u) {q[0] = q[1] = q[2] = grey;} + const float v = L->type == NavMapLayerMsg::F32 ? L->data_f32[t] : + static_cast(L->data_f64[t]); + return ctx.rainbow ? colorFromRainbow(v, ctx.max_val, alpha) : + colorFromHeat(v, ctx.max_val, alpha); + }; + // Cells holding the layer's unknown value: translucent grey (U8 keeps its own mapping) + auto unknown = [&](std::size_t t) -> bool { + if (ctx.is_u8 || !L->has_unknown) {return false;} + const double u = L->unknown_value; + const double v = L->type == NavMapLayerMsg::I16 ? L->data_i16[t] : + L->type == NavMapLayerMsg::F32 ? L->data_f32[t] : L->data_f64[t]; + return (std::isnan(u) && std::isnan(v)) || v == u; + }; + const uint32_t grey = pack(Ogre::ColourValue(0.5f, 0.5f, 0.5f, 0.35f * alpha)); + const uint32_t neutral = pack(Ogre::ColourValue(0.7f, 0.7f, 0.7f, alpha)); + + auto * p = static_cast(chunks_[k].colour->lock(Ogre::HardwareBuffer::HBL_DISCARD)); + const std::size_t nv = last_msg_->positions_x.size(); + for (std::size_t t = first; t < last; ++t) { + if (ctx.vertex_colours) { + const auto & R = last_msg_->colors_r; + const auto & G = last_msg_->colors_g; + const auto & B = last_msg_->colors_b; + const auto & A = last_msg_->colors_a; + for (const uint32_t i : {V0[t], V1[t], V2[t]}) { + if (i >= nv) {*p++ = neutral; continue;} + *p++ = pack( + Ogre::ColourValue( + R[i] / 255.f, G[i] / 255.f, B[i] / 255.f, + A.size() == nv ? (A[i] / 255.f) * alpha : alpha)); } + continue; } - } else { - // Fallback to neutral grey - const uint32_t packed = packARGB(Ogre::ColourValue(0.7f, 0.7f, 0.7f, alpha)); - for (size_t t = 0; t < V0.size(); ++t) { - *p++ = packed; *p++ = packed; *p++ = packed; - } + const uint32_t c = !L ? neutral : (unknown(t) ? grey : pack(colour_of(t))); + *p++ = c; *p++ = c; *p++ = c; } + chunks_[k].colour->unlock(); +} - colour_vbuf_->unlock(); - - // No extra invalidation is necessary; OGRE will render new colours next frame. +void NavMapDisplay::updateColorsOnly_() +{ + ensureMeshBuilt_(); + const auto ctx = colourContext_(); + for (std::size_t k = 0; k < chunks_.size(); ++k) { + colourChunk_(k, ctx); + } } +// The edges of the chunk's NavCels, each once within the chunk, lifted 2 cm so they do not +// flicker against the surface. Degenerate NavCels (placeholders) are left out. +void NavMapDisplay::edgesChunk_(std::size_t k) +{ + if (!context_ || k >= chunks_.size()) {return;} + Chunk & ch = chunks_[k]; + if (!last_msg_ || !draw_edges_property_->getBool()) { + if (ch.edges) {ch.edges->clear();} + return; + } + if (!ch.edges) { + ch.edges = context_->getSceneManager()->createManualObject(); + ch.edges->setDynamic(true); + root_node_->attachObject(ch.edges); + } + ch.edges->clear(); + + const auto & X = last_msg_->positions_x; + const auto & Y = last_msg_->positions_y; + const auto & Z = last_msg_->positions_z; + const auto & V0 = last_msg_->navcels_v0; + const auto & V1 = last_msg_->navcels_v1; + const auto & V2 = last_msg_->navcels_v2; + const std::size_t first = k * kChunkCels; + const std::size_t last = std::min(V0.size(), first + kChunkCels); + const std::size_t nv = X.size(); + std::vector edges; + edges.reserve(3 * (last > first ? last - first : 0)); + for (std::size_t t = first; t < last; ++t) { + const uint32_t v[3] = {V0[t], V1[t], V2[t]}; + if (v[0] == v[1] || v[1] == v[2] || v[0] == v[2]) {continue;} + if (v[0] >= nv || v[1] >= nv || v[2] >= nv) {continue;} + for (int e = 0; e < 3; ++e) { + const uint32_t a = std::min(v[e], v[(e + 1) % 3]), b = std::max(v[e], v[(e + 1) % 3]); + edges.push_back((static_cast(a) << 32) | b); + } + } + std::sort(edges.begin(), edges.end()); + edges.erase(std::unique(edges.begin(), edges.end()), edges.end()); + if (edges.empty()) {return;} + + const QColor q = edge_color_property_->getColor(); + const Ogre::ColourValue colour(q.redF(), q.greenF(), q.blueF(), 1.0f); + const Ogre::Vector3 lift(0.0f, 0.0f, 0.02f); + ch.edges->begin("BaseWhiteNoLighting", Ogre::RenderOperation::OT_LINE_LIST); + for (const auto key : edges) { + const auto a = static_cast(key >> 32), b = static_cast(key & 0xffffffffu); + ch.edges->position(Ogre::Vector3(X[a], Y[a], Z[a]) + lift); + ch.edges->colour(colour); + ch.edges->position(Ogre::Vector3(X[b], Y[b], Z[b]) + lift); + ch.edges->colour(colour); + } + ch.edges->end(); +} void NavMapDisplay::updateGeometry_() { @@ -898,6 +1027,19 @@ void NavMapDisplay::updateNormals_() normals_obj_->end(); } +void NavMapDisplay::onDrawEdgesChanged() +{ + updateEdges_(); + context_->queueRender(); +} + +void NavMapDisplay::updateEdges_() +{ + for (std::size_t k = 0; k < chunks_.size(); ++k) { + edgesChunk_(k); + } +} + void NavMapDisplay::onDrawLinksChanged() { updateLinks_(); diff --git a/navmap_rviz_plugin/src/navmap_rviz_plugin/navmap_pose_tool.cpp b/navmap_rviz_plugin/src/navmap_rviz_plugin/navmap_pose_tool.cpp index e9540b4..e957d96 100644 --- a/navmap_rviz_plugin/src/navmap_rviz_plugin/navmap_pose_tool.cpp +++ b/navmap_rviz_plugin/src/navmap_rviz_plugin/navmap_pose_tool.cpp @@ -100,7 +100,7 @@ rayHitOnNavMap( ::navmap::NavCelId cid = 0; float t = 0.0f; Eigen::Vector3f hit; - const bool ok = received_navmap.raycast(o, d, cid, t, hit); + const bool ok = current_received_navmap().raycast(o, d, cid, t, hit); if (!ok) { return {false, Ogre::Vector3::ZERO}; } @@ -112,7 +112,7 @@ int NavMapPoseTool::processMouseEvent(rviz_common::ViewportMouseEvent & event) { std::pair hit = {false, Ogre::Vector3::ZERO}; - if (!received_navmap.surfaces.empty()) { + if (!current_received_navmap().surfaces.empty()) { hit = rayHitOnNavMap(event, context_); }