diff --git a/localization/autoware_ndt_scan_matcher_common/CMakeLists.txt b/localization/autoware_ndt_scan_matcher_common/CMakeLists.txt new file mode 100644 index 0000000000..ba8f9e88e4 --- /dev/null +++ b/localization/autoware_ndt_scan_matcher_common/CMakeLists.txt @@ -0,0 +1,62 @@ +cmake_minimum_required(VERSION 3.14) +project(autoware_ndt_scan_matcher_common) + +find_package(autoware_cmake REQUIRED) +autoware_package() + +# This package has headers only. They include Eigen and PCL, so the packages that depend on this +# package find both. Export all of PCL: a package that first finds only some components of PCL can +# miss the targets of the other components when it finds PCL again (for example, through pcl_ros). +find_package(eigen3_cmake_module REQUIRED) +find_package(Eigen3 REQUIRED) +find_package(PCL REQUIRED COMPONENTS common) +ament_export_dependencies(eigen3_cmake_module Eigen3 PCL) + +# A backend package links this target. It gives the include directory, Eigen and PCL. +add_library(${PROJECT_NAME} INTERFACE) +target_include_directories(${PROJECT_NAME} INTERFACE + $ + $) +target_link_libraries(${PROJECT_NAME} INTERFACE Eigen3::Eigen pcl_common) +install(TARGETS ${PROJECT_NAME} EXPORT export_${PROJECT_NAME}) +ament_export_targets(export_${PROJECT_NAME}) + +if(BUILD_TESTING) + find_package(ament_cmake_gtest REQUIRED) + find_package(class_loader REQUIRED) + + # The same fake backend as several plugin libraries: once with the Eigen configuration of the + # test, and once for each definition that can change the layout of the Eigen types or the heap + # allocator of Eigen, as a backend that was built with other compiler options. + set(fake_backend_definitions_same "") + set(fake_backend_definitions_align_0 EIGEN_MAX_STATIC_ALIGN_BYTES=0) + set(fake_backend_definitions_align_16 EIGEN_MAX_STATIC_ALIGN_BYTES=16) + set(fake_backend_definitions_align_32 EIGEN_MAX_STATIC_ALIGN_BYTES=32) + set(fake_backend_definitions_align_64 EIGEN_MAX_STATIC_ALIGN_BYTES=64) + set(fake_backend_definitions_allocator_eigen EIGEN_MALLOC_ALREADY_ALIGNED=0) + set(fake_backend_definitions_allocator_std EIGEN_MALLOC_ALREADY_ALIGNED=1) + + ament_add_gtest(test_ndt_backend_abi + test/test_ndt_backend_abi.cpp + ) + target_link_libraries(test_ndt_backend_abi + ${PROJECT_NAME} class_loader::class_loader ${CMAKE_DL_LIBS}) + + foreach(variant + same align_0 align_16 align_32 align_64 allocator_eigen allocator_std) + add_library(fake_ndt_backend_${variant} MODULE test/fake_ndt_backend.cpp) + target_link_libraries(fake_ndt_backend_${variant} ${PROJECT_NAME} class_loader::class_loader) + target_compile_definitions(fake_ndt_backend_${variant} PRIVATE + ${fake_backend_definitions_${variant}}) + # $<1:...> keeps a multi-config generator from adding a directory for each configuration. + set_target_properties(fake_ndt_backend_${variant} PROPERTIES + LIBRARY_OUTPUT_DIRECTORY $<1:${CMAKE_CURRENT_BINARY_DIR}/fake_ndt_backends>) + add_dependencies(test_ndt_backend_abi fake_ndt_backend_${variant}) + endforeach() + target_compile_definitions(test_ndt_backend_abi PRIVATE + FAKE_BACKEND_DIRECTORY="${CMAKE_CURRENT_BINARY_DIR}/fake_ndt_backends") +endif() + +autoware_ament_auto_package( + USE_SCOPED_HEADER_INSTALL_DIR +) diff --git a/localization/autoware_ndt_scan_matcher_common/README.md b/localization/autoware_ndt_scan_matcher_common/README.md new file mode 100644 index 0000000000..26c16787fa --- /dev/null +++ b/localization/autoware_ndt_scan_matcher_common/README.md @@ -0,0 +1,76 @@ +# autoware_ndt_scan_matcher_common + +## Purpose + +This package holds the interface between [autoware_ndt_scan_matcher](../autoware_ndt_scan_matcher/README.md) and its NDT backends. An NDT backend is an implementation of NDT scan matching that the node loads with [pluginlib](https://github.com/ros/pluginlib). This package has headers only. + +A backend package depends on this package, not on the node and its ROS dependencies. + +![The interface package holds NdtBackend, NdtParams, NdtResult and an ABI guard. The node calls the interface, and backend packages implement it.](media/ndt-backend-interface.svg) + +## Contents + +- `autoware::ndt_scan_matcher::NdtBackend` in `autoware/ndt_scan_matcher_common/ndt_backend.hpp`: the interface of a backend. Its comments state the rules for a backend: instances, threads, the order of calls, exceptions, copies and the lifetime of the library. +- `autoware::ndt_scan_matcher::NdtParams` and `autoware::ndt_scan_matcher::NdtResult` in `autoware/ndt_scan_matcher_common/ndt_types.hpp`: the parameters and the result of an alignment. The comments of `NdtResult` state how the node uses each field and how a backend must compute the scores. + +## How the node uses a backend + +The node has two instances of the backend: the active instance, and the instance that the map update thread builds. It calls them in three places: + +1. At startup, pluginlib makes the backend with the name in `ndt.backend`, and the node calls `initialize()`. +2. The map update thread changes the map of the second instance with `add_target()`, `remove_target()` and `commit_target()`. Then the node swaps the two instances under a short lock. +3. The scan callback calls `align()` on the active instance for each scan. The node compares the scores of the `NdtResult` with its thresholds and accepts or rejects the pose. + +![At startup, pluginlib makes the backend and the node calls initialize(). The map update thread fills an instance and the node swaps the instances. The scan callback calls align() on the active instance.](media/ndt-backend-calls.svg) + +The comments in `ndt_backend.hpp` state the exact rules for each of these calls. + +## Add a backend + +![Add a backend in four steps: depend, implement, build and register. Then the node loads the backend when ndt.backend has its name.](media/ndt-backend-add.svg) + +A backend package does these steps: + +1. Depend on `autoware_ndt_scan_matcher_common` and `pluginlib` in `package.xml`. +2. Implement `autoware::ndt_scan_matcher::NdtBackend`, and export the class with `PLUGINLIB_EXPORT_CLASS`. +3. Build the class into a library with `add_library()`, link the targets of `autoware_ndt_scan_matcher_common` and `pluginlib` with `target_link_libraries()`, and install the library. Do not use `ament_auto_add_library()`: ament_auto exports the library and links it into the packages that depend on the backend package. pluginlib loads the library at runtime, so no other library may link it. The target of `autoware_ndt_scan_matcher_common` gives only the `common` component of PCL. A backend that uses another component of PCL, for example `kdtree`, finds and links that component itself. +4. Register the class with `pluginlib_export_plugin_description_file(autoware_ndt_scan_matcher_common .xml)`. + +`CMakeLists.txt`: + +```cmake +cmake_minimum_required(VERSION 3.14) +project(my_package) + +find_package(ament_cmake REQUIRED) +find_package(autoware_ndt_scan_matcher_common REQUIRED) +find_package(pluginlib REQUIRED) + +add_library(my_ndt_backend SHARED src/my_ndt_backend.cpp) +target_link_libraries(my_ndt_backend + ${autoware_ndt_scan_matcher_common_TARGETS} ${pluginlib_TARGETS}) +install(TARGETS my_ndt_backend LIBRARY DESTINATION lib) +pluginlib_export_plugin_description_file(autoware_ndt_scan_matcher_common plugins.xml) + +ament_package() +``` + +`plugins.xml`: + +```xml + + + My NDT backend. + + +``` + +`path` is the name of the library. `type` is the class that `PLUGINLIB_EXPORT_CLASS` exports. `name` is the value of `ndt.backend` that selects the backend. Use a short, lowercase name that tells the implementation, for example `ndt_omp` or `ndt_cuda`. A name must be unique among all installed backends, so do not use only the name of a technology that other implementations can also use, for example `cuda`. + +## Compile options + +`NdtResult` holds fixed-size `Eigen` types, which pass between the node and the backend library. Their memory layout depends on the static alignment of `Eigen`, which depends on the SIMD options of the compiler: AVX changes it, and SSE does not. The node also frees vectors that the backend allocated with the allocator of `Eigen`. Some options change this allocator, for example AVX or the address sanitizer of GCC. + +The types and the interface are in an inline namespace whose name holds the version of the interface, the `Eigen` alignment (`EIGEN_MAX_STATIC_ALIGN_BYTES`) and the `Eigen` allocator. A backend that was built against another version of the interface, or with an alignment or an allocator that differs from the node, has other C++ symbols. Then the node loads its library but finds no factory for the backend, and it stops with an error message that names this cause. Rebuild the backend against the same version of Autoware Core, and do not enable AVX or a sanitizer in only one of the two. The name does not hold the version of `Eigen` or of PCL, so the node and the backend must also use the same `Eigen` and the same PCL. `NdtBackend` passes `pcl::PointCloud` between them. + +When a declaration in `ndt_types.hpp` or `ndt_backend.hpp` changes, change the version `v1` in the name of the inline namespace. diff --git a/localization/autoware_ndt_scan_matcher_common/include/autoware/ndt_scan_matcher_common/ndt_backend.hpp b/localization/autoware_ndt_scan_matcher_common/include/autoware/ndt_scan_matcher_common/ndt_backend.hpp new file mode 100644 index 0000000000..931f3fb503 --- /dev/null +++ b/localization/autoware_ndt_scan_matcher_common/include/autoware/ndt_scan_matcher_common/ndt_backend.hpp @@ -0,0 +1,139 @@ +// Copyright 2026 Autoware Foundation +// +// 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. + +#ifndef AUTOWARE__NDT_SCAN_MATCHER_COMMON__NDT_BACKEND_HPP_ +#define AUTOWARE__NDT_SCAN_MATCHER_COMMON__NDT_BACKEND_HPP_ + +#include "autoware/ndt_scan_matcher_common/ndt_types.hpp" + +#include + +#include +#include + +#include +#include +#include + +namespace autoware::ndt_scan_matcher +{ +inline namespace AUTOWARE_NDT_BACKEND_ABI +{ +/// An implementation of NDT scan matching for autoware_ndt_scan_matcher. The node loads it with +/// pluginlib, by the name in its parameter `ndt.backend`. The README of this package explains how +/// a package adds a backend. +/// +/// Instances: the node calls initialize() only on the instance that pluginlib makes. clone() and +/// clone_empty() make instances that are ready without initialize(), so they must share or take +/// again what initialize() took. The node destroys the instance from pluginlib at the first full +/// map rebuild. +/// +/// Threads: one thread at a time uses one instance, but different threads use it over its life. +/// So a backend must not need a resource that works only in one thread. Two instances (the active +/// one and the one that the map update module builds) run at the same time in two threads, so they +/// must not share mutable state. +/// +/// Order of calls: after add_target() or remove_target(), the node calls commit_target() before it +/// calls any function of the instance other than these two. The node calls align() and the +/// calculate functions only while has_target() is true. The source of align() always has points. +/// The cloud of a calculate function can be empty. +/// +/// Exceptions: an exception from initialize() stops the node at startup. The node does not catch +/// exceptions from the other functions either, so such an exception stops the node. +/// +/// Library lifetime: the node never unloads a backend library. So clone() and clone_empty() can +/// make instances in the library without pluginlib. +class NdtBackend +{ +public: + using PointSource = pcl::PointXYZ; + using PointTarget = pcl::PointXYZ; + using SharedPtr = std::shared_ptr; + + virtual ~NdtBackend() = default; + + /// Called once, after pluginlib makes the instance. A backend that needs a resource (for + /// example, a GPU) gets it here, and throws std::runtime_error if it cannot run on this computer. + virtual void initialize(const NdtParams & params) = 0; + + /// The name of the backend, for logs. + virtual std::string name() const = 0; + + /// The parameters that the backend uses. The node compares NdtResult::iteration_num with + /// get_params().max_iterations. + virtual NdtParams get_params() const = 0; + + /// add_target() and remove_target() change the map, and commit_target() finishes the change. + /// These three functions do all the map work, on an instance that no other thread uses at the + /// same time. align() must not do map work that these functions deferred. + /// + /// The backend can keep the cloud. The node takes the ids from the map loader and does not + /// examine them. Normally, each map_id is unique among the added clouds and remove_target() gets + /// only ids that were added. remove_target() must ignore an id that was not added. + virtual void add_target( + const pcl::PointCloud::ConstPtr & cloud, const std::string & map_id) = 0; + virtual void remove_target(const std::string & map_id) = 0; + virtual void commit_target() = 0; + /// The ids of the map clouds that were added and not removed. + virtual std::vector get_current_map_ids() const = 0; + /// True if get_current_map_ids() is not empty. The map can still have no voxel, for example if + /// no cell has enough points. Then align() must return a result and must not fail. + virtual bool has_target() const = 0; + + /// An independent instance with the same parameters, map, regularization pose and state. Later + /// changes to one instance do not change the other. The node calls it on the active instance + /// while it holds the lock of that instance, so a long copy delays the alignments. It also calls + /// it on the instance that the map update thread builds, which no other thread uses at that time. + /// The instances can share immutable data, for example a map that is already on the GPU. + virtual SharedPtr clone() const = 0; + /// A new instance of the same backend, with the same parameters, without a map and without a + /// regularization pose. + virtual SharedPtr clone_empty() const = 0; + + /// Sets the regularization pose (base_link to map) for the next alignments, until + /// unset_regularization_pose(). The regularization pulls the aligned pose toward the x and y of + /// this pose, along the heading of the vehicle, with the weight + /// NdtParams::regularization_scale_factor. The node sets it only if its parameter + /// `ndt.regularization.enable` is true. + virtual void set_regularization_pose(const Eigen::Matrix4f & pose) = 0; + virtual void unset_regularization_pose() = 0; + + /// Aligns source (in the base_link frame) to the map, from guess (base_link to map). The backend + /// does not keep source after it returns. NdtResult describes what the node needs from each + /// field. + virtual NdtResult align( + const Eigen::Matrix4f & guess, const pcl::PointCloud::ConstPtr & source) = 0; + + /// The scores of NdtResult for a cloud that is already in the map frame, without the + /// regularization. For an empty cloud, the two scores are 0 and the cloud of the third function + /// is empty. + virtual double calculate_transformation_probability( + const pcl::PointCloud & cloud_in_map) const = 0; + virtual double calculate_nearest_voxel_transformation_likelihood( + const pcl::PointCloud & cloud_in_map) const = 0; + /// The points of the cloud that have at least one voxel near them, each with its largest NDT + /// score as the intensity, in any order. + virtual pcl::PointCloud calculate_nearest_voxel_score_each_point( + const pcl::PointCloud & cloud_in_map) const = 0; + +protected: + NdtBackend() = default; + // Only a derived class copies the base, for clone(). This prevents slicing. + NdtBackend(const NdtBackend &) = default; + NdtBackend & operator=(const NdtBackend &) = delete; +}; +} // namespace AUTOWARE_NDT_BACKEND_ABI +} // namespace autoware::ndt_scan_matcher + +#endif // AUTOWARE__NDT_SCAN_MATCHER_COMMON__NDT_BACKEND_HPP_ diff --git a/localization/autoware_ndt_scan_matcher_common/include/autoware/ndt_scan_matcher_common/ndt_types.hpp b/localization/autoware_ndt_scan_matcher_common/include/autoware/ndt_scan_matcher_common/ndt_types.hpp new file mode 100644 index 0000000000..9f3c068f22 --- /dev/null +++ b/localization/autoware_ndt_scan_matcher_common/include/autoware/ndt_scan_matcher_common/ndt_types.hpp @@ -0,0 +1,151 @@ +// Copyright 2026 Autoware Foundation +// +// 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. + +#ifndef AUTOWARE__NDT_SCAN_MATCHER_COMMON__NDT_TYPES_HPP_ +#define AUTOWARE__NDT_SCAN_MATCHER_COMMON__NDT_TYPES_HPP_ + +#include + +#include + +// The types of the NDT backend interface are in an inline namespace whose name holds three things: +// the version of the interface, the static alignment of Eigen, and the heap allocator of Eigen. +// The alignment depends on the SIMD options of the compiler (for example, AVX makes it 32). The +// allocator is std::malloc(), or an allocator of Eigen with another pointer layout (for example, +// with AVX, or with the address sanitizer of GCC). The interface passes fixed-size Eigen types by +// value, and one side frees vectors that the other side allocated, so both must agree. +// +// A backend that was built against another version, or with another alignment or allocator than +// the node, has other C++ symbols. Then the node loads its library but finds no factory for the +// backend. Without this, the node and the backend corrupt the memory of each other. +// +// The name does not hold the version of Eigen. The node and its backends must use the same Eigen. +// +// Change "v1" below when a declaration in ndt_types.hpp or ndt_backend.hpp changes. +#ifdef EIGEN_DEFAULT_TO_ROW_MAJOR +#error "The NDT backend interface needs the default (column-major) storage order of Eigen." +#endif +#if EIGEN_MAX_STATIC_ALIGN_BYTES == 0 +#define AUTOWARE_NDT_BACKEND_ABI_ALIGN 0 +#elif EIGEN_MAX_STATIC_ALIGN_BYTES == 16 +#define AUTOWARE_NDT_BACKEND_ABI_ALIGN 16 +#elif EIGEN_MAX_STATIC_ALIGN_BYTES == 32 +#define AUTOWARE_NDT_BACKEND_ABI_ALIGN 32 +#elif EIGEN_MAX_STATIC_ALIGN_BYTES == 64 +#define AUTOWARE_NDT_BACKEND_ABI_ALIGN 64 +#else +#error "Unknown value of EIGEN_MAX_STATIC_ALIGN_BYTES" +#endif +// The condition of Eigen::internal::aligned_malloc() for std::malloc(). +#if (EIGEN_DEFAULT_ALIGN_BYTES == 0) || EIGEN_MALLOC_ALREADY_ALIGNED +#define AUTOWARE_NDT_BACKEND_ABI_ALLOCATOR std +#else +#define AUTOWARE_NDT_BACKEND_ABI_ALLOCATOR eigen +#endif +#define AUTOWARE_NDT_BACKEND_ABI_JOIN_IMPL(version, align, allocator) \ + version##_eigen_align_##align##_malloc_##allocator +#define AUTOWARE_NDT_BACKEND_ABI_JOIN(version, align, allocator) \ + AUTOWARE_NDT_BACKEND_ABI_JOIN_IMPL(version, align, allocator) +// For example, v1_eigen_align_16_malloc_std. +#define AUTOWARE_NDT_BACKEND_ABI \ + AUTOWARE_NDT_BACKEND_ABI_JOIN( \ + v1, AUTOWARE_NDT_BACKEND_ABI_ALIGN, AUTOWARE_NDT_BACKEND_ABI_ALLOCATOR) + +namespace autoware::ndt_scan_matcher +{ +inline namespace AUTOWARE_NDT_BACKEND_ABI +{ +/// The parameters of an NDT alignment. The node sets every field from its parameters. +/// +/// A step of the alignment is a 6-D vector: x, y and z in meters, and roll, pitch and yaw in +/// radians. +struct NdtParams +{ + /// The alignment stops when the length of a step is less than this. + double trans_epsilon{}; + /// The largest length of one step. + double step_size{}; + /// The size of a voxel of the map [m]. It is also the search radius for the voxels near a point. + float resolution{}; + /// The largest number of iterations of one alignment. + int max_iterations{}; + /// The number of CPU threads that the backend can use. At least 1. + int num_threads{}; + /// The weight of the regularization. It has an effect only while a regularization pose is set + /// (NdtBackend::set_regularization_pose()). + float regularization_scale_factor{}; +}; + +/// The result of an NDT alignment. +/// +/// The node compares the scores with thresholds that are tuned for ndt_omp, so a backend must +/// compute them as ndt_omp does. The NDT score of a point for one voxel is the score of Magnusson +/// (2009, eq. 6.9) with an outlier ratio of 0.55. The voxels near a point are the voxels whose +/// mean is within NdtParams::resolution of the point. +/// +/// The scores also depend on the voxels. ndt_omp builds them in this way: +/// - Each map cloud (each map_id) has its own grid. So two clouds can each have a voxel for the +/// same cell. +/// - A voxel is a cube with the side NdtParams::resolution. A point p is in the cell +/// floor(p / resolution). +/// - A voxel needs at least 6 points. Cells with fewer points have no voxel. +/// - The covariance of a voxel with n points p_i and the mean m is +/// (I + sum((p_i - m) * (p_i - m)^T)) / (n - 1). I is the 3x3 identity matrix. So it is larger +/// than the sample covariance by I / (n - 1). +/// - After that, an eigenvalue of the covariance that is less than 0.01 times the largest +/// eigenvalue is raised to that value. +/// +/// The regularization score is -s * n * d * d. s is NdtParams::regularization_scale_factor. n is +/// the number of pairs of a point and a voxel near it. d is the distance from the pose to the +/// regularization pose along the heading of the pose: d = dx * cos(yaw) + dy * sin(yaw). yaw is the +/// third angle of Eigen's eulerAngles(0, 1, 2) of the pose, as in the hessian. +/// +/// The backend "ndt_omp" of autoware_ndt_scan_matcher is the reference for all of these rules. +struct NdtResult +{ + /// The aligned pose (base_link to map). + Eigen::Matrix4f pose{Eigen::Matrix4f::Identity()}; + /// The sum of the NDT scores of each point for all voxels near it, plus the regularization score + /// if a regularization pose is set, divided by the number of all points (also the points with no + /// voxel near them). 0 for an empty source. The node compares it with a threshold. + float transform_probability{}; + /// The sum of the largest NDT score of each point among the voxels near it, divided by the + /// number of points that have at least one voxel near them. 0 if no point has a voxel near it. + /// It does not include the regularization. The node compares it with a threshold (the default). + float nearest_voxel_transformation_likelihood{}; + /// The number of iterations. If it is not less than NdtParams::max_iterations, the node treats + /// the alignment as not converged, unless the poses of transformation_array oscillate. + int iteration_num{}; + /// The guess, then the pose after each iteration (iteration_num + 1 poses). The node finds + /// oscillations in these poses, so an empty array changes which alignments the node accepts. + std::vector> transformation_array; + /// The hessian of the sum score (transform_probability times the number of points, with the + /// regularization) at the aligned pose, in the order (x, y, z, roll, pitch, yaw). The angles are + /// those of Eigen's eulerAngles(0, 1, 2). It is negative definite at a maximum of the score. For + /// the covariance estimation LAPLACE, the node uses the inverse of its x-y block, negated, as the + /// covariance of x and y. + Eigen::Matrix hessian{Eigen::Matrix::Zero()}; + /// transform_probability at the guess and after each iteration (iteration_num + 1 values): + /// front() at the guess, back() at the aligned pose. The node uses front() and back(). For other + /// sizes, it does not use the array and gives a warning in the diagnostics. + std::vector transform_probability_array; + /// The same as transform_probability_array, for nearest_voxel_transformation_likelihood. + std::vector nearest_voxel_transformation_likelihood_array; + + EIGEN_MAKE_ALIGNED_OPERATOR_NEW +}; +} // namespace AUTOWARE_NDT_BACKEND_ABI +} // namespace autoware::ndt_scan_matcher + +#endif // AUTOWARE__NDT_SCAN_MATCHER_COMMON__NDT_TYPES_HPP_ diff --git a/localization/autoware_ndt_scan_matcher_common/media/ndt-backend-add.svg b/localization/autoware_ndt_scan_matcher_common/media/ndt-backend-add.svg new file mode 100644 index 0000000000..f8cde2162c --- /dev/null +++ b/localization/autoware_ndt_scan_matcher_common/media/ndt-backend-add.svg @@ -0,0 +1,175 @@ + + + Add a backend in four steps: depend on the interface package, implement NdtBackend, build a plain library, and register the class in a plugin description file. Then the node loads the backend when + ndt.backend has its name. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1 + Depend + package.xml + On the interface package + and on pluginlib + + + + + 2 + Implement + class My : NdtBackend + Export the class with + PLUGINLIB_EXPORT_CLASS + + + + + 3 + Build + add_library() + A plain library that no + other library links + + + + + 4 + Register + plugins.xml + The name of the class is + the value of ndt.backend + + + + + install + + + + + The node loads your backend + ndt.backend: "my_backend" + No change to the node or to Autoware Core + + pluginlib finds the backend + through the plugin description + file. No other library links it. + diff --git a/localization/autoware_ndt_scan_matcher_common/media/ndt-backend-calls.svg b/localization/autoware_ndt_scan_matcher_common/media/ndt-backend-calls.svg new file mode 100644 index 0000000000..583e23f23a --- /dev/null +++ b/localization/autoware_ndt_scan_matcher_common/media/ndt-backend-calls.svg @@ -0,0 +1,205 @@ + + + How the node calls a backend. At startup, pluginlib makes the backend and the node calls initialize(). The map update thread fills an instance with add_target(), remove_target() and + commit_target(), and the node then swaps the instances. The scan callback calls align() on the active instance and uses the NdtResult. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1. At startup + Once, in the constructor of the node + + + pluginlib makes the backend + ndt.backend: "ndt_omp" + + + + initialize(params) + Gets resources, for example a GPU + + + + has_target() == false + No alignment before the first map + + An error here stops the node + with the name of the backend. + + + + 2. Map update thread + When the vehicle moves to new map cells + + + clone_empty() or clone() + A second instance for the new map + + + + add_target(), remove_target() + Map clouds, each with an id + + + + commit_target() + All heavy map work finishes here + + + + The node swaps the instances + Under a short lock + + + + 3. Scan callback + For each LiDAR scan + + + align(guess, scan) + On the active instance, no map work + + + + NdtResult + Pose, scores, iterations, hessian + + + + calculate_...(cloud_in_map) + Scores of other clouds, if enabled + + + + The node accepts or rejects + It compares the scores with thresholds + + + + + + active + + One thread at a time uses one instance. The active instance and the instance that the map update thread builds + run at the same time, so they must not share mutable state. + diff --git a/localization/autoware_ndt_scan_matcher_common/media/ndt-backend-interface.svg b/localization/autoware_ndt_scan_matcher_common/media/ndt-backend-interface.svg new file mode 100644 index 0000000000..f405ee7dff --- /dev/null +++ b/localization/autoware_ndt_scan_matcher_common/media/ndt-backend-interface.svg @@ -0,0 +1,204 @@ + + + The interface package holds the NdtBackend interface, the types NdtParams and NdtResult, and an ABI guard. The NDT scan matcher node calls the interface. Backend packages implement it and depend + only on this package. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + NDT scan matcher node + Loads one backend + with pluginlib + + + + Interface package + autoware_ndt_scan_matcher_common + + + + + NdtBackend + The interface: 16 pure virtual functions + Map, alignment, scores and copies + + + NdtParams + The 6 parameters + of an alignment + + + NdtResult + Pose, scores, iterations + and hessian + + + + + ABI guard + An inline namespace with the interface version, + the Eigen alignment and the Eigen allocator + v1_eigen_align_16_malloc_std + + + + + calls + + + + Backend packages + + + ndt_omp backend + On the CPU + + + Your backend + For example, on a GPU + + + + + Backends implement + NdtBackend. A backend + package depends only on + the interface package, + not on the node. + diff --git a/localization/autoware_ndt_scan_matcher_common/package.xml b/localization/autoware_ndt_scan_matcher_common/package.xml new file mode 100644 index 0000000000..7486958f95 --- /dev/null +++ b/localization/autoware_ndt_scan_matcher_common/package.xml @@ -0,0 +1,30 @@ + + + + autoware_ndt_scan_matcher_common + 1.10.0 + The NDT backend interface of autoware_ndt_scan_matcher + Yamato Ando + Masahiro Sakamoto + NGUYEN Viet Anh + Taiki Yamada + Apache License 2.0 + Mete Fatih Cırıt + ament_cmake_auto + autoware_cmake + eigen3_cmake_module + eigen3_cmake_module + + eigen + libpcl-all-dev + + ament_cmake_cppcheck + ament_cmake_gtest + ament_lint_auto + autoware_lint_common + class_loader + + + ament_cmake + + diff --git a/localization/autoware_ndt_scan_matcher_common/test/fake_ndt_backend.cpp b/localization/autoware_ndt_scan_matcher_common/test/fake_ndt_backend.cpp new file mode 100644 index 0000000000..d5220f9484 --- /dev/null +++ b/localization/autoware_ndt_scan_matcher_common/test/fake_ndt_backend.cpp @@ -0,0 +1,87 @@ +// Copyright 2026 Autoware Foundation +// +// 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. + +// A minimal backend in a plugin library, for test_ndt_backend_abi. + +#include +#include + +#include +#include +#include + +namespace fake +{ + +using autoware::ndt_scan_matcher::NdtBackend; +using autoware::ndt_scan_matcher::NdtParams; +using autoware::ndt_scan_matcher::NdtResult; + +class FakeBackend : public NdtBackend +{ +public: + void initialize(const NdtParams & params) override { params_ = params; } + std::string name() const override { return "fake"; } + NdtParams get_params() const override { return params_; } + void add_target(const pcl::PointCloud::ConstPtr &, const std::string &) override {} + void remove_target(const std::string &) override {} + void commit_target() override {} + std::vector get_current_map_ids() const override { return {}; } + bool has_target() const override { return false; } + SharedPtr clone() const override { return std::make_shared(*this); } + SharedPtr clone_empty() const override { return std::make_shared(); } + void set_regularization_pose(const Eigen::Matrix4f &) override {} + void unset_regularization_pose() override {} + NdtResult align( + const Eigen::Matrix4f & guess, const pcl::PointCloud::ConstPtr &) override + { + NdtResult result; + result.pose = guess; + return result; + } + double calculate_transformation_probability(const pcl::PointCloud &) const override + { + return 0.0; + } + double calculate_nearest_voxel_transformation_likelihood( + const pcl::PointCloud &) const override + { + return 0.0; + } + pcl::PointCloud calculate_nearest_voxel_score_each_point( + const pcl::PointCloud &) const override + { + return {}; + } + +private: + NdtParams params_{}; +}; + +} // namespace fake + +CLASS_LOADER_REGISTER_CLASS(fake::FakeBackend, autoware::ndt_scan_matcher::NdtBackend) + +// The Eigen configuration of this library, from the macros of Eigen and not from the name of the +// inline namespace. The test compares it with its own configuration. +extern "C" int fake_ndt_backend_static_alignment() +{ + return EIGEN_MAX_STATIC_ALIGN_BYTES; +} + +// 1 if Eigen::internal::aligned_malloc() is std::malloc(). +extern "C" int fake_ndt_backend_std_malloc() +{ + return ((EIGEN_DEFAULT_ALIGN_BYTES == 0) || EIGEN_MALLOC_ALREADY_ALIGNED) ? 1 : 0; +} diff --git a/localization/autoware_ndt_scan_matcher_common/test/test_ndt_backend_abi.cpp b/localization/autoware_ndt_scan_matcher_common/test/test_ndt_backend_abi.cpp new file mode 100644 index 0000000000..5a810fc913 --- /dev/null +++ b/localization/autoware_ndt_scan_matcher_common/test/test_ndt_backend_abi.cpp @@ -0,0 +1,112 @@ +// Copyright 2026 Autoware Foundation +// +// 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. + +// The inline namespace of the interface must keep a backend with another Eigen alignment or +// another heap allocator of Eigen from loading. Without the inline namespace, the test of each +// library with another configuration fails. + +#include +#include + +#include +#include + +#include +#include + +namespace +{ + +using autoware::ndt_scan_matcher::NdtBackend; + +// A copy assignment cannot slice a backend. +static_assert(!std::is_copy_assignable_v); + +// The Eigen configuration of this test, as fake_ndt_backend.cpp computes it for a library. +constexpr int static_alignment = EIGEN_MAX_STATIC_ALIGN_BYTES; +constexpr int std_malloc = + ((EIGEN_DEFAULT_ALIGN_BYTES == 0) || EIGEN_MALLOC_ALREADY_ALIGNED) ? 1 : 0; + +std::string library_path(const std::string & variant) +{ + return std::string(FAKE_BACKEND_DIRECTORY) + "/libfake_ndt_backend_" + variant + ".so"; +} + +// Calls a function of a library that is already loaded. +int call(const std::string & library, const char * function) +{ + void * handle = dlopen(library.c_str(), RTLD_NOW | RTLD_NOLOAD); + EXPECT_NE(handle, nullptr) << library; + if (handle == nullptr) { + return -1; + } + const auto pointer = reinterpret_cast(dlsym(handle, function)); // NOLINT + EXPECT_NE(pointer, nullptr) << function; + const int value = (pointer != nullptr) ? pointer() : -1; + dlclose(handle); + return value; +} + +// "same" has no definition of its own. The other libraries set a static alignment of 0, 16, 32 +// (AVX) or 64 bytes (AVX-512), or the allocator: the one of Eigen or std::malloc(). Which of them +// have the configuration of the test depends on the compiler options of the build. +constexpr const char * variants[] = {"same", "align_0", "align_16", "align_32", + "align_64", "allocator_eigen", "allocator_std"}; + +// The library must be loaded. +bool has_same_configuration(const std::string & library) +{ + return call(library, "fake_ndt_backend_static_alignment") == static_alignment && + call(library, "fake_ndt_backend_std_malloc") == std_malloc; +} + +class FakeBackendLibrary : public testing::TestWithParam +{ +}; + +// A library loads only if its Eigen configuration is the configuration of this test. +TEST_P(FakeBackendLibrary, LoadsOnlyWithTheSameConfiguration) +{ + const std::string library = library_path(GetParam()); + class_loader::ClassLoader loader(library); + + if (has_same_configuration(library)) { + const auto backend = loader.createUniqueInstance("fake::FakeBackend"); + ASSERT_NE(backend, nullptr); + EXPECT_EQ(backend->name(), "fake"); + } else { + EXPECT_THROW( + loader.createUniqueInstance("fake::FakeBackend"), + class_loader::CreateClassException); + } +} + +INSTANTIATE_TEST_SUITE_P(NdtBackendAbi, FakeBackendLibrary, testing::ValuesIn(variants)); + +// At least the alignments that differ from the test give another configuration, so the +// definitions of the libraries have an effect. +TEST(FakeBackendLibraries, DefinitionsChangeTheConfiguration) +{ + int other_configuration_count = 0; + for (const char * variant : variants) { + const std::string library = library_path(variant); + const class_loader::ClassLoader loader(library); + if (!has_same_configuration(library)) { + ++other_configuration_count; + } + } + EXPECT_GE(other_configuration_count, 3); +} + +} // namespace