### Run Simple Grid Map Demo Source: https://github.com/anybotics/grid_map/blob/master/README.md Launches a ROS node that demonstrates basic grid map creation, data addition, and publishing. Use this to verify installation and get started. ```bash roslaunch grid_map_demos simple_demo.launch ``` -------------------------------- ### Project and Catkin Setup Source: https://github.com/anybotics/grid_map/blob/master/grid_map_msgs/CMakeLists.txt Sets the minimum CMake version and project name, then finds necessary Catkin components. ```cmake cmake_minimum_required(VERSION 3.5.1) project(grid_map_msgs) ``` ```cmake find_package(catkin REQUIRED COMPONENTS std_msgs geometry_msgs message_generation ) ``` -------------------------------- ### Target and File Installation Rules Source: https://github.com/anybotics/grid_map/blob/master/grid_map_demos/CMakeLists.txt Specifies which targets (executables and libraries) and other files (config, data, etc.) should be installed and their destination directories within the package structure. ```cmake # Mark executables and/or libraries for installation install( TARGETS filters_demo image_to_gridmap_demo grid_map_to_image_demo interpolation_demo iterator_benchmark iterators_demo move_demo normal_filter_comparison_demo octomap_to_gridmap_demo opencv_demo resolution_change_demo simple_demo tutorial_demo sdf_demo ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION} ) # Mark other files for installation install( DIRECTORY config data doc launch rviz scripts DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION} ) ``` -------------------------------- ### Installation Rules Source: https://github.com/anybotics/grid_map/blob/master/grid_map_octomap/CMakeLists.txt Specifies rules for installing the built library and header files to their designated locations within the ROS package structure. ```cmake ## Specify additional locations of header files ## Declare a cpp library add_library(${PROJECT_NAME} src/GridMapOctomapConverter.cpp ) target_link_libraries(${PROJECT_NAME} ${catkin_LIBRARIES} ${OCTOMAP_LIBRARIES} ) add_dependencies(${PROJECT_NAME} ${catkin_EXPORTED_TARGETS} ) ############# ## Install ## ############# # Mark executables and/or libraries for installation install( TARGETS ${PROJECT_NAME} ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION} ) # Mark cpp header files for installation install( DIRECTORY include/${PROJECT_NAME}/ DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION} FILES_MATCHING PATTERN "*.hpp" ) ``` -------------------------------- ### Install Header Files Source: https://github.com/anybotics/grid_map/blob/master/grid_map_costmap_2d/CMakeLists.txt Marks C++ header files for installation into the package's include directory. Only files matching the .hpp pattern are installed. ```cmake install( DIRECTORY include/${PROJECT_NAME}/ DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION} FILES_MATCHING PATTERN "*.hpp" ) ``` -------------------------------- ### Install Targets and Headers Source: https://github.com/anybotics/grid_map/blob/master/grid_map_filters/CMakeLists.txt Specifies which targets (libraries, executables) and header files should be installed. This ensures the package can be used by other ROS packages. ```cmake install( TARGETS ${PROJECT_NAME} ${PROJECT_NAME}_plugins ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION} ) # Mark cpp header files for installation install( DIRECTORY include/${PROJECT_NAME}/ DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION} FILES_MATCHING PATTERN "*.hpp" ) # Mark other files for installation install( FILES filter_plugins.xml DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION} ) ``` -------------------------------- ### Project and Dependency Setup Source: https://github.com/anybotics/grid_map/blob/master/grid_map_octomap/CMakeLists.txt Initializes the CMake project and finds required catkin and octomap packages. It sets C++ standard and compiler flags for enhanced code quality and debugging. ```cmake cmake_minimum_required(VERSION 3.5.1) project(grid_map_octomap) set(CMAKE_CXX_FLAGS "-std=c++11 ${CMAKE_CXX_FLAGS}") add_compile_options(-Wall -Wextra -Wpedantic) set(CMAKE_EXPORT_COMPILE_COMMANDS ON) ## Find catkin macros and libraries find_package(catkin REQUIRED COMPONENTS grid_map_core ) find_package(octomap REQUIRED) message(STATUS "Found Octomap (version ${octomap_VERSION}): ${OCTOMAP_INCLUDE_DIRS}") ``` -------------------------------- ### Install grid_map Package Source: https://github.com/anybotics/grid_map/blob/master/README.md Installs all grid map library packages from Debian packages. Ensure your ROS_DISTRO is set correctly. ```bash sudo apt-get install ros-$ROS_DISTRO-grid-map ``` -------------------------------- ### Python Script Installation Source: https://github.com/anybotics/grid_map/blob/master/grid_map_demos/CMakeLists.txt Installs a Python script to the package's binary destination. This makes the script executable after installation. ```cmake catkin_install_python( PROGRAMS scripts/image_publisher.py DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION} ) ``` -------------------------------- ### Include Directories Setup Source: https://github.com/anybotics/grid_map/blob/master/grid_map_octomap/CMakeLists.txt Configures include directories based on the Octomap version. It adds system include directories for compatibility with different ROS distributions. ```cmake if(${octomap_VERSION} VERSION_LESS 1.8) # ROS Indigo and Jade. add_definitions(-DOCTOMAP_VERSION_BEFORE_ROS_KINETIC) include_directories( include SYSTEM ${catkin_INCLUDE_DIRS} ${OCTOMAP_INCLUDE_DIR} ) else() # ROS Kinetic and above. include_directories( include SYSTEM ${catkin_INCLUDE_DIRS} ${OCTOMAP_INCLUDE_DIRS} ) endif() ``` -------------------------------- ### Finding Catkin and System Dependencies Source: https://github.com/anybotics/grid_map/blob/master/grid_map_demos/CMakeLists.txt Finds required catkin packages and system libraries like OpenCV and octomap. Ensure these dependencies are installed before building. ```cmake find_package(catkin REQUIRED COMPONENTS roscpp grid_map_core grid_map_cv grid_map_filters grid_map_loader grid_map_msgs grid_map_octomap grid_map_ros grid_map_rviz_plugin grid_map_sdf grid_map_visualization geometry_msgs sensor_msgs cv_bridge octomap_msgs filters ) find_package(OpenCV REQUIRED COMPONENTS opencv_highgui CONFIG ) find_package(octomap REQUIRED) ``` -------------------------------- ### CMakeLists.txt for grid_map Metapackage Source: https://github.com/anybotics/grid_map/blob/master/grid_map/CMakeLists.txt This CMakeLists.txt file defines the grid_map ROS metapackage. It specifies the minimum CMake version, project name, and finds the required catkin package. Use this for ROS package setup. ```cmake cmake_minimum_required(VERSION 3.5.1) project(grid_map) find_package(catkin REQUIRED) catkin_metapackage() ``` -------------------------------- ### Find Catkin Packages Source: https://github.com/anybotics/grid_map/blob/master/grid_map_costmap_2d/CMakeLists.txt Finds necessary catkin packages and their components. Ensure these packages are installed in your ROS environment. ```cmake find_package(catkin REQUIRED COMPONENTS grid_map_core costmap_2d tf ) ``` -------------------------------- ### Find and Add Clang Tooling Source: https://github.com/anybotics/grid_map/blob/master/grid_map_pcl/CMakeLists.txt Finds the cmake_clang_tools package and adds default clang tooling if found. Ensure cmake_clang_tools is installed. ```cmake find_package(cmake_clang_tools QUIET) if(cmake_clang_tools_FOUND) add_default_clang_tooling() endif(cmake_clang_tools_FOUND) ``` -------------------------------- ### Testing Setup with GTest Source: https://github.com/anybotics/grid_map/blob/master/grid_map_octomap/CMakeLists.txt Configures C++ unit tests using Google Test (GTest), linking necessary libraries and setting up include paths. It also enables code coverage if the tool is found. ```cmake ############# ## Testing ## ############# if(CATKIN_ENABLE_TESTING) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pthread") # Add gtest based cpp test target and link libraries catkin_add_gtest(${PROJECT_NAME}-test test/test_grid_map_octomap.cpp test/OctomapConverterTest.cpp ) target_include_directories(${PROJECT_NAME}-test PRIVATE include ) target_include_directories(${PROJECT_NAME}-test SYSTEM PUBLIC ${catkin_INCLUDE_DIRS} ${OCTOMAP_INCLUDE_DIRS} ) target_link_libraries(${PROJECT_NAME}-test ${PROJECT_NAME} ${OCTOMAP_LIBRARIES} ) ################### ## Code_coverage ## ################### find_package(cmake_code_coverage QUIET) if(cmake_code_coverage_FOUND) add_gtest_coverage( TEST_BUILD_TARGETS ${PROJECT_NAME}-test ) endif() endif() ``` -------------------------------- ### Configure C++ Test Target with gtest Source: https://github.com/anybotics/grid_map/blob/master/grid_map_costmap_2d/CMakeLists.txt Adds a gtest-based C++ test target, linking necessary libraries and including directories. This setup is conditional on CATKIN_ENABLE_TESTING being true. ```cmake if(CATKIN_ENABLE_TESTING) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pthread") ## Add gtest based cpp test target and link libraries catkin_add_gtest(${PROJECT_NAME}-test test/test_grid_map_costmap_2d.cpp test/Costmap2DConverterTest.cpp ) # TODO(mw): Disabled rostest because pipeline was failing. Locally not reproducible. # add_subdirectory(rostest) target_include_directories(${PROJECT_NAME}-test PRIVATE include ) target_include_directories(${PROJECT_NAME}-test SYSTEM PUBLIC ${catkin_INCLUDE_DIRS} ${EIGEN3_INCLUDE_DIR} ) target_link_libraries(${PROJECT_NAME}-test ${catkin_LIBRARIES} ) ################### ## Code_coverage ## ################### find_package(cmake_code_coverage QUIET) if(cmake_code_coverage_FOUND) add_gtest_coverage( TEST_BUILD_TARGETS ${PROJECT_NAME}-test ) endif() endif() ``` -------------------------------- ### Define Catkin Package Dependencies Source: https://github.com/anybotics/grid_map/blob/master/grid_map_filters/CMakeLists.txt Lists the catkin packages required by this package, both for header files and for general compilation. Ensure these packages are installed and available in your ROS environment. ```cmake set(CATKIN_PACKAGE_HEADER_DEPENDENCIES grid_map_core grid_map_ros grid_map_msgs filters ) ## Create a list of catkin package dependencies, now for both header and source files. set(CATKIN_PACKAGE_DEPENDENCIES ${CATKIN_PACKAGE_HEADER_DEPENDENCIES} ) ``` -------------------------------- ### Visualize Grid Map Vectors Source: https://github.com/anybotics/grid_map/blob/master/README.md Visualizes vector data from a grid map layer using visualization markers. Specify layers for vector components and the starting position. Optional parameters include scale, line width, and color. ```yaml name: surface_normals type: vectors params: layer_prefix: normal_ position_layer: elevation scale: 0.06 line_width: 0.005 color: 15600153 # red ``` -------------------------------- ### Iterate Over Rectangular Subregion with SubmapIterator Source: https://context7.com/anybotics/grid_map/llms.txt Use SubmapIterator to traverse a rectangular subregion. The subregion can be defined by start index and buffer size, or by position and length. ```cpp #include GridMap map({"elevation"}); map.setGeometry(Length(2.0, 2.0), 0.05); // Define submap region by start index and buffer size Index submapStartIndex(3, 5); Index submapBufferSize(12, 7); for (SubmapIterator it(map, submapStartIndex, submapBufferSize); !it.isPastEnd(); ++it) { map.at("elevation", *it) = 0.5; } // Alternative: Define submap by position and length Position topLeftCorner(0.5, 0.2); boundPositionToRange(topLeftCorner, map.getLength(), map.getPosition()); Index startIndex; map.getIndex(topLeftCorner, startIndex); Size size = (Length(0.6, 0.4) / map.getResolution()).cast(); for (SubmapIterator it(map, startIndex, size); !it.isPastEnd(); ++it) { Position pos; map.getPosition(*it, pos); // Process cell at position } ``` -------------------------------- ### Evaluate Mathematical Expression on Grid Map Layers Source: https://github.com/anybotics/grid_map/blob/master/README.md Parses and evaluates a mathematical expression using layers from a grid map. The expression can involve layer values and mathematical functions. Examples include calculating slope, surface roughness, and weighted sums. ```yaml name: math_expression type: gridMapFilters/MathExpressionFilter params: output_layer: output expression: acos(normal_vectors_z) # Slope. # expression: abs(elevation - elevation_smooth) # Surface roughness. # expression: 0.5 * (1.0 - (slope / 0.6)) + 0.5 * (1.0 - (roughness / 0.1)) # Weighted and normalized sum. ``` -------------------------------- ### Run Tutorial Grid Map Demo Source: https://github.com/anybotics/grid_map/blob/master/README.md Launches an extended ROS demonstration node that showcases a wider range of the grid map library's functionalities. ```bash roslaunch grid_map_demos tutorial_demo.launch ``` -------------------------------- ### Run Image to Grid Map Demo Source: https://github.com/anybotics/grid_map/blob/master/README.md Launches a ROS demonstration node that illustrates the process of converting image data into a grid map format. ```bash roslaunch grid_map_demos image_to_gridmap_demo.launch ``` -------------------------------- ### Create and Populate GridMap Source: https://context7.com/anybotics/grid_map/llms.txt Demonstrates creating a GridMap with multiple layers, setting its geometry, and populating cells with data. Shows how to access data by position and interpolate values. Includes adding new layers and performing direct Eigen matrix operations. ```cpp #include using namespace grid_map; // Create a grid map with named layers GridMap map({"elevation", "variance", "color"}); // Configure map geometry: 1.2m x 2.0m, 3cm resolution, centered at origin map.setGeometry(Length(1.2, 2.0), 0.03, Position(0.0, 0.0)); map.setFrameId("map"); // Add data to cells by iterating through the map for (GridMapIterator it(map); !it.isPastEnd(); ++it) { Position position; map.getPosition(*it, position); // Set elevation based on position map.at("elevation", *it) = 0.5 * sin(position.x()) * cos(position.y()); map.at("variance", *it) = 0.01; } // Access data at specific position Position queryPos(0.5, 0.3); if (map.isInside(queryPos)) { float elevation = map.atPosition("elevation", queryPos); // With interpolation methods: INTER_NEAREST, INTER_LINEAR, INTER_CUBIC_CONVOLUTION, INTER_CUBIC float interpolatedElevation = map.atPosition("elevation", queryPos, InterpolationMethods::INTER_LINEAR); } // Add new layer with Eigen operations map.add("noise", 0.01 * Matrix::Random(map.getSize()(0), map.getSize()(1))); map.add("elevation_noisy", map.get("elevation") + map["noise"]); // Access layer data directly as Eigen matrix for efficient operations Matrix& elevationData = map["elevation"]; elevationData = elevationData.cwiseMax(0.0); // Clamp to non-negative values // Get submap from a region bool success; GridMap submap = map.getSubmap(Position(0.3, 0.2), Length(0.5, 0.5), success); // Move map to follow robot (circular buffer handles data efficiently) std::vector newRegions; map.move(Position(1.0, 0.5), newRegions); // New regions are set to NaN ``` -------------------------------- ### Build grid_map from Source Source: https://github.com/anybotics/grid_map/blob/master/README.md Compiles the grid_map package from source after cloning. Navigate to the catkin workspace root before running. ```bash cd ../ catkin_make ``` -------------------------------- ### Run Grid Map Interpolation Demo Source: https://github.com/anybotics/grid_map/blob/master/README.md Launches a ROS demonstration node to visualize the results of different interpolation methods (NN, Linear, Cubic convolution, Cubic) on a grid map surface. Allows experimentation with various worlds and interpolation settings. ```bash roslaunch grid_map_demos interpolation_demo.launch ``` -------------------------------- ### Run Grid Map Iterators Demo Source: https://github.com/anybotics/grid_map/blob/master/README.md Launches a ROS demonstration node specifically designed to showcase the usage and capabilities of grid map iterators. ```bash roslaunch grid_map_demos iterators_demo.launch ``` -------------------------------- ### Run OpenCV Grid Map Demo Source: https://github.com/anybotics/grid_map/blob/master/README.md Launches a ROS demonstration node that utilizes OpenCV functions for various grid map manipulations. This demo highlights image processing techniques applied to grid maps. ```bash roslaunch grid_map_demos opencv_demo.launch ``` -------------------------------- ### Run Grid Map Resolution Change Demo Source: https://github.com/anybotics/grid_map/blob/master/README.md Launches a ROS demonstration node that showcases how to alter the resolution of a grid map using OpenCV's image scaling methods. Observe the results of resolution adjustments. ```bash roslaunch grid_map_demos resolution_change_demo.launch ``` -------------------------------- ### Run Grid Map Filters Demo Source: https://github.com/anybotics/grid_map/blob/master/README.md Launches a ROS demonstration node that applies a chain of ROS Filters to process a grid map. This includes computing surface normals, inpainting, smoothing, and edge detection using math expressions. ```bash roslaunch grid_map_demos filters_demo.launch ``` -------------------------------- ### Run grid_map Unit Tests (catkin_make) Source: https://github.com/anybotics/grid_map/blob/master/README.md Executes unit tests for the grid_map_core and grid_map_ros packages using catkin_make. Ensure tests are enabled in the build. ```bash catkin_make run_tests_grid_map_core run_tests_grid_map_ros ``` -------------------------------- ### Iterate Within a Circular Region Source: https://context7.com/anybotics/grid_map/llms.txt Demonstrates using CircleIterator to access cells within a specified circular area. Includes examples for setting values within the circle and computing a weighted mean based on distance from the center. ```cpp #include GridMap map({"elevation"}); map.setGeometry(Length(2.0, 2.0), 0.05); Position center(0.3, -0.2); double radius = 0.4; // Set all cells within circle to specific value for (CircleIterator it(map, center, radius); !it.isPastEnd(); ++it) { map.at("elevation", *it) = 1.0; } // Compute weighted mean within radius double mean = 0.0; double sumOfWeights = 0.0; for (CircleIterator circleIt(map, center, radius); !circleIt.isPastEnd(); ++circleIt) { if (!map.isValid(*circleIt, "elevation")) continue; Position cellPosition; map.getPosition(*circleIt, cellPosition); double distance = (center - cellPosition).norm(); double weight = pow(radius - distance, 2); mean += weight * map.at("elevation", *circleIt); sumOfWeights += weight; } double weightedMean = mean / sumOfWeights; ``` -------------------------------- ### Enable Testing with Catkin Source: https://github.com/anybotics/grid_map/blob/master/grid_map_filters/CMakeLists.txt Configures Google Test for the project if testing is enabled. Includes necessary include directories and links required libraries. ```cmake if (CATKIN_ENABLE_TESTING) catkin_add_gtest(${PROJECT_NAME}-test test/test_grid_map_filters.cpp test/median_fill_filter_test.cpp test/mock_filter_test.cpp test/threshold_filter_test.cpp ) target_include_directories(${PROJECT_NAME}-test PRIVATE include ) target_include_directories(${PROJECT_NAME}-test SYSTEM PUBLIC ${catkin_INCLUDE_DIRS} ) target_link_libraries(${PROJECT_NAME}-test gmock gtest ${PROJECT_NAME} ) ################### ## Code_coverage ## ################### find_package(cmake_code_coverage QUIET) if(cmake_code_coverage_FOUND) add_gtest_coverage( TEST_BUILD_TARGETS ${PROJECT_NAME}-test ) endif() endif() ``` -------------------------------- ### Run grid_map Unit Tests (catkin build) Source: https://github.com/anybotics/grid_map/blob/master/README.md Executes unit tests for the grid_map package using catkin tools. This command builds the package and runs its tests. ```bash catkin build grid_map --no-deps --verbose --catkin-make-args run_tests ``` -------------------------------- ### Include Directories Configuration Source: https://github.com/anybotics/grid_map/blob/master/grid_map_demos/CMakeLists.txt Configures include paths for the project, including local headers, catkin-provided headers, Eigen3, and Octomap. ```cmake include_directories( include ${catkin_INCLUDE_DIRS} ${EIGEN3_INCLUDE_DIR} ${OCTOMAP_INCLUDE_DIR} ) ``` -------------------------------- ### Define Main Library Source: https://github.com/anybotics/grid_map/blob/master/grid_map_filters/CMakeLists.txt Creates the main C++ library for the package, listing all source files. Ensure all source files are correctly listed here. ```cmake add_library(${PROJECT_NAME} src/ThresholdFilter.cpp src/MinInRadiusFilter.cpp src/MeanInRadiusFilter.cpp src/MedianFillFilter.cpp src/MockFilter.cpp src/NormalVectorsFilter.cpp src/CurvatureFilter.cpp src/NormalColorMapFilter.cpp src/LightIntensityFilter.cpp src/MathExpressionFilter.cpp src/SlidingWindowMathExpressionFilter.cpp src/DuplicationFilter.cpp src/DeletionFilter.cpp src/ColorFillFilter.cpp src/ColorMapFilter.cpp src/ColorBlendingFilter.cpp src/SetBasicLayersFilter.cpp src/BufferNormalizerFilter.cpp ) ``` -------------------------------- ### Build grid_map in Release Mode Source: https://github.com/anybotics/grid_map/blob/master/README.md Builds the grid_map package in Release mode for maximum performance. This is recommended for production use. ```bash catkin_make -DCMAKE_BUILD_TYPE=Release ``` -------------------------------- ### Set Include Directories Source: https://github.com/anybotics/grid_map/blob/master/grid_map_filters/CMakeLists.txt Specifies directories where header files can be found. SYSTEM is used for OpenCV and catkin includes to prevent warnings from those headers. ```cmake include_directories( include SYSTEM ${catkin_INCLUDE_DIRS} ${OpenCV_INCLUDE_DIRS} ) ``` -------------------------------- ### Include Directories for Build Source: https://github.com/anybotics/grid_map/blob/master/grid_map_costmap_2d/CMakeLists.txt Specifies directories for header files during the build process. Includes local headers, system headers from catkin, and Eigen3 headers if available. ```cmake include_directories( include SYSTEM ${catkin_INCLUDE_DIRS} ${EIGEN3_INCLUDE_DIR} ) ``` -------------------------------- ### Link Libraries and Dependencies Source: https://github.com/anybotics/grid_map/blob/master/grid_map_filters/CMakeLists.txt Links the main library against catkin, TBB, and OpenCV libraries. It also adds dependencies to ensure correct build order. ```cmake target_include_directories(${PROJECT_NAME} PRIVATE ${TBB_INCLUDE_DIRS} ) target_include_directories(${PROJECT_NAME} SYSTEM PUBLIC ${catkin_INCLUDE_DIRS} ) target_link_libraries(${PROJECT_NAME} ${catkin_LIBRARIES} ${TBB_LIBRARIES} ${OpenCV_LIBRARIES} ) add_dependencies(${PROJECT_NAME} ${catkin_EXPORTED_TARGETS} ) ``` -------------------------------- ### Configure Clang Tools Source: https://github.com/anybotics/grid_map/blob/master/grid_map_costmap_2d/CMakeLists.txt Finds and configures clang-format for code formatting. This is an optional step and is skipped if clang-format is not found. ```cmake ################# ## Clang_tools ## ################# find_package(cmake_clang_tools QUIET) if(cmake_clang_tools_FOUND) add_default_clang_tooling( DISABLE_CLANG_FORMAT ) endif(cmake_clang_tools_FOUND) ``` -------------------------------- ### Clone grid_map Repository Source: https://github.com/anybotics/grid_map/blob/master/README.md Clones the grid_map repository into your catkin workspace src directory. This is the first step for building from source. ```bash cd catkin_ws/src git clone https://github.com/anybotics/grid_map.git ``` -------------------------------- ### Project and C++ Standard Configuration Source: https://github.com/anybotics/grid_map/blob/master/grid_map_demos/CMakeLists.txt Sets the minimum CMake version, project name, C++ standard to C++17, enables all compiler warnings, and ensures compile commands are exported. ```cmake cmake_minimum_required(VERSION 3.5.1) project(grid_map_demos) set(CMAKE_CXX_STANDARD 17) add_compile_options(-Wall -Wextra -Wpedantic) set(CMAKE_EXPORT_COMPILE_COMMANDS ON) ``` -------------------------------- ### Save Grid Map Layer to Image Source: https://github.com/anybotics/grid_map/blob/master/README.md Runs a ROS node that demonstrates how to save a specific layer of a grid map to an image file. Specify the grid map topic and output file path. ```bash rosrun grid_map_demos grid_map_to_image_demo _grid_map_topic:=/grid_map _file:=/home/$USER/Desktop/grid_map_image.png ``` -------------------------------- ### Define Plugin Library Source: https://github.com/anybotics/grid_map/blob/master/grid_map_filters/CMakeLists.txt Creates a separate library for plugin exports, typically containing registration code. This helps in modularizing the plugin system. ```cmake # Instantiate plugin exports for every filter in this package. add_library(${PROJECT_NAME}_plugins src/plugins.cpp ) target_include_directories(${PROJECT_NAME}_plugins SYSTEM PUBLIC ${catkin_INCLUDE_DIRS} ) target_link_libraries(${PROJECT_NAME}_plugins ${PROJECT_NAME} ${TBB_LIBRARIES} # is this necessary? ${OpenCV_LIBRARIES} # is this necessary? ) add_dependencies(${PROJECT_NAME}_plugins ${catkin_EXPORTED_TARGETS} ${PROJECT_NAME} ) ``` -------------------------------- ### Iterate Over All GridMap Cells Source: https://context7.com/anybotics/grid_map/llms.txt Shows how to iterate through every cell of a GridMap using GridMapIterator. Includes basic iteration and an optimized approach for direct data access using Eigen matrices. ```cpp #include GridMap map({"elevation"}); map.setGeometry(Length(1.0, 1.0), 0.05); // Basic iteration through all cells for (GridMapIterator it(map); !it.isPastEnd(); ++it) { Index index = *it; Position position; map.getPosition(index, position); map.at("elevation", index) = computeElevation(position); } // Optimized iteration with direct data access Matrix& data = map["elevation"]; for (GridMapIterator it(map); !it.isPastEnd(); ++it) { const int linearIndex = it.getLinearIndex(); data(linearIndex) = 1.0; } ``` -------------------------------- ### Run ROS Text Test Source: https://github.com/anybotics/grid_map/blob/master/grid_map_costmap_2d/rostest/README.md Use this command to run a ROS test in text mode. Ensure you are in the correct directory or provide the full path to the test file. ```bash rostest --text mytest.test ``` -------------------------------- ### Find Rostest Package Source: https://github.com/anybotics/grid_map/blob/master/grid_map_costmap_2d/rostest/CMakeLists.txt Finds the required rostest package for setting up tests. ```cmake find_package(rostest REQUIRED) ``` -------------------------------- ### Find External Dependencies Source: https://github.com/anybotics/grid_map/blob/master/grid_map_filters/CMakeLists.txt Locates necessary external libraries and packages such as TBB and OpenCV. The EXACT keyword ensures a specific version is found, which is crucial for avoiding compatibility issues. ```cmake find_package(TBB 2020.1 EXACT REQUIRED) find_package(OpenCV REQUIRED) ``` -------------------------------- ### Set C++ Standard and Compiler Flags Source: https://github.com/anybotics/grid_map/blob/master/grid_map_filters/CMakeLists.txt Configures the C++ standard to C++17 and sets compiler flags for performance and NaN handling. Use this to ensure compatibility and optimize for specific hardware features. ```cmake cmake_minimum_required(VERSION 3.5.1) project(grid_map_filters) # Better with serial algorithms. set(CMAKE_CXX_STANDARD 17) # We want performance (fast-math) but also need a representation for NaN values to represent missing values. # Therefore, we disable the finite-math-only flag that was set by fast-math. set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -ffast-math -fno-finite-math-only") add_compile_options(-Wall -Wextra -Wpedantic) set(CMAKE_EXPORT_COMPILE_COMMANDS ON) ``` -------------------------------- ### Add gtest for Project Testing Source: https://github.com/anybotics/grid_map/blob/master/grid_map_demos/CMakeLists.txt Configures Google Test for the project if testing is enabled. Includes dependencies and target libraries. ```cmake if(CATKIN_ENABLE_TESTING) catkin_add_gtest(${PROJECT_NAME}-test test/empty_test.cpp ) add_dependencies(${PROJECT_NAME}-test filters_demo image_to_gridmap_demo grid_map_to_image_demo interpolation_demo iterator_benchmark iterators_demo move_demo normal_filter_comparison_demo octomap_to_gridmap_demo opencv_demo resolution_change_demo simple_demo tutorial_demo ) target_include_directories(${PROJECT_NAME}-test PRIVATE include ) target_include_directories(${PROJECT_NAME}-test SYSTEM PUBLIC ${catkin_INCLUDE_DIRS} ) target_link_libraries(${PROJECT_NAME}-test gtest_main ${catkin_LIBRARIES} ) endif() ``` -------------------------------- ### Visualize Grid Map as Point Cloud Source: https://github.com/anybotics/grid_map/blob/master/README.md Configures the visualization of a grid map layer as a point cloud. Specify the layer to be transformed into points. 'flat: false' is optional. ```yaml name: elevation type: point_cloud params: layer: elevation flat: false # optional ``` -------------------------------- ### ROS Node: Publish Grid Map Source: https://context7.com/anybotics/grid_map/llms.txt This C++ ROS node creates, populates, and publishes a grid map. It requires the grid_map_ros and grid_map_msgs packages. The map layers include 'elevation', 'normal_x', 'normal_y', and 'normal_z'. ```cpp #include #include #include #include using namespace grid_map; int main(int argc, char** argv) { ros::init(argc, argv, "grid_map_publisher"); ros::NodeHandle nh("~"); ros::Publisher publisher = nh.advertise("grid_map", 1, true); // Create and configure grid map GridMap map({"elevation", "normal_x", "normal_y", "normal_z"}); map.setFrameId("map"); map.setGeometry(Length(1.2, 2.0), 0.03, Position(0.0, -0.1)); ROS_INFO("Created map: %f x %f m (%i x %i cells)", map.getLength().x(), map.getLength().y(), map.getSize()(0), map.getSize()(1)); ros::Rate rate(30.0); while (nh.ok()) { ros::Time time = ros::Time::now(); // Update elevation with time-varying sine wave for (GridMapIterator it(map); !it.isPastEnd(); ++it) { Position position; map.getPosition(*it, position); map.at("elevation", *it) = -0.04 + 0.2 * sin(3.0 * time.toSec() + 5.0 * position.y()) * position.x(); // Compute surface normal Eigen::Vector3d normal( -0.2 * sin(3.0 * time.toSec() + 5.0 * position.y()), -position.x() * cos(3.0 * time.toSec() + 5.0 * position.y()), 1.0); normal.normalize(); map.at("normal_x", *it) = normal.x(); map.at("normal_y", *it) = normal.y(); map.at("normal_z", *it) = normal.z(); } // Add noise layer using Eigen operations map.add("noise", 0.015 * Matrix::Random(map.getSize()(0), map.getSize()(1))); map.add("elevation_noisy", map.get("elevation") + map["noise"]); // Publish map.setTimestamp(time.toNSec()); grid_map_msgs::GridMap message; GridMapRosConverter::toMessage(map, message); publisher.publish(message); rate.sleep(); } return 0; } ``` -------------------------------- ### Declare ROS Messages and Services Source: https://github.com/anybotics/grid_map/blob/master/grid_map_msgs/CMakeLists.txt Declares message and service files to be generated by Catkin. ```cmake add_message_files( FILES GridMapInfo.msg GridMap.msg ) ``` ```cmake add_service_files( FILES SetGridMap.srv GetGridMap.srv GetGridMapInfo.srv ProcessFile.srv ) ``` ```cmake generate_messages( DEPENDENCIES std_msgs geometry_msgs ) ``` -------------------------------- ### Query Signed Distance and Gradient Source: https://context7.com/anybotics/grid_map/llms.txt Demonstrates querying the signed distance and its gradient at a specific 3D point using the SignedDistanceField object. Efficiently retrieves both values simultaneously. ```cpp // Query signed distance at 3D position Position3 queryPoint(0.5, 0.3, 0.2); double distance = sdf.value(queryPoint); // Get gradient (useful for optimization) Eigen::Vector3d gradient = sdf.derivative(queryPoint); // Get both value and derivative efficiently auto [dist, grad] = sdf.valueAndDerivative(queryPoint); ``` -------------------------------- ### Executable Target Definitions Source: https://github.com/anybotics/grid_map/blob/master/grid_map_demos/CMakeLists.txt Defines various executable targets for different demos and benchmarks within the grid_map project. Each executable is built from specified source files. ```cmake add_executable(simple_demo src/simple_demo_node.cpp ) add_executable(tutorial_demo src/tutorial_demo_node.cpp ) add_executable(iterators_demo src/iterators_demo_node.cpp src/IteratorsDemo.cpp ) add_executable(image_to_gridmap_demo src/image_to_gridmap_demo_node.cpp src/ImageToGridmapDemo.cpp ) add_executable(grid_map_to_image_demo src/grid_map_to_image_demo_node.cpp src/GridmapToImageDemo.cpp ) add_executable(octomap_to_gridmap_demo src/octomap_to_gridmap_demo_node.cpp src/OctomapToGridmapDemo.cpp ) add_executable(move_demo src/move_demo_node.cpp ) add_executable(iterator_benchmark src/iterator_benchmark.cpp ) add_executable(opencv_demo src/opencv_demo_node.cpp ) add_executable(resolution_change_demo src/resolution_change_demo_node.cpp ) add_executable(filters_demo src/filters_demo_node.cpp src/FiltersDemo.cpp ) add_executable(normal_filter_comparison_demo src/normal_filter_comparison_node.cpp ) add_executable(interpolation_demo src/interpolation_demo_node.cpp src/InterpolationDemo.cpp ) add_executable(sdf_demo src/sdf_demo_node.cpp src/SdfDemo.cpp ) ``` -------------------------------- ### Set C++ Standard and Compiler Flags Source: https://github.com/anybotics/grid_map/blob/master/grid_map_costmap_2d/CMakeLists.txt Configures the C++ standard to C++11 and enables common compiler warnings for better code quality. This should be set early in the CMakeLists.txt file. ```cmake cmake_minimum_required(VERSION 3.5.1) project(grid_map_costmap_2d) set(CMAKE_CXX_FLAGS "-std=c++11 ${CMAKE_CXX_FLAGS}") add_compile_options(-Wall -Wextra -Wpedantic) set(CMAKE_EXPORT_COMPILE_COMMANDS ON) ``` -------------------------------- ### Catkin Package Configuration Source: https://github.com/anybotics/grid_map/blob/master/grid_map_octomap/CMakeLists.txt Declares package information for dependent projects, including include directories, libraries, catkin dependencies, and system dependencies. ```cmake catkin_package( INCLUDE_DIRS include ${OCTOMAP_INCLUDE_DIRS} LIBRARIES ${PROJECT_NAME} ${OCTOMAP_LIBRARIES} CATKIN_DEPENDS grid_map_core DEPENDS ) ``` -------------------------------- ### Configure Clang Tools Source: https://github.com/anybotics/grid_map/blob/master/grid_map_filters/CMakeLists.txt Finds and configures clang-tools if available. This snippet specifically disables clang-format. ```cmake find_package(cmake_clang_tools QUIET) if(cmake_clang_tools_FOUND) add_default_clang_tooling( DISABLE_CLANG_FORMAT ) endif(cmake_clang_tools_FOUND) ``` -------------------------------- ### Visualize Grid Map as Flat Point Cloud Source: https://github.com/anybotics/grid_map/blob/master/README.md Configures the visualization of a grid map as a 'flat' point cloud at a specified height. This is useful for 2D maps or images. Points from empty/invalid cells can be omitted by specifying layers for validity checks. ```yaml name: flat_grid type: flat_point_cloud params: height: 0.0 ``` -------------------------------- ### Visualize Grid Map as Occupancy Grid Source: https://github.com/anybotics/grid_map/blob/master/README.md Visualizes a grid map layer as an occupancy grid. Specify the layer and the data range (min/max) for visualization. ```yaml name: traversability_grid type: occupancy_grid params: layer: traversability data_min: -0.15 data_max: 0.15 ``` -------------------------------- ### Convert Grid Map to OpenCV Images Source: https://context7.com/anybotics/grid_map/llms.txt Converts grid maps to and from OpenCV cv::Mat images. Supports initialization from grayscale or color images and adding layers from them. ```cpp #include #include // Initialize grid map from OpenCV image cv::Mat inputImage = cv::imread("terrain.png", cv::IMREAD_GRAYSCALE); GridMap map; GridMapCvConverter::initializeFromImage(inputImage, 0.01, map, Position(0.0, 0.0)); // Add layer from grayscale image (8-bit unsigned) GridMapCvConverter::addLayerFromImage( inputImage, "elevation", map, 0.0, // lowerValue (black pixels) 1.0, // upperValue (white pixels) 0.5 // alphaThreshold ); // Add color layer from BGR image cv::Mat colorImage = cv::imread("terrain_color.png", cv::IMREAD_COLOR); GridMapCvConverter::addColorLayerFromImage(colorImage, "color", map); // Convert layer to OpenCV image cv::Mat outputImage; GridMapCvConverter::toImage( map, "elevation", CV_8UC1, 0.0, // lowerValue 1.0, // upperValue outputImage ); // Auto-scaling based on min/max values in layer cv::Mat autoScaledImage; GridMapCvConverter::toImage(map, "elevation", CV_8UC1, autoScaledImage); ``` -------------------------------- ### Add Two Grid Map Layers Source: https://github.com/anybotics/grid_map/blob/master/README.md Create a new layer by element-wise adding two existing layers. ```cpp map["sum"] = map["layer_1"] + map["layer_2"]; ``` -------------------------------- ### Configure Catkin Package Source: https://github.com/anybotics/grid_map/blob/master/grid_map_filters/CMakeLists.txt Declares package information for dependent projects, including include directories, libraries, catkin dependencies, and system dependencies. This macro is essential for integrating with the ROS build system. ```cmake catkin_package( INCLUDE_DIRS include ${OpenCV_INCLUDE_DIRS} # TODO Remove this include directory, currently it exported by the medianFillFilter header. LIBRARIES ${PROJECT_NAME} ${PROJECT_NAME}_plugins CATKIN_DEPENDS ${CATKIN_PACKAGE_HEADER_DEPENDENCIES} DEPENDS OpenCV ) ``` -------------------------------- ### Add Rostest Macro Source: https://github.com/anybotics/grid_map/blob/master/grid_map_costmap_2d/rostest/CMakeLists.txt Defines a macro to add rostests using gtest. Ensure CATKIN_ENABLE_TESTING is true to run tests. ```cmake macro(${PROJECT_NAME}_add_rostest test_name) add_rostest_gtest(test_${test_name} ${test_name}/${test_name}.test ${test_name}/${test_name}.cpp) if (TARGET test_${test_name}) add_dependencies(test_${test_name} ${catkin_EXPORTED_TARGETS}) target_link_libraries(test_${test_name} ${catkin_LIBRARIES}) endif() endmacro() ``` -------------------------------- ### Convert Grid Map to ROS Messages Source: https://context7.com/anybotics/grid_map/llms.txt Converts a GridMap object to various ROS message types like GridMap, PointCloud2, and OccupancyGrid. Includes initialization from images and saving/loading to ROS bags. ```cpp #include #include #include #include GridMap map({"elevation", "color"}); map.setGeometry(Length(1.2, 2.0), 0.03); map.setFrameId("map"); map.setTimestamp(ros::Time::now().toNSec()); // Convert to ROS GridMap message grid_map_msgs::GridMap message; GridMapRosConverter::toMessage(map, message); publisher.publish(message); // Convert from ROS message GridMap receivedMap; GridMapRosConverter::fromMessage(message, receivedMap); // Convert to PointCloud2 (elevation as z-coordinate) sensor_msgs::PointCloud2 pointCloud; GridMapRosConverter::toPointCloud(map, "elevation", pointCloud); // Convert to OccupancyGrid with value range nav_msgs::OccupancyGrid occupancyGrid; GridMapRosConverter::toOccupancyGrid(map, "elevation", -0.5, 0.5, occupancyGrid); // Initialize map from image sensor_msgs::Image inputImage; GridMapRosConverter::initializeFromImage(inputImage, 0.01, map); GridMapRosConverter::addLayerFromImage(inputImage, "elevation", map, 0.0, 1.0); GridMapRosConverter::addColorLayerFromImage(inputImage, "color", map); // Convert to image sensor_msgs::Image outputImage; GridMapRosConverter::toImage(map, "elevation", sensor_msgs::image_encodings::MONO8, outputImage); // Save/load to ROS bag GridMapRosConverter::saveToBag(map, "/path/to/map.bag", "grid_map"); GridMapRosConverter::loadFromBag("/path/to/map.bag", "grid_map", map); ``` -------------------------------- ### Catkin Package Configuration Source: https://github.com/anybotics/grid_map/blob/master/grid_map_msgs/CMakeLists.txt Configures the Catkin package, declaring dependencies for dependent projects. ```cmake catkin_package( CATKIN_DEPENDS geometry_msgs message_runtime std_msgs ) ``` -------------------------------- ### Visualize Grid Map as Grid Cells Source: https://github.com/anybotics/grid_map/blob/master/README.md Visualizes a grid map layer as grid cells. Specify the layer and the thresholds for cell values. Lower and upper thresholds are optional. ```yaml name: elevation_cells type: grid_cells params: layer: elevation lower_threshold: -0.08 # optional, default: -inf upper_threshold: 0.08 # optional, default: inf ``` -------------------------------- ### Target Linking Libraries Source: https://github.com/anybotics/grid_map/blob/master/grid_map_demos/CMakeLists.txt Links the defined executable targets against catkin libraries and specific system libraries like Octomap and OpenCV. This ensures all necessary dependencies are resolved during the build process. ```cmake target_link_libraries( simple_demo ${catkin_LIBRARIES} ) target_link_libraries( tutorial_demo ${catkin_LIBRARIES} ) target_link_libraries( iterators_demo ${catkin_LIBRARIES} ) target_link_libraries( image_to_gridmap_demo ${catkin_LIBRARIES} ) target_link_libraries( grid_map_to_image_demo ${catkin_LIBRARIES} ) target_link_libraries( octomap_to_gridmap_demo ${catkin_LIBRARIES} ${OCTOMAP_LIBRARIES} ) target_link_libraries( move_demo ${catkin_LIBRARIES} ) target_link_libraries( iterator_benchmark ${catkin_LIBRARIES} ) target_link_libraries( opencv_demo ${catkin_LIBRARIES} ${OpenCV_LIBRARIES} ) target_link_libraries( resolution_change_demo ${catkin_LIBRARIES} ) target_link_libraries( filters_demo ${catkin_LIBRARIES} ) target_link_libraries( normal_filter_comparison_demo ${catkin_LIBRARIES} ) target_link_libraries( interpolation_demo ${catkin_LIBRARIES} ) target_link_libraries( sdf_demo ${catkin_LIBRARIES} ) ``` -------------------------------- ### Grid Map Filters Configuration Source: https://context7.com/anybotics/grid_map/llms.txt YAML configuration for a pipeline of grid map filters. Each filter processes an input layer to produce an output layer, with parameters defining the operation and its scope. ```yaml grid_map_filters: # Fill holes using OpenCV inpainting - name: inpaint type: gridMapCv/InpaintFilter params: input_layer: elevation output_layer: elevation_inpainted radius: 0.05 # Smooth with mean filter - name: mean_in_radius type: gridMapFilters/MeanInRadiusFilter params: input_layer: elevation_inpainted output_layer: elevation_smooth radius: 0.06 # Compute surface normals - name: surface_normals type: gridMapFilters/NormalVectorsFilter params: input_layer: elevation_inpainted output_layers_prefix: normal_vectors_ radius: 0.05 normal_vector_positive_axis: z # Compute slope from normal z-component - name: slope type: gridMapFilters/MathExpressionFilter params: output_layer: slope expression: acos(normal_vectors_z) # Compute roughness - name: roughness type: gridMapFilters/MathExpressionFilter params: output_layer: roughness expression: abs(elevation_inpainted - elevation_smooth) # Edge detection using sliding window standard deviation - name: edge_detection type: gridMapFilters/SlidingWindowMathExpressionFilter params: input_layer: slope output_layer: edges expression: sqrt(sumOfFinites(square(slope - meanOfFinites(slope))) ./ numberOfFinites(slope)) compute_empty_cells: false edge_handling: crop window_length: 0.05 # Compute traversability as weighted sum - name: traversability type: gridMapFilters/MathExpressionFilter params: output_layer: traversability expression: 0.5 * (1.0 - (slope / 0.6)) + 0.5 * (1.0 - (roughness / 0.1)) # Apply threshold - name: threshold type: gridMapFilters/ThresholdFilter params: condition_layer: traversability output_layer: traversability lower_threshold: 0.0 set_to: 0.0 # Delete intermediate layers - name: delete_layers type: gridMapFilters/DeletionFilter params: layers: [slope, roughness, edges] ``` -------------------------------- ### Iterate over Grid Map with GridMapIterator Source: https://github.com/anybotics/grid_map/blob/master/README.md Use GridMapIterator to loop through all cells of a grid map. Access cell values using `map.at()`. ```cpp for (grid_map::GridMapIterator iterator(map); !iterator.isPastEnd(); ++iterator) { cout << "The value at index " << (*iterator).transpose() << " is " << map.at("layer", *iterator) << endl; } ``` -------------------------------- ### Efficient Grid Map Iteration with Direct Data Access Source: https://github.com/anybotics/grid_map/blob/master/README.md For performance, store a reference to the layer's data outside the loop. Access elements using `data(row, col)`. ```cpp grid_map::Matrix& data = map["layer"]; for (GridMapIterator iterator(map); !iterator.isPastEnd(); ++iterator) { const Index index(*iterator); cout << "The value at index " << index.transpose() << " is " << data(index(0), index(1)) << endl; } ```