text:
/* Copyright 2003-2013 Joaquin M Lopez Munoz.
 * Distributed under the Boost Software License, Version 1.0.
 * (See accompanying file LICENSE_1_0.txt or copy at
 * http://www.boost.org/LICENSE_1_0.txt)
 *
 * See http://www.boost.org/libs/multi_index for library home page.
 */

#ifndef BOOST_MULTI_INDEX_ORDERED_INDEX_FWD_HPP
#define BOOST_MULTI_INDEX_ORDERED_INDEX_FWD_HPP

#if defined(_MSC_VER)
#pragma once
#endif

#include <boost/multi_index/detail/ord_index_args.hpp>

namespace boost{

namespace multi_index{

namespace detail{

template<
  typename KeyFromValue,typename Compare,
  typename SuperMeta,typename TagList,typename Category
>
class ordered_index;

template<
  typename KeyFromValue1,typename Compare1,
  typename SuperMeta1,typename TagList1,typename Category1,
  typename KeyFromValue2,typename Compare2,
  typename SuperMeta2,typename TagList2,typename Category2
>
bool operator==(
  const ordered_index<
    KeyFromValue1,Compare1,SuperMeta1,TagList1,Category1>& x,
  const ordered_index<
    KeyFromValue2,Compare2,SuperMeta2,TagList2,Category2>& y);

template<
  typename KeyFromValue1,typename Compare1,
  typename SuperMeta1,typename TagList1,typename Category1,
  typename KeyFromValue2,typename Compare2,
  typename SuperMeta2,typename TagList2,typename Category2
>
bool operator<(
  const ordered_index<
    KeyFromValue1,Compare1,SuperMeta1,TagList1,Category1>& x,
  const ordered_index<
    KeyFromValue2,Compare2,SuperMeta2,TagList2,Category2>& y);

template<
  typename KeyFromValue1,typename Compare1,
  typename SuperMeta1,typename TagList1,typename Category1,
  typename KeyFromValue2,typename Compare2,
  typename SuperMeta2,typename TagList2,typename Category2
>
bool operator!=(
  const ordered_index<
    KeyFromValue1,Compare1,SuperMeta1,TagList1,Category1>& x,
  const ordered_index<
    KeyFromValue2,Compare2,SuperMeta2,TagList2,Category2>& y);

template<
  typename KeyFromValue1,typename Compare1,
  typename SuperMeta1,typename TagList1,typename Category1,
  typename KeyFromValue2,typename Compare2,
  typename SuperMeta2,typename TagList2,typename Category2
>
bool operator>(
  const ordered_index<
    KeyFromValue1,Compare1,SuperMeta1,TagList1,Category1>& x,
  const ordered_index<
    KeyFromValue2,Compare2,SuperMeta2,TagList2,Category2>& y);

template<
  typename KeyFromValue1,typename Compare1,
  typename SuperMeta1,typename TagList1,typename Category1,
  typename KeyFromValue2,typename Compare2,
  typename SuperMeta2,typename TagList2,typename Category2
>
bool operator>=(
  const ordered_index<
    KeyFromValue1,Compare1,SuperMeta1,TagList1,Category1>& x,
  const ordered_index<
    KeyFromValue2,Compare2,SuperMeta2,TagList2,Category2>& y);

template<
  typename KeyFromValue1,typename Compare1,
  typename SuperMeta1,typename TagList1,typename Category1,
  typename KeyFromValue2,typename Compare2,
  typename SuperMeta2,typename TagList2,typename Category2
>
bool operator<=(
  const ordered_index<
    KeyFromValue1,Compare1,SuperMeta1,TagList1,Category1>& x,
  const ordered_index<
    KeyFromValue2,Compare2,SuperMeta2,TagList2,Category2>& y);

template<
  typename KeyFromValue,typename Compare,
  typename SuperMeta,typename TagList,typename Category
>
void swap(
  ordered_index<KeyFromValue,Compare,SuperMeta,TagList,Category>& x,
  ordered_index<KeyFromValue,Compare,SuperMeta,TagList,Category>& y);

} /* namespace multi_index::detail */

/* ordered_index specifiers */

template<typename Arg1,typename Arg2=mpl::na,typename Arg3=mpl::na>
struct ordered_unique;

template<typename Arg1,typename Arg2=mpl::na,typename Arg3=mpl::na>
struct ordered_non_unique;

} /* namespace multi_index */

} /* namespace boost */

#endif

max_stars_repo_name: multi-os-engine/cinder-natj-binding

max_issues_repo_name: wujf/mongo

max_forks_repo_name: wujf/mongo


text:
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

#ifndef quantext_autolink_hpp
#define quantext_autolink_hpp

#include <boost/config.hpp>

// select toolset:
#if (_MSC_VER < 1310)
#error "unsupported Microsoft compiler"
#elif(_MSC_VER == 1310)
#define QE_LIB_TOOLSET "vc71"
#elif(_MSC_VER == 1400)
#define QE_LIB_TOOLSET "vc80"
#elif(_MSC_VER == 1500)
#ifdef x64
#define QE_LIB_TOOLSET "vc90-x64"
#else
#define QE_LIB_TOOLSET "vc90"
#endif
#elif(_MSC_VER == 1600)
#define QE_LIB_TOOLSET "vc100"
#elif(_MSC_VER == 1700)
#define QE_LIB_TOOLSET "vc110"
#elif(_MSC_VER == 1800)
#define QE_LIB_TOOLSET "vc120"
#elif(_MSC_VER == 1900)
#define QE_LIB_TOOLSET "vc140"
#else
#define QE_LIB_TOOLSET "vc141"
#endif

#ifdef _M_X64
#define QE_LIB_PLATFORM "-x64"
#else
#define QE_LIB_PLATFORM
#endif

/*** libraries to be linked ***/

// select thread opt:
#ifdef _MT
#define QE_LIB_THREAD_OPT "-mt"
#else
#define QE_LIB_THREAD_OPT
#endif

