MeshLib Documentation
Loading...
Searching...
No Matches
Global Registration

Example of Global Registration

▶ See it live in the browser

  • C++
    #include <MRMesh/MRBox.h>
    #include <iostream>
    void printStats( const MR::MultiwayICP& icp )
    {
    std::cout << "Samples: " << icp.getNumSamples() << std::endl
    << "Active point pairs: " << icp.getNumActivePairs() << std::endl;
    if ( icp.getNumActivePairs() > 0 )
    {
    const auto p2ptMetric = icp.getMeanSqDistToPoint();
    const auto p2plMetric = icp.getMeanSqDistToPlane();
    std::cout << "RMS point-to-point distance: " << p2ptMetric << " ± " << icp.getMeanSqDistToPoint( p2ptMetric ) << std::endl
    << "RMS point-to-plane distance: " << p2plMetric << " ± " << icp.getMeanSqDistToPlane( p2plMetric ) << std::endl;
    }
    }
    int main( int argc, char* argv[] )
    {
    if ( argc < 4 )
    {
    std::cerr << "Usage: " << argv[0] << " INPUT1 INPUT2 [INPUTS...] OUTPUT" << std::endl;
    return EXIT_FAILURE;
    }
    // the global registration can be applied to meshes and point clouds
    // to simplify the sample app, we will work with point clouds only
    std::vector<MR::PointCloud> inputs;
    inputs.reserve( argc - 2 ); // no reallocation, `objects` refer to the elements
    // as ICP and MultiwayICP classes accept both meshes and point clouds,
    // the input data must be converted to special wrapper objects
    // NB: the wrapper objects hold *references* to the source data, NOT their copies
    MR::ICPObjects objects;
    MR::Box3f maxBBox;
    for ( auto i = 1; i < argc - 1; ++i )
    {
    if ( !pointCloud )
    {
    std::cerr << "Failed to load point cloud: " << pointCloud.error() << std::endl;
    return EXIT_FAILURE;
    }
    auto bbox = pointCloud->computeBoundingBox();
    if ( !maxBBox.valid() || bbox.volume() > maxBBox.volume() )
    maxBBox = bbox;
    inputs.emplace_back( std::move( *pointCloud ) );
    // you may also set an affine transformation for each input as a second argument
    objects.push_back( { inputs.back(), {} } );
    }
    // you can set various parameters for the global registration; see the documentation for more info
    MR::MultiwayICP icp( objects, {
    // set sampling voxel size
    .samplingVoxelSize = maxBBox.diagonal() * 0.03f,
    } );
    icp.setParams( {} );
    // gather statistics
    icp.updateAllPointPairs();
    printStats( icp );
    std::cout << "Calculating transformations..." << std::endl;
    auto xfs = icp.calculateTransformations();
    printStats( icp );
    for ( auto i = MR::ObjId( 0 ); i < inputs.size(); ++i )
    {
    const auto& input = inputs[i];
    const auto& xf = xfs[i];
    for ( const auto& point : input.points )
    output.addPoint( xf( point ) );
    }
    auto res = MR::PointsSave::toAnySupportedFormat( output, argv[argc - 1] );
    if ( !res )
    {
    std::cerr << "Failed to save point cloud: " << res.error() << std::endl;
    return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
    }
    int main()
    Definition LaplacianDeformation.cpp:4
    const std::shared_ptr< const PointCloud > & pointCloud() const
    bool input(const char *label, T &v, const U &vMin=std::numeric_limits< U >::lowest(), const U &vMax=std::numeric_limits< U >::max(), UnitToStringParams< E > unitParams={}, ImGuiSliderFlags flags=defaultSliderFlags, const U &step=getDefaultStep< E, U, T >(false), const U &stepFast=getDefaultStep< E, U, T >(true))
    Vector< MeshOrPointsXf, ObjId > ICPObjects
    Expected< PointCloud > fromAnySupportedFormat(const std::filesystem::path &file, const PointsLoadSettings &settings={})
    Expected< void > toAnySupportedFormat(const PointCloud &points, const std::filesystem::path &file, const SaveSettings &settings={})
  • Python
    import meshlib.mrmeshpy as mrmeshpy
    import sys
    def print_stats(icp):
    num_active_pairs = icp.getNumActivePairs()
    print(f"Samples: {icp.getNumSamples()}")
    print(f"Active point pairs: {num_active_pairs}")
    if num_active_pairs > 0:
    p2pt_metric = icp.getMeanSqDistToPoint()
    p2pt_inaccuracy = icp.getMeanSqDistToPoint(p2pt_metric)
    print(f"RMS point-to-point distance: {p2pt_metric} ± {p2pt_inaccuracy}")
    p2pl_metric = icp.getMeanSqDistToPlane()
    p2pl_inaccuracy = icp.getMeanSqDistToPlane(p2pl_metric)
    print(f"RMS point-to-plane distance: {p2pl_metric} ± {p2pl_inaccuracy}")
    def main(argv):
    if len(argv) < 4:
    print(f"Usage for script: {argv[0]} INPUT1 INPUT2 [INPUTS...] OUTPUT")
    return
    file_args = argv[1:]
    # the global registration can be applied to meshes and point clouds
    # to simplify the sample app, we will work with point clouds only
    input_clouds_num = len(file_args) - 1
    inputs = []
    # as ICP and MultiwayICP classes accept both meshes and point clouds,
    # the input data must be converted to special wrapper objects
    # NB: the wrapper objects hold *references* to the source data, NOT their copies
    max_bbox = None
    for i in range(input_clouds_num):
    points = mrmeshpy.loadPoints(file_args[i])
    # you may also set an affine transformation for each input as a second argument
    inputs.append(mrmeshpy.MeshOrPointsXf(points, mrmeshpy.AffineXf3f()))
    bbox = points.getBoundingBox()
    if not max_bbox or bbox.volume() > max_bbox.volume():
    max_bbox = bbox
    # you can set various parameters for the global registration; see the documentation for more info
    sampling_params = mrmeshpy.MultiwayICPSamplingParameters()
    # set sampling voxel size
    sampling_params.samplingVoxelSize = max_bbox.diagonal() * 0.03
    icp = mrmeshpy.MultiwayICP(inputs, sampling_params)
    icp.setParams(mrmeshpy.ICPProperties())
    # gather statistics
    icp.updateAllPointPairs()
    print_stats(icp)
    print("Calculating transformations...")
    xfs = icp.calculateTransformations()
    print_stats(icp)
    output = mrmeshpy.PointCloud()
    for i in range(input_clouds_num):
    xf = xfs[mrmeshpy.ObjId(i)]
    for point in inputs[i].obj.points():
    output.addPoint(xf(point))
    mrmeshpy.PointsSave.toAnySupportedFormat(output, file_args[-1])
    main(sys.argv)
  • C
    #include <MRCMesh/MRAffineXf.h>
    #include <MRCMesh/MRBox.h>
    #include <MRCMesh/MRICP.h>
    #include <MRCMesh/MRMeshOrPoints.h>
    #include <MRCMesh/MRMultiwayICP.h>
    #include <MRCMesh/MRPointCloud.h>
    #include <MRCMesh/MRPointCloudPart.h>
    #include <MRCMesh/MRPointsLoad.h>
    #include <MRCMesh/MRPointsSave.h>
    #include <MRCMesh/MRString.h>
    #include <MRCMesh/MRVector.h>
    #include <MRCMisc/expected_MR_PointCloud_std_string.h>
    #include <MRCMisc/expected_void_std_string.h>
    #include <MRCMisc/std_string.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    void printStats( const MR_MultiwayICP* icp )
    {
    size_t numSamples = MR_MultiwayICP_getNumSamples( icp );
    size_t numActivePairs = MR_MultiwayICP_getNumActivePairs( icp );
    printf( "Samples: %zu\n", numSamples );
    printf( "Active point pairs: %zu\n", numActivePairs );
    if ( numActivePairs > 0 )
    {
    double p2ptMetric = MR_MultiwayICP_getMeanSqDistToPoint( icp, NULL );
    double p2ptInaccuracy = MR_MultiwayICP_getMeanSqDistToPoint( icp, &p2ptMetric );
    printf( "RMS point-to-point distance: %g ± %g\n", p2ptMetric, p2ptInaccuracy );
    double p2plMetric = MR_MultiwayICP_getMeanSqDistToPlane( icp, NULL );
    double p2plInaccuracy = MR_MultiwayICP_getMeanSqDistToPlane( icp, &p2plMetric );
    printf( "RMS point-to-plane distance: %g ± %g\n", p2plMetric, p2plInaccuracy );
    }
    }
    int main( int argc, char* argv[] )
    {
    int rc = EXIT_FAILURE;
    if ( argc < 4 )
    {
    fprintf( stderr, "Usage: %s INPUT1 INPUT2 [INPUTS...] OUTPUT\n", argv[0] );
    goto out;
    }
    // the global registration can be applied to meshes and point clouds
    // to simplify the sample app, we will work with point clouds only
    // Note that the default ICP method (point-to-plane) relies on the point cloud having the normals information, and will not work otherwise.
    // If your point cloud doesn't have normals, switch to the point-to-point method by calling `MR_ICPProperties_Set_method( params, MR_ICPMethod_PointToPoint );`.
    const int inputNum = argc - 2;
    // as ICP and MultiwayICP classes accept both meshes and point clouds,
    // the input data must be converted to special wrapper objects
    // NB: The wrapper is non-owning, it holds a reference to an existing mesh or point cloud and doesn't automatically destroy it when the wrapper is destroyed.
    // So we manually destroy the wrapped contents before destroying the wrappers.
    MR_Vector_MR_MeshOrPointsXf_MR_ObjId* inputs = MR_Vector_MR_MeshOrPointsXf_MR_ObjId_DefaultConstruct();
    MR_Box3f maxBBox = MR_Box3f_DefaultConstruct();
    for ( int i = 0; i < inputNum; ++i )
    {
    MR_expected_MR_PointCloud_std_string* pointCloudEx = MR_PointsLoad_fromAnySupportedFormat( argv[1 + i], NULL, NULL );
    MR_PointCloud* pointCloud = MR_expected_MR_PointCloud_std_string_value_mut( pointCloudEx );
    if ( !pointCloud )
    {
    // Failed to load.
    fprintf( stderr, "Failed to load point cloud: %s\n", MR_std_string_data( MR_expected_MR_PointCloud_std_string_error( pointCloudEx ) ) );
    MR_expected_MR_PointCloud_std_string_Destroy( pointCloudEx );
    goto out_inputs;
    }
    // Construct the wrapper.
    MR_MeshOrPoints* mop = MR_MeshOrPoints_Construct_MR_PointCloud( pointCloud ); // Or `MR_MeshOrPoints_Construct_MR_Mesh()` for meshes.
    MR_MeshOrPointsXf* mopXf = MR_MeshOrPointsXf_ConstructFrom( mop, MR_AffineXf3f_DefaultConstruct() ); // Here you can optionally specify an affine transformation.
    MR_MeshOrPoints_Destroy( mop );
    // Insert the wrapper into the vector.
    MR_Vector_MR_MeshOrPointsXf_MR_ObjId_push_back_MR_MeshOrPointsXf_rvalue_ref( inputs, mopXf );
    MR_MeshOrPointsXf_Destroy( mopXf );
    MR_Box3f bbox = MR_PointCloud_computeBoundingBox( pointCloud, NULL );
    if ( !MR_Box3f_valid( &maxBBox ) || MR_Box3f_volume( &bbox ) > MR_Box3f_volume( &maxBBox ) )
    maxBBox = bbox;
    }
    // you can set various parameters for the global registration; see the documentation for more info
    MR_MultiwayICPSamplingParameters* samplingParams = MR_MultiwayICPSamplingParameters_DefaultConstruct();
    // set sampling voxel size
    MR_MultiwayICPSamplingParameters_Set_samplingVoxelSize( samplingParams, MR_Box3f_diagonal( &maxBBox ) * 0.03f );
    MR_MultiwayICP* icp = MR_MultiwayICP_Construct( inputs, samplingParams );
    MR_MultiwayICPSamplingParameters_Destroy( samplingParams );
    MR_ICPProperties* params = MR_ICPProperties_DefaultConstruct();
    MR_MultiwayICP_setParams( icp, params );
    MR_ICPProperties_Destroy( params );
    // gather statistics
    MR_MultiwayICP_updateAllPointPairs( icp, NULL );
    printStats( icp );
    printf( "Calculating transformations...\n" );
    MR_Vector_MR_AffineXf3f_MR_ObjId* xfs = MR_MultiwayICP_calculateTransformations( icp, NULL );
    printStats( icp );
    MR_PointCloud* output = MR_PointCloud_DefaultConstruct();
    for ( int i = 0; i < inputNum; i++ )
    {
    const MR_MeshOrPointsXf* input = MR_Vector_MR_MeshOrPointsXf_MR_ObjId_index( inputs, (MR_ObjId){i} );
    const MR_AffineXf3f* xf = MR_Vector_MR_AffineXf3f_MR_ObjId_index( xfs, (MR_ObjId){i} );
    const MR_PointCloud* cloud = MR_PointCloudPart_Get_cloud( MR_MeshOrPoints_asPointCloudPart( MR_MeshOrPointsXf_Get_obj( input ) ) );
    const MR_VertCoords* points = MR_PointCloud_Get_points( cloud );
    size_t numPoints = MR_VertCoords_size( points );
    for ( size_t j = 0; j < numPoints; j++ )
    {
    MR_Vector3f point = *MR_VertCoords_index( points, (MR_VertId){(int)j} );
    point = MR_AffineXf3f_call( xf, &point );
    MR_PointCloud_addPoint( output, &point );
    }
    }
    MR_expected_void_std_string* saveEx = MR_PointsSave_toAnySupportedFormat( output, argv[argc - 1], NULL, NULL );
    const MR_std_string* saveError = MR_expected_void_std_string_error( saveEx );
    if ( !saveError )
    rc = EXIT_SUCCESS;
    else
    fprintf( stderr, "Failed to save point cloud: %s\n", MR_std_string_data( saveError ) );
    MR_expected_void_std_string_Destroy( saveEx );
    MR_PointCloud_Destroy( output );
    MR_Vector_MR_AffineXf3f_MR_ObjId_Destroy( xfs );
    MR_MultiwayICP_Destroy( icp );
    out_inputs: ;
    // As explained earlier, since those wrappers are non-owning, we have to manually destroy the contents.
    size_t numLoadedInputs = MR_Vector_MR_MeshOrPointsXf_MR_ObjId_size( inputs );
    for ( size_t i = 0; i < numLoadedInputs; i++ )
    {
    MR_PointCloud_Destroy( MR_PointCloudPart_Get_cloud( MR_MeshOrPoints_asPointCloudPart( MR_MeshOrPointsXf_Get_obj( MR_Vector_MR_MeshOrPointsXf_MR_ObjId_index( inputs, (MR_ObjId){(int)i} ) ) ) ) );
    }
    MR_Vector_MR_MeshOrPointsXf_MR_ObjId_Destroy( inputs );
    out:
    return rc;
    }
    const UiRenderParams * params
    VertCoords & points() const
  • C#
    public static class GlobalRegistrationExample
    {
    static void PrintStats(MR.MultiwayICP icp)
    {
    Console.WriteLine("Samples: {0}", icp.getNumSamples());
    Console.WriteLine("Active point pairs: {0}", icp.getNumActivePairs());
    if (icp.getNumActivePairs() > 0)
    {
    float p2ptMetric = icp.getMeanSqDistToPoint();
    float p2plMetric = icp.getMeanSqDistToPlane();
    Console.WriteLine("RMS point-to-point distance: {0} ± {1}", p2ptMetric, icp.getMeanSqDistToPoint(p2ptMetric));
    Console.WriteLine("RMS point-to-plane distance: {0} ± {1}", p2plMetric, icp.getMeanSqDistToPlane(p2plMetric));
    }
    }
    public static void Main(string[] args)
    {
    if (args.Length < 3)
    {
    Console.Error.WriteLine("Usage: GlobalRegistration INPUT1 INPUT2 [INPUTS...] OUTPUT");
    Environment.Exit(1);
    }
    // the global registration can be applied to meshes and point clouds
    // to simplify the sample app, we will work with point clouds only
    List<MR.PointCloud> inputs = new();
    // as ICP and MultiwayICP classes accept both meshes and point clouds,
    // the input data must be converted to special wrapper objects
    // NB: the wrapper objects hold *references* to the source data, NOT their copies
    MR.Vector_MRMeshOrPointsXf_MRObjId objects = new();
    MR.Box3f maxBBox = new();
    for (int i = 0; i < args.Length - 1; ++i)
    {
    var pointCloud = MR.PointsLoad.fromAnySupportedFormat(args[i]);
    var bbox = pointCloud.computeBoundingBox();
    if (!maxBBox.valid() || bbox.volume() > maxBBox.volume())
    maxBBox = bbox;
    inputs.Add(pointCloud);
    // you may also set an affine transformation for each input as a second argument
    objects.pushBack(new MR.MeshOrPointsXf(pointCloud, new MR.AffineXf3f()));
    }
    // you can set various parameters for the global registration; see the documentation for more info
    MR.MultiwayICPSamplingParameters samplingParams = new();
    // set sampling voxel size
    samplingParams.samplingVoxelSize = maxBBox.diagonal() * 0.03f;
    MR.MultiwayICP icp = new(objects, samplingParams);
    icp.setParams(new MR.ICPProperties());
    // gather statistics
    icp.updateAllPointPairs();
    PrintStats(icp);
    Console.WriteLine("Calculating transformations...");
    var xfs = icp.calculateTransformations();
    PrintStats(icp);
    MR.PointCloud output = new();
    for (int i = 0; i < inputs.Count; ++i)
    {
    var points = inputs[i].points;
    var xf = xfs[new MR.ObjId(i)];
    for (int v = 0; v < (int)points.size(); ++v)
    output.addPoint(xf.call(points[new MR.VertId(v)]));
    }
    MR.PointsSave.toAnySupportedFormat(output, args[args.Length - 1]);
    }
    }
  • JavaScript
    import createMeshLib from '@meshinspector/meshlib';
    const ml = await createMeshLib();
    // the global registration can be applied to meshes and point clouds;
    // to keep the sample simple, we work with point clouds only
    const inputPaths = ['cloud1.ply', 'cloud2.ply', 'cloud3.ply'];
    const outputPath = 'registered.ply';
    // a DisposableStack frees the per-input WASM handles (there is a variable number of them) at the
    // end of the scope, in reverse order, the same way `using` frees a single handle
    using stack = new DisposableStack();
    // as ICP and MultiwayICP accept both meshes and point clouds, each input is wrapped in a
    // MeshOrPointsXf; the wrapper references the source cloud, so the clouds must outlive it (the
    // stack, declared first, is disposed last)
    using identityXf = new ml.AffineXf3f();
    const inputs = [];
    const objects = [];
    let maxVolume = -Infinity;
    let baseDiagonal = 0;
    for (const path of inputPaths) {
    const cloud = stack.use(ml.PointsLoad.fromAnySupportedFormat(path));
    inputs.push(cloud);
    using bbox = cloud.computeBoundingBox();
    const volume = bbox.volume();
    if (volume > maxVolume) {
    maxVolume = volume;
    baseDiagonal = bbox.diagonal();
    }
    const mop = stack.use(ml.MeshOrPoints.fromPoints(cloud));
    objects.push(stack.use(new ml.MeshOrPointsXf(mop, identityXf)));
    }
    // set the sampling voxel size relative to the largest input
    using samplingParams = new ml.MultiwayICPSamplingParameters();
    samplingParams.samplingVoxelSize = baseDiagonal * 0.03;
    using icp = new ml.MultiwayICP(objects, samplingParams);
    using icpProps = new ml.ICPProperties();
    icp.setParams(icpProps);
    // gather statistics
    icp.updateAllPointPairs();
    console.log(`Samples: ${icp.getNumSamples()}`);
    console.log(`Active point pairs: ${icp.getNumActivePairs()}`);
    // one transformation per input object
    const xfs = icp.calculateTransformations();
    // apply each transformation to its cloud and merge everything into one output cloud
    using output = new ml.PointCloud();
    for (let i = 0; i < inputs.length; ++i) {
    using xf = xfs[i];
    using srcPoints = inputs[i].points;
    const coords = srcPoints.toArray();
    for (let p = 0; p < coords.length; p += 3)
    output.addPoint(xf.apply({ x: coords[p], y: coords[p + 1], z: coords[p + 2] }));
    }
    ml.PointsSave.toAnySupportedFormat(output, outputPath);
    Note
    The using declaration requires Node.js 24+ or a modern browser. On older runtimes, call .delete() on each object instead (see Memory Management in the JavaScript Setup Guide).
  • Rust
    use meshlib::{AffineXf3f, Box3f, ICPProperties, MeshOrPoints, MeshOrPointsXf, MultiwayICP, MultiwayICPSamplingParameters, ObjId, PointCloud};
    fn print_stats(icp: &MultiwayICP)
    {
    println!("Samples: {}", icp.get_num_samples());
    println!("Active point pairs: {}", icp.get_num_active_pairs());
    if icp.get_num_active_pairs() > 0
    {
    let p2pt_metric = icp.get_mean_sq_dist_to_point(None);
    let p2pl_metric = icp.get_mean_sq_dist_to_plane(None);
    println!("RMS point-to-point distance: {} ± {}", p2pt_metric, icp.get_mean_sq_dist_to_point(Some(p2pt_metric as f64)));
    println!("RMS point-to-plane distance: {} ± {}", p2pl_metric, icp.get_mean_sq_dist_to_plane(Some(p2pl_metric as f64)));
    }
    }
    fn main() -> Result<(), String>
    {
    let args: Vec<String> = std::env::args().collect();
    if args.len() < 4
    {
    return Err(format!("Usage: {} INPUT1 INPUT2 [INPUTS...] OUTPUT", args[0]));
    }
    // the global registration can be applied to meshes and point clouds
    // to simplify the sample app, we will work with point clouds only
    let mut inputs = Vec::new();
    // as ICP and MultiwayICP classes accept both meshes and point clouds,
    // the input data must be converted to special wrapper objects
    // NB: the wrapper objects hold *references* to the source data, NOT their copies
    let mut objects = meshlib::Vector_MR_MeshOrPointsXf_MR_ObjId::new();
    let mut max_bbox = Box3f::new();
    for input_path in &args[1..args.len() - 1]
    {
    let point_cloud = meshlib::points_load::from_any_supported_format(input_path, None).into_result().map_err(|error| format!("Failed to load point cloud: {error}"))?;
    let bbox = point_cloud.compute_bounding_box(None);
    if !max_bbox.valid() || bbox.volume() > max_bbox.volume()
    {
    max_bbox = bbox;
    }
    // you may also set an affine transformation for each input as a second argument
    objects.push_back_const_mr_mesh_or_points_xf_ref(&MeshOrPointsXf::construct_from(&MeshOrPoints::construct_mr_point_cloud(&point_cloud), AffineXf3f::new()));
    inputs.push(point_cloud);
    }
    // you can set various parameters for the global registration; see the documentation for more info
    let mut sampling_params = MultiwayICPSamplingParameters::new();
    // set sampling voxel size
    sampling_params.set_sampling_voxel_size(max_bbox.diagonal() * 0.03);
    let mut icp = MultiwayICP::construct(&objects, &sampling_params);
    icp.set_params(&ICPProperties::new());
    // gather statistics
    icp.update_all_point_pairs(None);
    print_stats(&icp);
    println!("Calculating transformations...");
    let xfs = icp.calculate_transformations(None);
    print_stats(&icp);
    let mut output = PointCloud::new();
    for (i, input) in inputs.iter().enumerate()
    {
    let xf = xfs.index(ObjId {id_: i as i32});
    let points = input.points();
    for j in 0..points.size()
    {
    output.add_point(&xf.call(points.index(meshlib::VertId {id_: j as i32})));
    }
    }
    meshlib::points_save::to_any_supported_format(&output, &args[args.len() - 1], None).into_result().map_err(|error| format!("Failed to save point cloud: {error}"))?;
    Ok(())
    }
  • Java
    import java.util.ArrayList;
    import meshlib.AffineXf3f;
    import meshlib.Box3f;
    import meshlib.ICPProperties;
    import meshlib.MeshOrPoints;
    import meshlib.MeshOrPointsXf;
    import meshlib.MultiwayICP;
    import meshlib.MultiwayICPSamplingParameters;
    import meshlib.ObjId;
    import meshlib.PointCloud;
    import meshlib.Vector_MR_AffineXf3f_MR_ObjId;
    import meshlib.Vector_MR_MeshOrPointsXf_MR_ObjId;
    import meshlib.VertCoords;
    import meshlib.VertId;
    // The class isn't public because of the `.dox.java` file name, the launcher doesn't mind.
    class GlobalRegistration
    {
    static void printStats(MultiwayICP icp)
    {
    System.out.println("Samples: " + icp.getNumSamples());
    System.out.println("Active point pairs: " + icp.getNumActivePairs());
    if (icp.getNumActivePairs() > 0)
    {
    float p2ptMetric = icp.getMeanSqDistToPoint(null);
    float p2plMetric = icp.getMeanSqDistToPlane(null);
    System.out.println("RMS point-to-point distance: " + p2ptMetric + " ± " + icp.getMeanSqDistToPoint((double)p2ptMetric));
    System.out.println("RMS point-to-plane distance: " + p2plMetric + " ± " + icp.getMeanSqDistToPlane((double)p2plMetric));
    }
    }
    public static void main(String[] args)
    {
    if (args.length < 3)
    {
    System.err.println("Usage: GlobalRegistration INPUT1 INPUT2 [INPUTS...] OUTPUT");
    System.exit(1);
    }
    // the global registration can be applied to meshes and point clouds
    // to simplify the sample app, we will work with point clouds only
    ArrayList<PointCloud> inputs = new ArrayList<>();
    // as ICP and MultiwayICP classes accept both meshes and point clouds,
    // the input data must be converted to special wrapper objects
    // NB: the wrapper objects hold *references* to the source data, NOT their copies
    Vector_MR_MeshOrPointsXf_MR_ObjId objects = new Vector_MR_MeshOrPointsXf_MR_ObjId();
    Box3f maxBBox = new Box3f();
    for (int i = 0; i < args.length - 1; i++)
    {
    // An error is thrown as `UnexpectedResultException`.
    PointCloud pointCloud = meshlib.pointsload.Functions.fromAnySupportedFormat(args[i], null);
    Box3f bbox = pointCloud.computeBoundingBox(null);
    if (!maxBBox.valid() || bbox.volume() > maxBBox.volume())
    maxBBox = bbox;
    inputs.add(pointCloud);
    // you may also set an affine transformation for each input as a second argument
    objects.push_back_const_MR_MeshOrPointsXf_ref(new MeshOrPointsXf(new MeshOrPoints(pointCloud), new AffineXf3f()));
    }
    // you can set various parameters for the global registration; see the documentation for more info
    MultiwayICPSamplingParameters samplingParams = new MultiwayICPSamplingParameters();
    // set sampling voxel size
    samplingParams.setSamplingVoxelSize(maxBBox.diagonal() * 0.03f);
    MultiwayICP icp = new MultiwayICP(objects, samplingParams);
    icp.setParams(new ICPProperties());
    // gather statistics
    icp.updateAllPointPairs(null);
    printStats(icp);
    System.out.println("Calculating transformations...");
    Vector_MR_AffineXf3f_MR_ObjId xfs = icp.calculateTransformations(null);
    printStats(icp);
    PointCloud output = new PointCloud();
    for (int i = 0; i < inputs.size(); i++)
    {
    VertCoords points = inputs.get(i).points();
    AffineXf3f xf = xfs.index(new ObjId(i));
    for (int v = 0; v < points.size(); v++)
    output.addPoint(xf.call(points.index(new VertId(v))));
    }
    // An error is thrown as `UnexpectedResultException`.
    meshlib.pointssave.Functions.toAnySupportedFormat(output, args[args.length - 1], null);
    }
    }
    MultiwayICP(const ICPObjects &objects, const MultiwayICPSamplingParameters &samplingParams)
    MeshOrPoints(const MeshPart &mp)