namespace mola¶
Overview¶
@file VizInterface.cpp @brief Virtual visualization interface (see MolaViz) @author Jose Luis Blanco Claraco @date Feb 15, 2026
namespace mola { // namespaces namespace mola::cov_diag; namespace mola::detail; namespace mola::factors; namespace mola::factors::detail; namespace mola::gtsam_compat; namespace mola::gui; namespace mola::imu; namespace mola::internal; namespace mola::kf_cli; namespace mola::mm_cli; namespace mola::state_estimation_simple; namespace mola::state_estimation_smoother; // typedefs typedef std::allocator<T> FastAllocator; typedef std::set<T, Compare, FastAllocator<T>> fast_set; typedef std::map<Key, T, Compare, FastAllocator<std::pair<const Key, T>>> fast_map; typedef std::uint64_t id_t; typedef std::uint64_t fid_t; typedef mrpt::system::CTimeLogger Profiler; typedef mrpt::system::CTimeLoggerEntry ProfilerEntry; typedef mrpt::system::CTimeLoggerSaveAtDtor ProfilerSaverAtDtor; typedef mrpt::poses::CPose3DInterpolator trajectory_t; typedef mrpt::obs::CObservation CObservation; typedef std::size_t timestep_t; typedef mrpt::containers::yaml Yaml; typedef mp2p_icp::MatchingDistanceProfile MatchingDistanceProfile; typedef std::variant<std::monostate, SensorCamera, SensorIMU> SensorEntry; typedef uint64_t euroc_timestamp_t; typedef std::multimap<euroc_timestamp_t, SensorEntry> euroc_dataset_t; // enums enum DiagnosticLevel; enum InitLocalization; enum InputMode; enum PointIndexType; enum ViewDirectionFilter; // structs struct AddGNSSFactorParams; struct AddIMUAttitudeFactorParams; struct AddIMUGravityFactorParams; struct CandidateSelection; struct CandidateSelectionParameters; struct ConsoleLogEntry; struct DiagnosticKeyValue; struct DiagnosticStatusMsg; struct FrameGNSS; struct FrameIMU; struct FrameIMUAcc; struct GNSSFrames; struct Georeferencing; struct IMUAccFrames; struct IMUFrames; struct ImuBias; struct KeyframeDecisionOptions; struct LocalMapCorrection; struct LocalMapKeyframe; struct LogRecord; struct MetricSample; struct NavState; struct RelocalizationICP_SE2; struct RelocalizationLikelihood_SE2; struct SMGeoReferencingOutput; struct SMGeoReferencingParams; struct SensorCamera; struct SensorIMU; struct SimplemapAttachOptions; struct SimplemapAttachResult; struct TransformTree; struct TransformTreeNode; struct YAMLParseOptions; template <typename cell_coord_t = int32_t> struct index3d_hash; template <typename cell_coord_t = int32_t> struct index3d_t; template <typename cell_coord_t = int32_t> struct index_se3_t; template <typename cell_coord_t = int32_t> struct index_se3_t_hash; template <class... Ts> struct overloaded; // classes class AdaptiveDecimation; class BinFileDataset; class BridgeROS2; class ConsoleLogSink; class Dataset_UI; class DiagnosticsProvider; class EurocDataset; class ExecutableBase; class FilterBase; template <typename T, size_t SIDE_NUM_BITS, typename inner_coord_t> class FixedDenseGrid3D; class FrontEndBase; class GravityLeveler; class HashedSetSE3; class HashedVoxelPointCloud; class ImuBiasSource; class IncrementalPointCloud; class KeyframeAttachmentBuffer; class KeyframeDecider; class KeyframePointCloudMap; class Kitti360Dataset; class KittiOdometryDataset; class LidarOdometry; class LocalMapCorrectionSource; class LocalizationSourceBase; class LogHub; class MapServer; class MapSourceBase; class MetricChannel; class MetricChannelImpl; class MetricsRegistry; class MinimalModuleContainer; class MockBiasEstimator; class MockDiagModule; class MockLogModule; class MockOtherModule; class MockQueueModule; class MolaLauncherApp; class MolaViz; class MolaVizImGui; class MolaVizImGuiCore; class MulranDataset; class NDT; class NavStateFilter; class OccGrid; class OfflineDatasetSource; class OptionsCapable; class ParisLucoDataset; class PendingImuBuffer; class PointTimeOutlierFilter; class RawDataConsumer; class RawDataSourceBase; class RawlogDataset; class RegexCache; class Relocalization; class RgbdAssembler; class Rosbag2Dataset; class ScanImuWaitList; class SearchablePoseList; class SharedKeyframeMap; class SparseTreesPointCloud; class SparseVoxelPointCloud; class Synchronizer; class TSDF; class TransformTreeSource; class VideoDataset; class VideoRecorder; class VizInterface; class WallUpReader; // global variables constexpr id_t INVALID_ID = std::numeric_limits<id_t>::max(); constexpr fid_t INVALID_FID = std::numeric_limits<fid_t>::max(); constexpr unsigned int DEFAULT_MAX_PARALLEL_THREADS = 4; // global functions void pretty_print_exception( const std::exception& e, const std::string& headerLine, const bool use_std_cerr = true ); unsigned int physical_core_count(); unsigned int max_parallel_threads(); SimplemapAttachResult simplemap_attach_observations( const std::string& inputFile, const std::string& outputFile, const OfflineDatasetSource& dataset, const SimplemapAttachOptions& options, const std::function<void(double)>& progress = {} ); template <class... Ts> overloaded(Ts...); template <typename cell_coord_t> std::ostream& operator << ( std::ostream& o, const index3d_t<cell_coord_t>& idx ); void exportLoadableOptionsToIni( const mrpt::config::CLoadableOptions& opts, mrpt::config::CConfigFileBase& cfg, const std::string& section, const std::set<std::string>& excludeKeys = {} ); bool importLoadableOptionsFromIni( mrpt::config::CLoadableOptions& opts, const mrpt::config::CConfigFileBase& cfg, const std::string& section ); bool exportMapLayerOptionsToIni( mrpt::maps::CMetricMap& map, mrpt::config::CConfigFileBase& cfg, const std::string& layerName ); bool importMapLayerOptionsFromIni( mrpt::maps::CMetricMap& map, const mrpt::config::CConfigFileBase& cfg, const std::string& layerName, std::vector<std::string>* appliedSections = nullptr, std::vector<std::string>* rejectedSections = nullptr ); template <typename cell_coord_t> std::ostream& operator << ( std::ostream& o, const index_se3_t<cell_coord_t>& idx ); auto refine_relocalization_candidates( const std::vector<RelocalizationICP_SE2::Candidate>& candidates, const mp2p_icp::metric_map_t& local_map, const mp2p_icp::metric_map_t& reference_map, mp2p_icp::ICP& icp, const mp2p_icp::Parameters& icp_parameters, const CandidateSelectionParameters& modes, size_t max_modes = 20 ); auto select_relocalization_candidate(const std::vector<RelocalizationICP_SE2::Candidate>& candidates, const CandidateSelectionParameters& params = {}); auto find_best_poses_se2(const mrpt::poses::CPosePDFGrid& grid, const double percentile = 0.99); std::string parse_yaml(const std::string& text, const YAMLParseOptions& opts = YAMLParseOptions()); mrpt::containers::yaml parse_yaml(const mrpt::containers::yaml& input, const YAMLParseOptions& opts = YAMLParseOptions()); mrpt::containers::yaml load_yaml_file(const std::string& fileName, const YAMLParseOptions& opts = YAMLParseOptions()); std::string yaml_to_string(const mrpt::containers::yaml& cfg); mrpt::poses::CPose3DPDFGaussianInf icp_prior_from_motion_model(const mrpt::poses::CPose3DPDFGaussianInf& motionModelPose); void set_icp_prior_mean( mrpt::poses::CPose3DPDFGaussianInf& prior, const mrpt::poses::CPose3D& newMean ); double imu_scan_release_time(double latestImuTime, double latestObsTime, double maxWaitTime); bool is_valid_keyframe_image_format(const std::string& format); std::string external_observation_file_name(const mrpt::obs::CObservation& obs, const std::string& ext); mrpt::obs::CObservationImage::Ptr external_image_copy( const mrpt::obs::CObservationImage& obs, const std::string& fileName ); template <std::size_t N, typename T> constexpr std::array<T, N> create_array(const T& value); void transform_to_new_map_frame( mrpt::poses::CPose3DInterpolator& trajectory, const mrpt::poses::CPose3D& b ); void transform_to_new_map_frame(mrpt::maps::CSimpleMap& sm, const mrpt::poses::CPose3D& b); void transform_to_new_map_frame(mp2p_icp::metric_map_t& m, const mrpt::poses::CPose3D& b); std::optional<mrpt::poses::CPose3D> pose_history_at( const std::map<double, mrpt::poses::CPose3D>& poses, double t, double maxEndGap ); bool pose_history_brackets(const std::map<double, mrpt::poses::CPose3D>& poses, double t); std::optional<mrpt::poses::CPose3D> pose_history_refreshed_at( const std::map<double, mrpt::poses::CPose3D>& poses, double t, const std::optional<mrpt::poses::CPose3D>& before, double maxEndGap ); mrpt::poses::CPose2D planar_motion( const mrpt::poses::CPose3D& from, const mrpt::poses::CPose3D& to ); std::optional<mrpt::Clock::time_point> keyframe_stamp(const mrpt::obs::CSensoryFrame& sf); std::size_t level_simplemap_keyframes( mrpt::maps::CSimpleMap& sm, const mrpt::poses::CPose3DInterpolator& before, const mrpt::poses::CPose3DInterpolator& after ); SMGeoReferencingOutput simplemap_georeference(const mrpt::maps::CSimpleMap& sm, const SMGeoReferencingParams& params = {}); mp2p_icp::metric_map_t::Georeferencing recenter_georeference(const mp2p_icp::metric_map_t::Georeferencing& in, const mrpt::math::TPoint3D& desiredEnuToMapTranslation); GNSSFrames extract_gnss_frames_from_sm( const mrpt::maps::CSimpleMap& sm, const std::optional<mrpt::topography::TGeodeticCoords>& refCoord = std::nullopt, unsigned int minimumFixQuality = 0 ); IMUFrames extract_imu_frames_from_sm(const mrpt::maps::CSimpleMap& sm); void add_imu_gravity_factors( gtsam::NonlinearFactorGraph& fg, gtsam::Values& v, const IMUFrames& imuFrames, const std::set<size_t>& existingPoseKeys, const AddIMUGravityFactorParams& params ); void add_imu_attitude_factors( gtsam::NonlinearFactorGraph& fg, gtsam::Values& v, const IMUFrames& imuFrames, const std::set<size_t>& existingPoseKeys, const AddIMUAttitudeFactorParams& params ); void add_gnss_factors( gtsam::NonlinearFactorGraph& fg, gtsam::Values& v, const GNSSFrames& frames, const AddGNSSFactorParams& params ); IMUAccFrames extract_imu_acc_frames_from_sm(const mrpt::maps::CSimpleMap& sm); } // namespace mola
Typedefs¶
typedef mrpt::poses::CPose3DInterpolator trajectory_t
We reuse mrpt::poses::CPose3DInterpolator as a time-indexed map of SE(3) poses
typedef std::size_t timestep_t
0-based indices of observations in a dataset
typedef mrpt::containers::yaml Yaml
Convenient typedef to save typing in the MOLA project.
typedef mp2p_icp::MatchingDistanceProfile MatchingDistanceProfile
Kept for code written against this alias.
Global Variables¶
constexpr unsigned int DEFAULT_MAX_PARALLEL_THREADS = 4
Upper limit of max_parallel_threads() when MOLA_MAX_THREADS is not set.
Global Functions¶
unsigned int physical_core_count()
Number of physical CPU cores this process may run on (its CPU affinity mask), counting the hardware threads of one core (SMT, Hyper-Threading) once. Where the CPU topology is unknown, the number of CPUs in the affinity mask, or std::thread::hardware_concurrency() without one. Always >= 1.
unsigned int max_parallel_threads()
Maximum number of threads that MOLA executables let the parallel algorithms (TBB) use: the environment variable MOLA_MAX_THREADS if it holds a positive integer, otherwise physical_core_count() but no more than DEFAULT_MAX_PARALLEL_THREADS.
LiDAR odometry runs many short parallel loops per scan, which do not scale much beyond a few threads, while the idle TBB workers spin waiting for the next one: each extra worker burns CPU that other processes need, for little gain in time per scan. The results do not depend on the number of threads.
SimplemapAttachResult simplemap_attach_observations( const std::string& inputFile, const std::string& outputFile, const OfflineDatasetSource& dataset, const SimplemapAttachOptions& options, const std::function<void(double)>& progress = {} )
Adds observations of dataset to the keyframes of the simplemap in inputFile, and saves it to outputFile (which may be the same file).
Each observation goes to the keyframe closest in time, within max_age, and each keyframe keeps the closest one per sensor label, so no observation is stored twice. Observations already in the map (same label and time) are not added again. Frames without sensor data (only the “metadata” comment of non-keyframes) get nothing. The keyframe time is that of its “metadata” comment, or else of its first observation.
External files of the input map (<input>_Images/) are hard-linked (or copied) into <output>_Images/ if that is another directory, so the output map is self-contained.
Parameters:
progress |
Optional, called with the fraction of the dataset read. |
std::exception |
On errors reading or writing files. |
template <class... Ts> overloaded(Ts...)
Based on https://en.cppreference.com/w/cpp/utility/variant/visit
void exportLoadableOptionsToIni( const mrpt::config::CLoadableOptions& opts, mrpt::config::CConfigFileBase& cfg, const std::string& section, const std::set<std::string>& excludeKeys = {} )
Dumps all parameters of opts (via its dumpToTextStream(), which all known CLoadableOptions implement) as key = value entries under section in cfg.
This indirect route (instead of calling saveToConfigFile() directly) is needed because several CLoadableOptions subclasses in this library (and in MRPT itself) only override dumpToTextStream(), not saveToConfigFile(), which would otherwise throw.
Any key listed in excludeKeys is skipped entirely (neither written nor overwritten), which is used to work around individual fields whose dumpToTextStream()/loadFromConfigFile() pair is known to be inconsistent in some MRPT classes (e.g. unit mismatches, or values that get truncated for display and can no longer be parsed back). Importing such a field then simply leaves it at whatever value it already had.
bool importLoadableOptionsFromIni( mrpt::config::CLoadableOptions& opts, const mrpt::config::CConfigFileBase& cfg, const std::string& section )
If section exists in cfg, calls opts.loadFromConfigFile() on it and returns true. Otherwise leaves opts untouched and returns false.
bool exportMapLayerOptionsToIni( mrpt::maps::CMetricMap& map, mrpt::config::CConfigFileBase& cfg, const std::string& layerName )
Exports all CLoadableOptions structures of map into cfg, one section per structure, named "<layerName>.<structName>". If map implements mola::OptionsCapable, the set of structures (and their names) is obtained generically via OptionsCapable::optionsByName() this covers all classes in this library, present and future, without needing per-class code here. Otherwise, a fallback handles basic mrpt::maps classes (CPointsMap and derivatives, COccupancyGridMap2D) via dynamic_cast.
Also writes a [<layerName>] section with a class key holding the MRPT RTTI class name, used by importMapLayerOptionsFromIni() as a sanity check.
Returns:
false if map is none of the known, supported classes (nothing is written).
bool importMapLayerOptionsFromIni( mrpt::maps::CMetricMap& map, const mrpt::config::CConfigFileBase& cfg, const std::string& layerName, std::vector<std::string>* appliedSections = nullptr, std::vector<std::string>* rejectedSections = nullptr )
The reverse of exportMapLayerOptionsToIni() : for each of map ‘s CLoadableOptions structures whose section is present in cfg, loads it from cfg into map.
Sections absent from cfg are silently skipped, leaving the corresponding options untouched. Names of the sections actually applied are appended to appliedSections, if provided.
The “creationOptions” structure (if present) is handled specially: instead of being overwritten directly, the new values are passed to OptionsCapable::trySetCreationOptions(), which may refuse to apply them (e.g. a voxel size change that would require discarding the map’s current contents). Section names refused this way are appended to rejectedSections, if provided, instead of appliedSections.
Returns:
false if map is none of the known, supported classes (nothing is read).
double imu_scan_release_time( double latestImuTime, double latestObsTime, double maxWaitTime )
Coverage time up to which waiting scans may be released.
Normally that is how far IMU data has been received, so a scan runs only once every sample it will consume exists. If the IMU stops, that time stops advancing and the scans behind it would wait for good, so the wait is bounded: maxWaitTime seconds after a scan’s coverage end has passed in sensor time, the scan is released with whatever IMU data did arrive.
Deliberately a function of timestamps only: using the wall clock here would make the released set depend on machine load, which is what the whole timestamp-driven synchronization exists to avoid.
Parameters:
latestImuTime |
Newest IMU timestamp received [s]. |
latestObsTime |
Newest timestamp received on any input [s], i.e. “now” in sensor time. |
maxWaitTime |
Bound on the wait [s]; 0 disables it (wait forever). |
bool is_valid_keyframe_image_format(const std::string& format)
Storage format of keyframe images: “jpg” or “png” files in the lazy-load directory of the simplemap, or “inline” (pixels inside the .simplemap).
std::string external_observation_file_name( const mrpt::obs::CObservation& obs, const std::string& ext )
File name for an externally stored observation: “<label>_<stamp>.<ext>”.
mrpt::obs::CObservationImage::Ptr external_image_copy( const mrpt::obs::CObservationImage& obs, const std::string& fileName )
A copy of obs whose image refers to fileName (lazy-load, relative to mrpt::io::getLazyLoadPathBase()) instead of holding the pixels. The file is not written here. obs is left untouched: CImage copies are shallow, so converting the image of an observation shared with other modules in place would change theirs too.
std::optional<mrpt::poses::CPose3D> pose_history_at( const std::map<double, mrpt::poses::CPose3D>& poses, double t, double maxEndGap )
Pose at time t [s] from a history of poses keyed by timestamp [s]: the stored one at an exact sample time, else the interpolation between the samples around t (linear for the position, SLERP for the attitude). A query at most maxEndGap past either end takes that end’s pose (e.g. a newest stamp slightly after the last reading). nullopt if the history is empty or does not cover t.
bool pose_history_brackets( const std::map<double, mrpt::poses::CPose3D>& poses, double t )
Whether the history brackets time t [s], i.e. a pose at t is exact or interpolated, not an end pose taken for a t just outside it (which later readings, even out of order, may still improve).
std::optional<mrpt::poses::CPose3D> pose_history_refreshed_at( const std::map<double, mrpt::poses::CPose3D>& poses, double t, const std::optional<mrpt::poses::CPose3D>& before, double maxEndGap )
The pose at time t [s] after some wait (e.g. a global search), given the one taken before it: the history’s current one if it brackets t (readings around t may have arrived meanwhile, also out of order), else the earlier one (the history may have dropped t meanwhile), else whatever the history gives now (see pose_history_at()).
mrpt::poses::CPose2D planar_motion( const mrpt::poses::CPose3D& from, const mrpt::poses::CPose3D& to )
Planar motion from from to to : that between their projections on the horizontal plane (x, y, yaw), in the frame of the first one. Unlike the projection of their 3D relative pose, a tilted vehicle does not stretch it.
std::optional<mrpt::Clock::time_point> keyframe_stamp(const mrpt::obs::CSensoryFrame& sf)
Stamp of a simplemap keyframe: its “metadata” observation, which carries the scan reference time the keyframe pose refers to (LidarOdometry), else its first observation with a valid stamp. sm-cli export-keyframes always takes the first observation (the scan’s own stamp), which may differ by up to one scan period.
std::size_t level_simplemap_keyframes( mrpt::maps::CSimpleMap& sm, const mrpt::poses::CPose3DInterpolator& before, const mrpt::poses::CPose3DInterpolator& after )
Moves every keyframe pose of sm by the correction a leveled path had at the keyframe’s stamp: after(t) * before(t)^-1, both interpolated, each held at its own ends. The keyframes and both paths must be in the same frame: the correction is a rotation about that frame’s axes. Keyframes without a stamp are left as they are. Pose covariances are rotated with the poses. Returns how many keyframes moved.
SMGeoReferencingOutput simplemap_georeference(const mrpt::maps::CSimpleMap& sm, const SMGeoReferencingParams& params = {})
Function to georeferencing a given SimpleMap with GNSS observations. A minimum of 3 (non-colinear) KFs with GNSS data are required to solve for the optimal transformation.
mp2p_icp::metric_map_t::Georeferencing recenter_georeference( const mp2p_icp::metric_map_t::Georeferencing& in, const mrpt::math::TPoint3D& desiredEnuToMapTranslation )
Re-datums a geo-referencing so that its T_enu_to_map has exactly the given translation, shifting the geodetic datum (geo_coord) accordingly so that the map <-> geodetic mapping is left completely unchanged. Since the local ENU axes rotate as the datum moves on the curved Earth, the rotation of T_enu_to_map is only approximately preserved (exactly so for small datum shifts); the 6D covariance is propagated accordingly, not just copied.
T_enu_to_map maps map coordinates into ENU ones, so the map origin ends up at the ENU coordinates desiredEnuToMapTranslation of the new datum (for {0,0,0}, the datum is the map origin).
This is useful to force the ENU origin to a chosen map location (e.g. the map origin, passing {0,0,0}) instead of the arbitrary first-GNSS position, which may be several meters from the map origin and make it awkward to pick an initial pose for localization.
Parameters:
in |
The input geo-referencing (datum + T_enu_to_map). |
desiredEnuToMapTranslation |
The desired translation of T_enu_to_map. |
Returns:
The re-datumed, geometrically-equivalent geo-referencing.
IMUFrames extract_imu_frames_from_sm(const mrpt::maps::CSimpleMap& sm)
Single pass over the simplemap collecting both gravity (accelerometer) and absolute-attitude (orientation) observations per keyframe.
void add_imu_gravity_factors( gtsam::NonlinearFactorGraph& fg, gtsam::Values& v, const IMUFrames& imuFrames, const std::set<size_t>& existingPoseKeys, const AddIMUGravityFactorParams& params )
Adds MeasuredGravityFactor factors to the graph. Creates new P(kf_index) variables for keyframes not already present in existingPoseKeys.
void add_imu_attitude_factors( gtsam::NonlinearFactorGraph& fg, gtsam::Values& v, const IMUFrames& imuFrames, const std::set<size_t>& existingPoseKeys, const AddIMUAttitudeFactorParams& params )
Adds Pose3RotationFactor factors to the graph. Creates new P(kf_index) variables for keyframes not already present in existingPoseKeys.
IMUAccFrames extract_imu_acc_frames_from_sm(const mrpt::maps::CSimpleMap& sm)
Deprecated Use extract_imu_frames_from_sm() instead, which also extracts absolute-attitude readings alongside gravity ones. This wrapper is kept for backward compatibility and simply forwards to it, returning only the gravity (accelerometer) subset.