// select linkage opt:
#ifdef _DLL
#if defined(_DEBUG)
#define QE_LIB_RT_OPT "-gd"
#else
#define QE_LIB_RT_OPT
#endif
#else
#if defined(_DEBUG)
#define QE_LIB_RT_OPT "-sgd"
#else
#define QE_LIB_RT_OPT "-s"
#endif
#endif

#define QE_LIB_NAME "QuantExt-" QE_LIB_TOOLSET QE_LIB_PLATFORM QE_LIB_THREAD_OPT QE_LIB_RT_OPT ".lib"

#pragma comment(lib, QE_LIB_NAME)
#ifdef BOOST_LIB_DIAGNOSTIC
#pragma message("Will (need to) link to lib file: " QE_LIB_NAME)
#endif

#endif

ext: hpp

max_stars_repo_name: paul-giltinan/Engine

max_issues_repo_name: paul-giltinan/Engine

max_forks_repo_name: paul-giltinan/Engine


text:
/**
 * Copyright (c) 2018, University Osnabrück
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the University Osnabrück nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL University Osnabrück BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * UosIO.tcc
 *
 *  @date 11.05.2011
 *  @author Thomas Wiemann
 */

#include <lvr2/io/UosIO.hpp>

#include <list>
#include <vector>
#include <string>
#include <iomanip>
#include <iostream>
#include <cmath>
#include <fstream>
#include <sstream>

using std::list;
using std::vector;
using std::ifstream;
using std::stringstream;

#include <boost/filesystem.hpp>
//using namespace boost::filesystem;

#include <lvr2/io/Progress.hpp>
#include <lvr2/io/Timestamp.hpp>

namespace lvr2
{

ModelPtr UosIO::read(string dir)
{
    ModelPtr model;

    size_t n = 0;
    boost::filesystem::path directory(dir);
    if(is_directory(directory))
    {
        // Iterate through directory, count relevant objects
        int n3dFiles = 0;

        // First and last scan to load
        int firstScan = -1;
        int lastScan =  -1;

        boost::filesystem::directory_iterator lastFile;

        // First, look for .3d files
        for(boost::filesystem::directory_iterator it(directory); it != lastFile; it++ )
        {
            boost::filesystem::path p = it->path();
            if(p.extension().string() == ".3d")
            {
                // Check for naming convention "scanxxx.3d"
                int num = 0;
                if(sscanf(p.filename().string().c_str(), "scan%3d", &num))
                {
                    n3dFiles++;
                    if(firstScan == -1) firstScan = num;
                    if(lastScan == -1) lastScan = num;

                    if(num > lastScan) lastScan = num;
                    if(num < firstScan) firstScan = num;
                }
            }
        }

        // Check if given directory contains scans in new format.
        // If so, read them and return result. Otherwise try to
        // read new format.
        if(n3dFiles > 0)
        {
            // Check for user scan ranges
            if(m_firstScan > -1 && m_firstScan <= lastScan)
            {
                firstScan = m_firstScan;
            }

            if(m_lastScan >= -1 && m_lastScan <= lastScan && m_lastScan >= firstScan)
            {
                lastScan = m_lastScan;
            }

            m_firstScan = firstScan;
            m_lastScan = lastScan;

            cout << timestamp << "Reading " << n3dFiles << " scans in UOS format "
                << "(From " << firstScan << " to " << lastScan << ")." << endl;
            readNewFormat(model, dir, firstScan, lastScan, n);
        }
        else
        {
            // Count numbered sub directories, ignore others
            int nDirs = 0;
            for(boost::filesystem::directory_iterator it(directory); it != lastFile; it++ )
            {
                boost::filesystem::path p = it->path();
                int num = 0;

                // Only count numbered dirs
                if(sscanf(p.filename().string().c_str(), "%d", &num))
                {
                    if(firstScan == -1) firstScan = num;
                    if(lastScan == -1) lastScan = num;

                    if(num > lastScan) lastScan = num;
                    if(num < firstScan) firstScan = num;

                    nDirs++;
                }
            }

            // Check is dirs were found and try to read old format
            if(nDirs)
            {
                // Check for user scan ranges
                if(m_firstScan > -1 && m_firstScan <= lastScan)
                {
                    firstScan = m_firstScan;
                }

                if(m_lastScan >= -1 && m_lastScan <= lastScan && m_lastScan >= firstScan)
                {
                    lastScan = m_lastScan;
                }

                m_firstScan = firstScan;
                m_lastScan = lastScan;

                cout << timestamp << "Reading " << nDirs << " scans in old UOS format "
                    << "(From " << firstScan << " to " << lastScan << ")." << endl;
                readOldFormat(model, dir, firstScan, lastScan, n);
            }
            else
            {
                return ModelPtr();
            }
        }

    }
    else
    {
        cout << timestamp << "UOSReader: " << dir << " is not a directory." << endl;
    }

    m_model = model;
    return model;
}

void UosIO::reduce(string dir, string target, int reduction)
{
    // Open output stream
    m_outputFile.open(target.c_str());
    if(!m_outputFile.good())
    {
        cout << timestamp << "UOSReader: " << dir << " unable to open " << target << " for writing." << endl;
        return;
    }

    // Set needed flags for inout code
    m_reductionTarget = reduction;
    m_saveToDisk = true;

    // Read data and write reduced points
    ModelPtr m = read(dir);

}

void UosIO::readNewFormat(ModelPtr &model, string dir, int first, int last, size_t &n)
{
    list<Vec > allPoints;
    list<BaseVector<int> > allColors;

    size_t point_counter = 0;

    vector<indexPair> sub_clouds;

    // Count points in all given files
    size_t numPointsTotal = 0;
    for(int fileCounter = first; fileCounter <= last; fileCounter++)
    {
        // Create scan file name
        boost::filesystem::path scan_path(
                boost::filesystem::path(dir) /
                boost::filesystem::path( "scan" + to_string( fileCounter, 3 ) + ".3d" ) );
        string scanFileName = "/" + scan_path.relative_path().string();

        // Count lines in scan
        numPointsTotal += AsciiIO::countLines(scanFileName);
    }

    // Calculate the number of points to skip when writing to disk
    size_t skipPoints = 1;

    if(m_reductionTarget > 1)
    {
        skipPoints = (int)numPointsTotal / m_reductionTarget;
    }

    if(m_saveToDisk)
    {
        cout << timestamp << "Reduction mode. Writing every " << skipPoints << "th point." << endl;
    }

    for(int fileCounter = first; fileCounter <= last; fileCounter++)
    {
        // New (unit) transformation matrix
        Matrix4<Vec> tf;

        // Input file streams for scan data, poses and frames
        ifstream scan_in, pose_in, frame_in;

        // Create scan file name
        boost::filesystem::path scan_path(
                boost::filesystem::path(dir) /
                boost::filesystem::path( "scan" + to_string( fileCounter, 3 ) + ".3d" ) );
        string scanFileName = scan_path.string();

        // Count lines in scan
        size_t points_in_file = AsciiIO::countLines(scanFileName);

        int num_attributes = AsciiIO::getEntriesInLine(scanFileName) - 3;
        bool has_color = (num_attributes == 3) || (num_attributes == 4);
        bool has_intensity = (num_attributes == 1) || (num_attributes == 4);

        if(has_color)
        {
            cout << timestamp << "Reading color information." << endl;
        }

        if(has_intensity)
        {
            cout << timestamp << "Reading intensity information." << endl;
        }

        // Read scan data
        scan_in.open(scanFileName.c_str());
        if(!scan_in.good())
        {
            // Continue with next file if the expected file couldn't be read
            cout << timestamp << "UOS Reader: Unable to read scan " << scanFileName << endl;
            scan_in.close();
            scan_in.clear();
            continue;
        }
        else
        {
            // Tmp list of read points
            list<Vec > tmp_points;

            // Try to get fransformation from .frames file
            boost::filesystem::path frame_path(
                    boost::filesystem::path(dir) /
                    boost::filesystem::path( "scan" + to_string( fileCounter, 3 ) + ".frames" ) );
            string frameFileName = frame_path.string();

            frame_in.open(frameFileName.c_str());
            if(!frame_in.good())
            {
                // Try to parse .pose file
                boost::filesystem::path pose_path(
                        boost::filesystem::path(dir) /
                        boost::filesystem::path( "scan" + to_string( fileCounter, 3 ) + ".pose" ) );
                string poseFileName = pose_path.string();

                pose_in.open(poseFileName.c_str());
                if(pose_in.good())
                {
                    float euler[6];
                    for(int i = 0; i < 6; i++) pose_in >> euler[i];

                    euler[3] *= 0.017453293;
                    euler[4] *= 0.017453293;
                    euler[5] *= 0.017453293;

                    Vec position(euler[0], euler[1], euler[2]);
                    Vec angle(euler[3], euler[4], euler[5]);

                    tf = Matrix4<Vec>(position, angle);
                }
                else
                {
                    cout << timestamp << "UOS Reader: Warning: No position information found." << endl;
                    tf = Matrix4<Vec>();
                }

            }
            else
            {
                // Use transformation from .frame files
                tf = parseFrameFile(frame_in);

            }

            // Print pose information
            float euler[6];
            tf.toPostionAngle(euler);

            cout << timestamp << "Processing " << scanFileName << " @ "
                << euler[0] << " " << euler[1] << " " << euler[2] << " "
                << euler[3] << " " << euler[4] << " " << euler[5] << endl;

            // Skip first line in scan file (maybe metadata)
            char dummy[1024];
            scan_in.getline(dummy, 1024);

            // Setup info output
            string comment = timestamp.getElapsedTime() + "Reading file " + scanFileName;
            ProgressBar progress(points_in_file, comment);

            // Read all points
            while(scan_in.good())
            {
                float x, y, z, rem, dummy;
                int r, g, b;

                point_counter ++;

                if(has_intensity && !has_color)
                {
                    scan_in >> x >> y >> z >> rem;
                }
                else if(has_intensity && has_color)
                {
                    scan_in >> x >> y >> z >> rem >> r >> g >> b;
                    allColors.push_back(BaseVector<int> (r, g, b));
                }
                else if(has_color && !has_intensity)
                {
                    scan_in >> x >> y >> z >> r >> g >> b;
                    allColors.push_back(BaseVector<int> (r, g, b));
                }
                else
                {
                    scan_in >> x >> y >> z;
                    for(int n_dummys = 0; n_dummys < num_attributes; n_dummys++) scan_in >> dummy;
                }

                BaseVector<float> point(x, y, z);
                BaseVector<unsigned char> color;

                // Code branching for point converter!
                if(!m_saveToDisk)
                {
                    tmp_points.push_back(point);
                }
                else
                {
                    if(m_outputFile.good())
                    {
                        if(point_counter % skipPoints == 0)
                        {
                            point = tf * point;
                            m_outputFile << point[0] << " " << point[1] << " " << point[2] << " ";

                            // Save remission values if present
                            if(has_intensity && m_saveRemission)
                            {
                                m_outputFile << rem << " ";
                            }

                            // Save color values if present
                            if(has_color)
                            {
                                m_outputFile << r << " " << g << " " << b;
                            }
                            else if(m_saveRemissionColor)
                            {
                                r = g = b = rem;
                                m_outputFile << r << " " << g << " " << b;
                            }
                            m_outputFile << endl;
                        }
                    }
                }
                ++progress;
            }

            // Save index of first point of new scan
            size_t firstIndex;
            if(allPoints.size() > 0)
            {
                firstIndex = allPoints.size();
            }
            else
            {
                firstIndex = 0;
            }

            // Transform scan point with current matrix
            list<Vec >::iterator it, it1;
            for(it = tmp_points.begin(); it != tmp_points.end(); it++)
            {
                Vec v = *it;
                v = tf * v;
                allPoints.push_back(v);
            }

            // Save last index
            size_t lastIndex;
            if(allPoints.size() > 0)
            {
                lastIndex = allPoints.size() - 1;
            }
            else
            {
                lastIndex = 0;
            }

            // Save index pair for current scan
            sub_clouds.push_back(make_pair(firstIndex, lastIndex));
            m_numScans++;
        }
        cout << endl;
    }

    // Convert into array
    if ( allPoints.size() )
    {
        cout << timestamp << "UOS Reader: Read " << allPoints.size() << " points." << endl;

        // Save position information

        size_t numPoints(0);
        floatArr points;
        ucharArr pointColors;

        numPoints = allPoints.size();
        points = floatArr( new float[3 * allPoints.size()] );
        list<Vec >::iterator p_it;
        size_t i(0);
        for( p_it = allPoints.begin(); p_it != allPoints.end(); p_it++ )
        {
            Vec v = *p_it;
            points[i    ] = v[0];
            points[i + 1] = v[1];
            points[i + 2] = v[2];
            i += 3;
        }

        // Save color information
        if ( allColors.size() )
        {
            pointColors = ucharArr( new unsigned char[ 3 * numPoints ] );
            i = 0;
            list<BaseVector<int>>::iterator c_it;
            for(c_it = allColors.begin(); c_it != allColors.end(); c_it++)
            {
                BaseVector<int> v = *c_it;
                pointColors[i    ] = (unsigned char) v[0];
                pointColors[i + 1] = (unsigned char) v[1];
                pointColors[i + 2] = (unsigned char) v[2];
                i += 3;
            }
        }

        // Create point cloud in model
        model = ModelPtr( new Model );
        model->m_pointCloud = PointBufferPtr( new PointBuffer );
        model->m_pointCloud->setPointArray( points, numPoints );

        if (allColors.size())
        {
            model->m_pointCloud->setColorArray(pointColors, numPoints);
        }

        // Add sub cloud information
        if (sub_clouds.size())
        {
            indexArray sub_clouds_array = indexArray( new unsigned int[sub_clouds.size() * 2] );
            for(size_t i = 0; i < sub_clouds.size(); i++)
            {
                sub_clouds_array[i*2 + 0] = sub_clouds[i].first;
                sub_clouds_array[i*2 + 1] = sub_clouds[i].second;
            }

            model->m_pointCloud->addIndexChannel(sub_clouds_array, "sub_clouds", numPoints, 2);
        }
    }

}

void UosIO::readOldFormat(ModelPtr &model, string dir, int first, int last, size_t &n)
{
    Matrix4<Vec> m_tf;

    list<Vec > ptss;
    list<Vec > allPoints;
    for(int fileCounter = first; fileCounter <= last; fileCounter++)
    {
        float euler[6];
        ifstream scan_in, pose_in, frame_in;

        // Code imported from slam6d! Don't blame me..
        string scanFileName;
        string poseFileName;

        // Create correct path
        boost::filesystem::path p(
                boost::filesystem::path(dir) /
                boost::filesystem::path( to_string( fileCounter, 3 ) ) /
                boost::filesystem::path( "position.dat" ) );

        // Get file name (if some knows a more elegant way to
        // extract the pull path let me know
        poseFileName = "/" + p.relative_path().string();

        // Try to open file
        pose_in.open(poseFileName.c_str());

        // Abort if opening failed and try with next die
        if (!pose_in.good()) continue;
        cout << timestamp << "Processing Scan " << dir << "/" << to_string(fileCounter, 3) << endl;

        // Extract pose information
        for (unsigned int i = 0; i < 6; pose_in >> euler[i++]);

        // Convert mm to cm
        for (unsigned int i = 0; i < 3; i++) euler[i] = euler[i] * 0.1;

        // Convert angles from deg to rad
        for (unsigned int i = 3; i <= 5; i++) {
            euler[i] *= 0.01f;
            //   if (euler[i] < 0.0) euler[i] += 360;
            euler[i] = rad(euler[i]);
        }

        // Read and convert scan
        for (int i = 1; ; i++) {
            //scanFileName = dir + to_string(fileCounter, 3) + "/scan" + to_string(i,3) + ".dat";

            boost::filesystem::path sfile(
                    boost::filesystem::path(dir) /
                    boost::filesystem::path( to_string( fileCounter, 3 ) ) /
                    boost::filesystem::path( "scan" + to_string(i) + ".dat" ) );
            scanFileName = "/" + sfile.relative_path().string();

            scan_in.open(scanFileName.c_str());
            if (!scan_in.good()) {
                scan_in.close();
                scan_in.clear();
                break;
            }

            int    Nr = 0, intensity_flag = 0;
            int    D;
            double current_angle;
            double X, Z, I;                     // x,z coordinate and intensity

            char firstLine[81];
            scan_in.getline(firstLine, 80);

            char cNr[4];
            cNr[0] = firstLine[2];
            cNr[1] = firstLine[3];
            cNr[2] = firstLine[4];
            cNr[3] = 0;
            Nr = atoi(cNr);

            // determine weather we have the new files with intensity information
            if (firstLine[16] != 'i') {
                intensity_flag = 1;
                char cAngle[8];
                cAngle[0] = firstLine[35];
                cAngle[1] = firstLine[36];
                cAngle[2] = firstLine[37];
                cAngle[3] = firstLine[38];
                cAngle[4] = firstLine[39];
                cAngle[5] = firstLine[40];
                cAngle[6] = firstLine[41];
                cAngle[7] = 0;
                current_angle = atof(cAngle);
                cout << current_angle << endl;
            } else {
                intensity_flag = 0;
                char cAngle[8];
                cAngle[0] = firstLine[54];
                cAngle[1] = firstLine[55];
                cAngle[2] = firstLine[56];
                cAngle[3] = firstLine[57];
                cAngle[4] = firstLine[58];
                cAngle[5] = firstLine[59];
                cAngle[6] = firstLine[60];
                cAngle[7] = 0;
                current_angle = atof(cAngle);
            }

            double cos_currentAngle = cos(rad(current_angle));
            double sin_currentAngle = sin(rad(current_angle));

            for (int j = 0; j < Nr; j++) {
                if (!intensity_flag) {
                    scan_in >> X >> Z >> D >> I;
                } else {
                    scan_in >> X >> Z;
                    I = 1.0;
                }

                // calculate 3D coordinates (local coordinates)
                Vec p;
                p[0] = X;
                p[1] = Z * sin_currentAngle;
                p[2] = Z * cos_currentAngle;

                ptss.push_back(p);
            }
            scan_in.close();
            scan_in.clear();
        }

        pose_in.close();
        pose_in.clear();

        // Create path to frame file
        boost::filesystem::path framePath(
                boost::filesystem::path(dir) /
                boost::filesystem::path("scan" + to_string( fileCounter, 3 ) + ".frames" ) );
        string frameFileName = "/" + framePath.relative_path().string();

        // Try to open frame file
        frame_in.open(frameFileName.c_str());
        if(frame_in.good())
        {
            // Transform scan data according to frame file
            m_tf = parseFrameFile(frame_in);
        }
        else
        {
            // Transform scan data using information from 'position.dat'
            Vec position(euler[0], euler[1], euler[2]);
            Vec angle(euler[3], euler[4], euler[5]);
            m_tf = Matrix4<Vec>(position, angle);
        }

        // Transform points and insert in to global vector
        list<Vec >::iterator it;
        for(it = ptss.begin(); it != ptss.end(); it++)
        {
            Vec v = *it;
            v = m_tf * v;
            allPoints.push_back(v);
        }

        // Clear scan
        ptss.clear();
    }

    // Convert into indexed array
    if(allPoints.size() > 0)
    {
        cout << timestamp << "UOS Reader: Read " << allPoints.size() << " points." << endl;
        n = allPoints.size();
        floatArr points( new float[3 * allPoints.size()] );
        list<Vec >::iterator p_it;
        int i(0);
        for( p_it = allPoints.begin(); p_it != allPoints.end(); p_it++ )
        {
            int t_index = 3 * i;
            Vec v = *p_it;
            points[t_index    ] = v[0];
            points[t_index + 1] = v[1];
            points[t_index + 2] = v[2];
            i++;
        }

        // Alloc model
        model = ModelPtr( new Model );
        model->m_pointCloud = PointBufferPtr( new PointBuffer );
        model->m_pointCloud->setPointArray( points, n );
    }
}

Matrix4<Vec> UosIO::parseFrameFile(ifstream& frameFile)
{
    float m[16], color;
    while(frameFile.good())
    {
        for(int i = 0; i < 16; i++ && frameFile.good()) frameFile >> m[i];
        frameFile >> color;
    }

    return Matrix4<Vec>(m);
}

} // namespace lvr2

ext: cpp


text:
#include "CarditConsensusMeeting.h"
#include "../net.h"
#include <memory>
#include "../util.h"
#include "../chain.h"
#include "../sync.h"
#include "../validation.h"
#include "../net_processing.h"
#include <boost/date_time/posix_time/posix_time.hpp>
#include <time.h>
#include <vector>
#include <list>
#include "../net.h"

extern void  generateDPOCForMeetingForPackage(uint160 pubkey160hash, uint32_t nPeriodCount, uint64_t  nPeriodStartTime, uint32_t  nTimePeriod);

CCarditConsensusMeeting::CCarditConsensusMeeting():bInit(true),bHasCompleteNewMeeting(false),nInitPeriodStartTime(0)
                                                          , bCanPackage(true)
                                                          , bPackageing(false), nMeetingStatus(0)
{
	pCurrentMetting.reset();
}

CCarditConsensusMeeting::~CCarditConsensusMeeting()
{
}

void CCarditConsensusMeeting::meeting()
{
	boost::this_thread::interruption_point();

	if (0 == nMeetingStatus || 3 == nMeetingStatus)
	{
		if (0 == nMeetingStatus)
		{
			nMeetingStatus = 1;
			init();
		}
		return;
	}
	else if (2 != nMeetingStatus || NULL == pCurrentMetting)
	{
		if (1 == nMeetingStatus  && NULL != pCurrentMetting)
		{
			nMeetingStatus = 2;
		}
		return;
	}

	doMeeting();
}

void CCarditConsensusMeeting::init()
{
	LogPrintf("[CCarditConsensusMeeting::init] begin\n");
	boost::this_thread::interruption_point();

	int readtime = (nInitPeriodStartTime - CACHED_BLOCK_COUNT * BLOCK_GEN_TIME) / 1000;

	//Get the list of consensus at the start
	std::list<std::shared_ptr<CConsensusAccount>> consensusList;
	CConsensusAccountPool::Instance().listSnapshotsToTime(consensusList, readtime);

	LogPrintf("[CCarditConsensusMeeting::init]PeriodStartTime--%d--ConsensusList--%d\n",
		       nInitPeriodStartTime,consensusList.size());

	pCurrentMetting.reset();
	localAccount.Set160Hash();

	pCurrentMetting.reset(new CMeetingItem(localAccount, consensusList, nInitPeriodStartTime));
	if (NULL == pCurrentMetting)
	{
		LogPrintf("[CCarditConsensusMeeting::init]Initialization failure，new CMeetingItem failure\n");

		nMeetingStatus = 3;
		return;
	}

	pCurrentMetting->sortConsensusList();

	//Get my packing position
	initNewMeetingRound();

	bInit = false;

	LogPrintf("[CCarditConsensusMeeting::init] old metting size : {%d}\n", oldMettingsList.size());
	LogPrintf("[CCarditConsensusMeeting::init] end by Initializing the meeting build completion\n");
}

void CCarditConsensusMeeting::doMeeting()
{
	int64_t nNowTime = timeService.GetCurrentTimeMillis();

	//Is it in the consensus list
	if (pCurrentMetting->inConsensusList())
	{
		//Should I pack it now
		if (pCurrentMetting->canPackage(nNowTime))
		{
			LogPrintf("[CCarditConsensusMeeting::doMeeting] canPackage is true. \n");
			doPackage();
		}
	}

	//Whether the meeting is over
	if (pCurrentMetting->canEnd(nNowTime))
	{
		LogPrintf("[CCarditConsensusMeeting::doMeeting] CurrentMetting is canEnd\n");
		newMeetingRound();
	}

	//MilliSleep(50);

	return;
}

void CCarditConsensusMeeting::initNewMeetingRound()
{
	LogPrintf("[CCarditConsensusMeeting::initNewMeetingRound] begin\n");
	pCurrentMetting->startConsensus();

	LogPrintf("[CCarditConsensusMeeting::initNewMeetingRound] end byRound the end, switch to a new round of consensus , startTime {%d} , endTime {%d} , myTime {%d}\n",
		       pCurrentMetting->getPeriodStartTime(),pCurrentMetting->getPeriodEndTime(),
		       pCurrentMetting->getMyPackageTime());
}

void CCarditConsensusMeeting::doPackage()
{
	LogPrintf("[CCarditConsensusMeeting::doPackage] begin\n");

	uint160 hash160;
	localAccount.Get160Hash(hash160);
	try
	{
		generateDPOCForMeetingForPackage(hash160, pCurrentMetting->getPeriodCount(),
			pCurrentMetting->getPeriodStartTime(),
			pCurrentMetting->getMyPackageIndex());

		//print out
		CBlockIndex* pBestBlockIndexss = NULL;
		{
			LOCK(cs_main);
			pBestBlockIndexss = chainActive.Tip();
		}
		if (NULL == pBestBlockIndexss)
		{
			LogPrintf("[CCarditConsensusMeeting::doPackage] end by error NULL == pBestBlockIndexss\n");
			return;
		}

		time_t t = time(NULL);
		struct tm* stime = localtime(&t);
		char cTmp[32];
		memset(cTmp, 0, sizeof(cTmp));
		sprintf(cTmp, "%04d-%02d-%02d %02d:%02d:%02d", 1900 + stime->tm_year, 1 + stime->tm_mon,
				stime->tm_mday, stime->tm_hour,
				stime->tm_min, stime->tm_sec);

		if (g_bStdCout)
		{
			std::cout <<"---------------------------------------------------"<< std::endl;
			std::cout << "CCarditConsensusMeeting::doPackage--MeetingStartTime--" << pCurrentMetting->getPeriodStartTime()
					  << "--MeetingEndTime--" << pCurrentMetting->getPeriodEndTime()
					  << "--packageTime--" << pCurrentMetting->getMyPackageTime()
					  << "--packageTimeEnd--" << pCurrentMetting->getMyPackageTimeEnd()
					  << "--packageIndex--" << pCurrentMetting->getMyPackageIndex()
					  << "--packageCount--" << pCurrentMetting->getPeriodCount()
					 // << "---Time----" << cTmp
					  << "-----PackageTime---" << DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pCurrentMetting->getMyPackageTimeEnd() / 1000)
					  <<"---Hight---"<<pBestBlockIndexss->nHeight
					  <<"---Publickey--"<< hash160.GetHex()
					  << std::endl;
			std::cout << "---------------------------------------------------" << std::endl;
		}

		LogPrintf("[CCarditConsensusMeeting::doPackage] end by-- \
				   MeetingStartTime--%d--MeetingEndTime--%d--packageTime--%d--  \
				   packageTimeEnd--%d--packageIndex--%d--packageCount--%d--  \
				   Time--%s--Hight--%d--Publickey--%s\n",
			pCurrentMetting->getPeriodStartTime(), pCurrentMetting->getPeriodEndTime(),
			pCurrentMetting->getMyPackageTime(), pCurrentMetting->getMyPackageTimeEnd(),
			pCurrentMetting->getMyPackageIndex(), pCurrentMetting->getPeriodCount(),
			cTmp, pBestBlockIndexss->nHeight, hash160.GetHex());
	}
	catch (std::exception &e)
	{
		LogPrintf("[CCarditConsensusMeeting::doPackage] end by generateDPOCForMeetingForPackage trow error %s\n", e.what());
		return;
	}
	catch (...)
	{
		LogPrintf("[CCarditConsensusMeeting::doPackage] end by generateDPOCForMeetingForPackage trow error\n");
		return;
	}
}

bool CCarditConsensusMeeting::newMeetingRound()
{
	boost::this_thread::interruption_point();
	LogPrintf("[CCarditConsensusMeeting::newMeetingRound] begin\n");

	std::shared_ptr<CMeetingItem> previousMetting(pCurrentMetting);

	{
		writeLock  wtlock(rwmutex);
		oldMettingsList.push_back(previousMetting);
		if (5 < oldMettingsList.size())
		{
			int count = oldMettingsList.size();
			for (int i = 0; i < count - 5; i++)
			{
				oldMettingsList.pop_front();
			}
		}
	}

	CBlockIndex* pBestBlockIndex = NULL;
	{
		LOCK(cs_main);
		pBestBlockIndex = chainActive.Tip();
	}
	if (NULL == pBestBlockIndex)
	{
		LogPrintf("[CCarditConsensusMeeting::newMeetingRound] end by error NULL == pBestBlockIndex\n");
		return false;
	}

	int64_t blockStartTime = pBestBlockIndex->nPeriodStartTime();
	int64_t blockStopTime = pBestBlockIndex->nPeriodStartTime() + pBestBlockIndex->nPeriodCount()*BLOCK_GEN_TIME;
	int64_t newMeetingTime = 0;

	// Reset meeting time
	// The last meeting was not finished
	if ((previousMetting->getPeriodEndTime() < blockStopTime) && (previousMetting->getPeriodEndTime() >= blockStartTime)) {
		//The meeting has not been completed and resumed
		newMeetingTime = blockStartTime;
	}
	else if (previousMetting->getPeriodEndTime() > blockStopTime) {
		//The state of the block synchronization is problematic, and the block synchronization is not completed.
		//(you're in a meeting, waiting to roll back or synchronize, and stop keeping the bookkeeping)
		newMeetingTime = previousMetting->getPeriodEndTime();
	}
	else if (previousMetting->getPeriodEndTime() == blockStopTime) {
		// The meeting is normal
		newMeetingTime = blockStopTime;
	}

	//So we're going to push 10 blocks
	int readtime = (newMeetingTime - CACHED_BLOCK_COUNT * BLOCK_GEN_TIME) / 1000;

	//Start a new round of meetings
	pCurrentMetting.reset();
	std::list<std::shared_ptr<CConsensusAccount>> accountlist;
	CConsensusAccountPool::Instance().listSnapshotsToTime(accountlist, readtime);
	localAccount.Set160Hash();
	pCurrentMetting.reset(new CMeetingItem(localAccount, accountlist, newMeetingTime));
	if (NULL == pCurrentMetting)
	{
		LogPrintf("[CCarditConsensusMeeting::newMeetingRound] Create a MeetingItem failure\n");
		return false;
	}

	//The sorting
	pCurrentMetting->sortConsensusList();
	//Get your own packaging start time and end time
	initNewMeetingRound();
	LogPrintf("[CCarditConsensusMeeting::newMeetingRound] end\n");
	return true;
}

void CCarditConsensusMeeting::GetLocalAccountHash160(uint160 &u160Hash)
{
	localAccount.Get160Hash(u160Hash);
}

void CCarditConsensusMeeting::stopPackageNow()
{
	bPackageing = false;
}

void CCarditConsensusMeeting::startMeeting()
{
	LogPrintf("[CCarditConsensusMeeting::startMeeting] begin\n");

	try
	{
		{
			if (g_bStdCout)
			{
				std::cout << "[CCarditConsensusMeeting::startMeeting] wait for TimeService begin" << std::endl;
			}
			LogPrintf("[CCarditConsensusMeeting::startMeeting] wait for TimeService begin\n");

			while (true)
			{
				boost::this_thread::interruption_point();
				if (timeService.IsHasNetTimeOffset())
				{
					break;
				}
				MilliSleep(2000);
			}

			if (g_bStdCout)
			{
				std::cout << "[CCarditConsensusMeeting::startMeeting] wait for TimeService end" << std::endl;
			}
			LogPrintf("[CCarditConsensusMeeting::startMeeting] wait for TimeService end\n");
		}

		while (!CConsensusAccountPool::Instance().InitFinished())
		{
			boost::this_thread::interruption_point();
			MilliSleep(1000);
		}

		while (true)
		{
			boost::this_thread::interruption_point();

			if (hasCompleteRev())
			{
				meeting();
			}

			MilliSleep(50);
		}
	}
	catch (boost::thread_interrupted & errcod)
	{
		LogPrintf("[CCarditConsensusMeeting::startMeeting] end by boost::thread thrdMiningService Interrupt exception was thrown\n");
	}
	LogPrintf("[CCarditConsensusMeeting::startMeeting] end\n");
}

extern int64_t g_Reboot_Meeting_StartTime;

bool CCarditConsensusMeeting::hasCompleteRev()
{
	if (IsInitialBlockDownload())
	{
		return false;
	}
	if (bInit)
	{
		CBlockIndex* pBestBlockIndex = NULL;
		try
		{
			{
				LOCK(cs_main);
				pBestBlockIndex = chainActive.Tip();
			}
			if (NULL == pBestBlockIndex)
			{
				return false;
			}
		}
		catch (...)
		{
			LogPrintf("[CCarditConsensusMeeting::hasCompleteRev] end\n");

			return false;
		}

		int64_t nMeetEndTime = (pBestBlockIndex->nPeriodStartTime()) + (pBestBlockIndex->nPeriodCount()*BLOCK_GEN_TIME);
		int64_t nPackageTime = (pBestBlockIndex->nPeriodStartTime()) + (pBestBlockIndex->nTimePeriod()+1)*BLOCK_GEN_TIME;
		int64_t nNowTime = timeService.GetCurrentTimeMillis();

		//MilliSleep(50);

		//reboot chain
		int64_t nRebootHeight = GetArg("-blockrebootheight", 0);
		if (0 != nRebootHeight)
		{
			std::cout << "reboot chain nHeight=" << nRebootHeight << std::endl;
			std::string strPublicKey;
			if (CDpocInfo::Instance().GetLocalAccount(strPublicKey))
			{
				if (CConsensusAccountPool::Instance().verifyPkIsTrustNode(strPublicKey))
				{
					if (nRebootHeight == pBestBlockIndex->nHeight+1)
					{
						int32_t p_timeout = 10*60;
						while (g_Reboot_Meeting_StartTime == 0)
						{
							MilliSleep (100);
							p_timeout --;

							if (p_timeout == 0)
							{
								break;
							}
						}

						if (p_timeout)
						{
							nInitPeriodStartTime = g_Reboot_Meeting_StartTime;
						}
						else
						{
							//nInitPeriodStartTime = timeService.GetCurrentTimeMillis();
							nNowTime = (nNowTime-pBestBlockIndex->nPeriodStartTime())/(pBestBlockIndex->nPeriodCount()*BLOCK_GEN_TIME);
							nNowTime *= (pBestBlockIndex->nPeriodCount()*BLOCK_GEN_TIME);
							nNowTime += pBestBlockIndex->nPeriodStartTime();
							nInitPeriodStartTime = nNowTime;
						}
						return true;
					}
				}
			}
		}

		//nowTime-The latest block package time < 10s
		if (((nNowTime - nPackageTime) < BLOCK_GEN_TIME) && (nNowTime >= nPackageTime))
		{
			//nowTime<The latest block Meet End Time
			if (nNowTime < nMeetEndTime)
			{
				//The start time of the current meeting of this block as the start time of the initialization meeting
				//But if you take your own packaging time, you're not packing, and packing judgment is logically involved
				nInitPeriodStartTime = pBestBlockIndex->nPeriodStartTime();
				LogPrintf("[CCarditConsensusMeeting::hasCompleteRev] 0 %d and nowtime= %d end\n",nInitPeriodStartTime,  nNowTime);
				return true;
			}//nowTime>The latest block Meet End Time，but nowTime< The first package time in the next round
			else if ((nNowTime >= nMeetEndTime)&&(nNowTime <= (nMeetEndTime+BLOCK_GEN_TIME)))
			{
				//At the end of the last meeting, as the beginning of the initial meeting
				nInitPeriodStartTime = nMeetEndTime;
				LogPrintf("[CCarditConsensusMeeting::hasCompleteRev] 1 %d and nowtime= %d end\n",nInitPeriodStartTime, nNowTime);
				return true;
			}//nowTime>The latest end of the meeting，The first 10 seconds passed, but not the first one
			else if(nNowTime > (nMeetEndTime + BLOCK_GEN_TIME))
			{
				//At the end of the last meeting, as the beginning of the initial meeting
				nInitPeriodStartTime = nMeetEndTime;
				LogPrintf("[CCarditConsensusMeeting::hasCompleteRev] 2 %d and nowtime= %d end\n",nInitPeriodStartTime, nNowTime);
				return true;
			}

		}
	}

	//The above code is executed only once when it is initialized
	if (!bInit)
	{
		//MilliSleep(50);
		return true;
	}

	return false;
}

void CCarditConsensusMeeting::stop()
{
}

bool CCarditConsensusMeeting::isPreMeetingLastBlock(CBlockIndex* pBlockHeader)
{
	if (NULL == pBlockHeader)
	{
		return false;
	}

	if (pBlockHeader->nTimePeriod() == pBlockHeader->nPeriodCount() - 1)
	{
		return true;
	}

	return false;
}

int CCarditConsensusMeeting::getCurrentConsensusInfo(int64_t nPeriodStartTime, int32_t nTimePeriod ,  uint160& myHash160)
{
	readLock  rdlock(rwmutex);

	if ( NULL == pCurrentMetting || pCurrentMetting->isNull() ) {
		return -1;
	}

	if (nPeriodStartTime == pCurrentMetting->getPeriodStartTime())
	{
		if (pCurrentMetting->getOldPublicKey(nTimePeriod, myHash160))
		{
			return 1;
		}
		return 0;
	}
	else {
		LogPrintf("[getCurrentConsensusInfo]  pCurrentMetting getPeriodStartTime== %ld\n", pCurrentMetting->getPeriodStartTime());
	}

	//Previous round
	bool bHavePeriodStartTime = false;

	std::list<std::shared_ptr<CMeetingItem>>::iterator iter = oldMettingsList.begin();
	for (;iter!=oldMettingsList.end();++iter)
	{
		LogPrintf("[getCurrentConsensusInfo] getPeriodStartTime== %ld\n", (*iter)->getPeriodStartTime());
		if ((*iter)->getPeriodStartTime() == nPeriodStartTime)
		{
			bHavePeriodStartTime = true;
		}

		if ((*iter)->getPeriodStartTime() == nPeriodStartTime)
		{
			if ((*iter)->getOldPublicKey(nTimePeriod, myHash160))
			{
				return 1;
			}
		}
	}

	if (bHavePeriodStartTime)
	{
		return 0;
	}
	return -1;
}

int CCarditConsensusMeeting::getLast1RoundMeetingInfo(int64_t curPeriodStartTime,   int64_t& nPeriodStartTime  , int32_t& nPeriodCount)
{
	readLock  rdlock(rwmutex);
	if (oldMettingsList.empty())
	{
		return -1;
	}

	std::list<std::shared_ptr<CMeetingItem>>::iterator iterbegin = oldMettingsList.begin();
	if ((*iterbegin)->getPeriodStartTime() > curPeriodStartTime)
	{
		return -1;
	}

	std::list<std::shared_ptr<CMeetingItem>>::reverse_iterator iter = oldMettingsList.rbegin();
	nPeriodCount= (*iter)->getPeriodCount();
	nPeriodStartTime = (*iter)->getPeriodStartTime();
	return 1;
}

int CCarditConsensusMeeting::getLast2RoundMeetingInfo(int64_t curPeriodStartTime,   int64_t& nPeriodStartTime  , int32_t& nPeriodCount)
{
	readLock  rdlock(rwmutex);
	if (oldMettingsList.size() < 2)
	{
		return -1;
	}

	std::list<std::shared_ptr<CMeetingItem>>::iterator iterbegin = oldMettingsList.begin();
	if ((*iterbegin)->getPeriodStartTime() > curPeriodStartTime)
	{
		return -1;
	}

	std::list<std::shared_ptr<CMeetingItem>>::reverse_iterator iter = oldMettingsList.rbegin();
	++iter;
	nPeriodCount= (*iter)->getPeriodCount();
	nPeriodStartTime = (*iter)->getPeriodStartTime();
	return 1;
}

bool CCarditConsensusMeeting::GetMeetingList(int64_t nStartTime, std::list<std::shared_ptr<CConsensusAccount>> &conList)
{
	LogPrintf("[CCarditConsensusMeeting::GetMeetingList] begin\n");
    static  int64_t tempStartTime = 0;
    static std::list<std::shared_ptr<CConsensusAccount>> tempconList;
    static std::list<std::shared_ptr<CConsensusAccount>> sortconList;
  if(tempStartTime == nStartTime && tempconList.size() == conList.size()&&tempconList.size()!=0){
        std::list<std::shared_ptr<CConsensusAccount>>::iterator itor1 = tempconList.begin();
        std::list<std::shared_ptr<CConsensusAccount>>::iterator itor2 = conList.begin();
        bool getdifference = false;
           while(itor1!=tempconList.end()&&itor2!=conList.end()){
               uint160 pk1 = (*itor1)->getPubicKey160hash();
               uint160 pk2 = (*itor2)->getPubicKey160hash();
               if(pk1 != pk2){
                   getdifference = true;
                       break;
                }
               itor1++;
               itor2++;
           }
           if(!getdifference){
                conList.clear();
                std::copy(sortconList.begin(), sortconList.end(), std::back_inserter(conList));
                LogPrintf("[CCarditConsensusMeeting::GetMeetingList] end temp used conList_size:%d\n",conList.size());
                return true;
           }
    }
    tempStartTime = nStartTime;
    tempconList.clear();
    tempconList = conList;

	CLocalAccount account;
    CMeetingItem meetingItem(account, conList, nStartTime);
	meetingItem.sortConsensusList();
	meetingItem.GetConsensusList(conList);
    sortconList = conList;

    LogPrintf("[CCarditConsensusMeeting::GetMeetingList] endl\n");
	return true;
}

bool CCarditConsensusMeeting::IsCompleteInit()
{
	if (!bInit)
	{
		return true;
	}
	else
	{
		return false;
	}
}

max_stars_repo_name: maxmaxj/ipchain

max_issues_repo_name: joshuabond/ipchain

max_forks_repo_name: joshuabond/ipchain