text:
//////////////////////////////////////////////////////////////////////////////////////
// This file is distributed under the University of Illinois/NCSA Open Source License.
// See LICENSE file in top directory for details.
//
// Copyright (c) 2016 Jeongnim Kim and QMCPACK developers.
//
// File developed by: Jeremy McMinnis, jmcminis@gmail.com, University of Illinois at Urbana-Champaign
//                    Cynthia Gu, zg1@ornl.gov, Oak Ridge National Laboratory
//                    Jeongnim Kim, jeongnim.kim@gmail.com, University of Illinois at Urbana-Champaign
//                    Mark A. Berrill, berrillma@ornl.gov, Oak Ridge National Laboratory
//
// File created by: Jeongnim Kim, jeongnim.kim@gmail.com, University of Illinois at Urbana-Champaign
//////////////////////////////////////////////////////////////////////////////////////

#include "QMCDrivers/BranchIO.h"
#include "HDFVersion.h"
#include "Message/CommOperators.h"
#include "io/hdf_archive.h"
#ifdef HAVE_ADIOS
#include "adios.h"
#include "adios_read.h"
#include "ADIOS/ADIOS_config.h"
#ifdef ADIOS_VERIFY
#include "ADIOS/ADIOS_verify.h"
#endif
#endif
#if defined(HAVE_LIBBOOST)
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/foreach.hpp>
#include <string>
#include <set>
#include <exception>
#include <iostream>
#endif

//#include <boost/archive/text_oarchive.hpp>
//
namespace qmcplusplus
{
#if defined(HAVE_LIBBOOST)
template<typename T>
inline void put_histogram( std::string name, accumulator_set<T> a,  boost::property_tree::ptree &pt)
{
  pt.put(name+".value",a.properties[0]);
  pt.put(name+".value_squared",a.properties[1]);
  pt.put(name+".weight",a.properties[2]);
}

template<typename T>
inline void get_histogram( std::string name, accumulator_set<T>& a, boost::property_tree::ptree &pt)
{
  a.properties[0]=pt.get<T>(name+".value");
  a.properties[1]=pt.get<T>(name+".value_squared");
  a.properties[2]=pt.get<T>(name+".weight");
}
#endif

template<typename T>
struct h5data_proxy<accumulator_set<T> >: public h5_space_type<T,1>
{
  enum {CAPACITY=accumulator_set<T>::CAPACITY};
  using h5_space_type<T,1>::dims;
  using h5_space_type<T,1>::get_address;
  typedef accumulator_set<T> data_type;
  data_type& ref_;

  inline h5data_proxy(data_type& a): ref_(a)
  {
    dims[0]=CAPACITY;
  }
  inline bool read(hid_t grp, const std::string& aname, hid_t xfer_plist=H5P_DEFAULT)
  {
    return h5d_read(grp,aname,get_address(ref_.properties),xfer_plist);
  }

  inline bool write(hid_t grp, const std::string& aname,hid_t xfer_plist=H5P_DEFAULT)
  {
    return h5d_write(grp,aname.c_str(),this->size(),dims,get_address(ref_.properties),xfer_plist);
  }

  /** return the start address */
  inline T* begin()
  {
    return ref_.properties;
  }
  /** return the end address */
  inline T* end()
  {
    return ref_.properties+CAPACITY;
  }
};

std::vector<std::string> BranchIO::vParamName;
std::vector<std::string> BranchIO::iParamName;

void BranchIO::initAttributes()
{
  if(vParamName.size()) return;
  vParamName.resize(10);
  vParamName[0]="tau";
  vParamName[1]="taueff";
  vParamName[2]="etrial";
  vParamName[3]="eref";
  vParamName[4]="branchmax";
  vParamName[5]="branchcutoff";
  vParamName[6]="branchfilter";
  vParamName[7]="sigma";
  vParamName[8]="acc_energy";
  vParamName[9]="acc_samples";

  iParamName.resize(7);
  iParamName[0]="warmupsteps";
  iParamName[1]="energyupdateinterval";
  iParamName[2]="counter";
  iParamName[3]="targetwalkers";
  iParamName[4]="maxwalkers";
  iParamName[5]="minwalkers";
  iParamName[6]="brnachinterval";
}

bool BranchIO::write(const std::string& fname)
{
  if(myComm->rank()) return true;

#if defined(HAVE_LIBBOOST)
  initAttributes();
  using boost::property_tree::ptree;
  ptree pt;

  // Put log filename in property tree
  pt.put("state.branchmode", ref.BranchMode);

  for(int i=0;i<vParamName.size(); ++i)
    pt.put("state.vparam."+vParamName[i], ref.vParam[i]);
  for(int i=0;i<iParamName.size(); ++i)
    pt.put("state.iparam."+iParamName[i], ref.iParam[i]);

  put_histogram("state.energy",ref.EnergyHist,pt);
  put_histogram("state.variance",ref.VarianceHist,pt);
  put_histogram("state.r2accepted",ref.R2Accepted,pt);
  put_histogram("state.r2proposed",ref.R2Proposed,pt);
  std::string xname=fname+".qmc.xml";
  write_xml(xname, pt);
#else
  //append .qmc.h5 if missing
  std::string h5name(fname);
  if(fname.find("qmc.h5")>= fname.size()) h5name.append(".qmc.h5");
  hdf_archive dump(myComm);
  hid_t fid = dump.create(h5name);
  dump.push(hdf::main_state);
  dump.push(hdf::qmc_status);
  std::string v_header("tau:taueff:etrial:eref:branchmax:branchcutoff:branchfilter:sigma:acc_energy:acc_samples");
  std::string i_header("warmupsteps:energyupdateinterval:counter:targetwalkers:maxwalkers:minwalkers:branchinterval");
  dump.write(v_header,"vparam_def");
  dump.write(i_header,"iparam_def");
  dump.write(ref.vParam,"vparam");
  dump.write(ref.iParam,"iparam");
  dump.write(ref.BranchMode,"branchmode");
  dump.push("histogram");
  dump.write(ref.EnergyHist,"energy");
  dump.write(ref.VarianceHist,"variance");
  dump.write(ref.R2Accepted,"r2accepted");
  dump.write(ref.R2Proposed,"r2proposed");
  //PopHist is not being used in 2010-10-19
  //if(ref.BranchMode[SimpleFixedNodeBranch::B_DMC])
  //{
	//  dump.push("population");
  //  dump.write(ref.PopHist.myData,"histogram");
  //}
#endif
  return true;
}

bool BranchIO::read(const std::string& fname)
{
  int found_config=0;

#if defined(HAVE_LIBBOOST)
  if(myComm->rank()==0)
  {
    initAttributes();
    using boost::property_tree::ptree;
    ptree pt;
    std::string xname=fname+".qmc.xml";
    read_xml(xname, pt);
    if(!pt.empty())
    {
      ref.BranchMode=pt.get<BranchModeType>("state.branchmode");

      get_histogram("state.energy",ref.EnergyHist,pt);
      get_histogram("state.variance",ref.VarianceHist,pt);
      get_histogram("state.r2accepted",ref.R2Accepted,pt);
      get_histogram("state.r2proposed",ref.R2Proposed,pt);

      int i=0;
      BOOST_FOREACH(const ptree::value_type& v, pt.get_child("state.iparam"))
      {
        ref.iParam[i++]=v.second.get_value<int>();
      }
      i=0;
      BOOST_FOREACH(const ptree::value_type& v, pt.get_child("state.vparam"))
      {
        ref.vParam[i++]=v.second.get_value<double>();
      }
      found_config=1;
    }
  }
#else
  if(myComm->rank()==0)
  {
    HDFVersion res_version(0,4); //start using major=0 and minor=4
    HDFVersion res_20080624(0,5);//major revision on 2008-06-24 0.5
    HDFVersion in_version(0,1);

    //append .config.h5 if missing
    std::string h5name(fname);
    if(fname.find("qmc.h5")>= fname.size()) h5name.append(".qmc.h5");

    hdf_archive prevconfig(myComm,true);
    found_config=prevconfig.open(h5name,H5F_ACC_RDONLY);

    if(found_config)
    {
      int n=ref.vParam.size()+ref.iParam.size();
      /** temporary storage to broadcast restart data */
      prevconfig.read(in_version.version,hdf::version);
      myComm->bcast(in_version.version);
      prevconfig.push(hdf::main_state,false);
      if(in_version>= res_20080624)
      {
        //need a better version control
        prevconfig.push(hdf::qmc_status,false);
        prevconfig.read(ref.vParam,"vparam");
        prevconfig.read(ref.iParam,"iparam");
        prevconfig.read(ref.BranchMode,"branchmode");

        prevconfig.push("histogram",false);
        prevconfig.read(ref.EnergyHist,"energy");
        prevconfig.read(ref.VarianceHist,"variance");
        prevconfig.read(ref.R2Accepted,"r2accepted");
        prevconfig.read(ref.R2Proposed,"r2proposed");
        prevconfig.pop();

        prevconfig.pop();
      }
      else
        found_config=false;
      prevconfig.pop();
    }
  }
#endif
  myComm->bcast(found_config);

  if(!found_config) return false;

  bcast_state();

  return true;
}

bool BranchIO::read_adios(const std::string& fname)
{//do not use this
  #ifdef HAVE_ADIOS
  if(ADIOS::getRdADIOS())
  {
    ADIOS::open(fname, myComm->getMPI());
    /** temporary storage to broadcast restart data */
    ADIOS::read(ref.vParam.data(),"vparam");
    ADIOS::read(ref.iParam.data(),"iparam");
    ADIOS::read(&ref.BranchMode,"branchmode");
    ADIOS::read(&ref.EnergyHist,"energy");
    ADIOS::read(&ref.VarianceHist,"variance");
    ADIOS::read(&ref.R2Accepted,"r2accepted");
    ADIOS::read(&ref.R2Proposed,"r2proposed");
    ADIOS::close();
  }
  bcast_state();
#endif
  return true;
}

void BranchIO::bcast_state()
{
  int n=ref.vParam.size()+ref.iParam.size();
  std::vector<RealType> pdata(n+1+16,-1);

  if(myComm->rank()==0)
  {
    copy(ref.vParam.begin(),ref.vParam.end(),pdata.begin());
    copy(ref.iParam.begin(),ref.iParam.end(),pdata.begin()+ref.vParam.size());
    int offset=n;
    pdata[offset++]=ref.BranchMode.to_ulong();
    copy(ref.EnergyHist.properties,ref.EnergyHist.properties+4,pdata.begin()+offset);
    offset+=4;
    copy(ref.VarianceHist.properties,ref.VarianceHist.properties+4,pdata.begin()+offset);
    offset+=4;
    copy(ref.R2Accepted.properties,ref.R2Accepted.properties+4,pdata.begin()+offset);
    offset+=4;
    copy(ref.R2Proposed.properties,ref.R2Proposed.properties+4,pdata.begin()+offset);
  }

  //broadcast to the nodes : need to add a namespace mpi::
  myComm->bcast(pdata);

  if(myComm->rank())
  {
    int ii=0;
    for(int i=0; i<ref.vParam.size(); ++i,++ii)
      ref.vParam[i]=pdata[ii];
    for(int i=0; i<ref.iParam.size(); ++i,++ii)
      ref.iParam[i]=static_cast<int>(pdata[ii]);
    ref.BranchMode=static_cast<unsigned long>(pdata[ii]);
  }
  {
    //update historgram
    int ii=n+1;
    ref.EnergyHist.reset(pdata[ii],pdata[ii+1],pdata[ii+2]);
    ii+=4;
    ref.VarianceHist.reset(pdata[ii],pdata[ii+1],pdata[ii+2]);
    ii+=4;
    ref.R2Accepted.reset(pdata[ii],pdata[ii+1],pdata[ii+2]);
    ii+=4;
    ref.R2Proposed.reset(pdata[ii],pdata[ii+1],pdata[ii+2]);
  }
}

#ifdef HAVE_ADIOS
int64_t BranchIO::get_Checkpoint_size()
{
  int64_t adios_groupsize = 8     \
                            + 8 * (4)                     \
                            + 8 * (4)                     \
                            + 8 * (4)                     \
                            + 8 * (4)                     \
                            + 4 * (8)                     \
                            + 8 * (16);
  return adios_groupsize;
}

void BranchIO::adios_checkpoint(int64_t adios_handle)
{
  //append .config.h5 if missing
  void* vparam = (void*)ref.vParam.data();
  void* iparam = (void*)ref.iParam.data();
  unsigned long branchmode = ref.BranchMode.to_ulong();
  RealType* energy = ref.EnergyHist.properties;
  RealType* variance = ref.VarianceHist.properties;
  RealType* r2accepted = ref.R2Accepted.properties;
  RealType* r2proposed = ref.R2Proposed.properties;
  adios_write (adios_handle, "branchmode", &branchmode);
  adios_write (adios_handle, "energy", energy);
  adios_write (adios_handle, "r2accepted", r2accepted);
  adios_write (adios_handle, "r2proposed", r2proposed);
  adios_write (adios_handle, "variance", variance);
  adios_write (adios_handle, "iparam", iparam);
  adios_write (adios_handle, "vparam", vparam);
}

#ifdef ADIOS_VERIFY
void BranchIO::adios_checkpoint_verify(ADIOS_FILE *fp)
{
  unsigned long branchmode = ref.BranchMode.to_ulong();
  IO_VERIFY::adios_checkpoint_verify_variables(fp, "branchmode", branchmode);
  IO_VERIFY::adios_checkpoint_verify_variables(fp, "energy", (RealType*) ref.EnergyHist.properties);
  IO_VERIFY::adios_checkpoint_verify_variables(fp, "variance", (RealType*)ref.VarianceHist.properties);
  IO_VERIFY::adios_checkpoint_verify_variables(fp, "r2accepted", (RealType*)ref.R2Accepted.properties);
  IO_VERIFY::adios_checkpoint_verify_variables(fp, "r2proposed", (RealType *)ref.R2Proposed.properties);
  IO_VERIFY::adios_checkpoint_verify_variables(fp, "iparam", (RealType *)ref.iParam.data());
  IO_VERIFY::adios_checkpoint_verify_intarray_variables(fp, "vparam", (int *)ref.vParam.data());
}
#endif

#endif

}

max_stars_repo_name: bwvdg/qmcpack

max_issues_repo_name: bwvdg/qmcpack

max_forks_repo_name: bwvdg/qmcpack


text:
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2005-2012. 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/interprocess for documentation.
//
//////////////////////////////////////////////////////////////////////////////

#ifndef BOOST_INTERPROCESS_SHM_NAMED_CONDITION_HPP
#define BOOST_INTERPROCESS_SHM_NAMED_CONDITION_HPP

#if (defined _MSC_VER) && (_MSC_VER >= 1200)
#  pragma once
#endif

#include <boost/interprocess/detail/config_begin.hpp>
#include <boost/interprocess/detail/workaround.hpp>
#include <boost/static_assert.hpp>
#include <boost/interprocess/detail/type_traits.hpp>
#include <boost/interprocess/creation_tags.hpp>
#include <boost/interprocess/exceptions.hpp>
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/sync/interprocess_condition.hpp>
#include <boost/interprocess/detail/managed_open_or_create_impl.hpp>
#include <boost/interprocess/detail/posix_time_types_wrk.hpp>
#include <boost/interprocess/sync/shm/named_creation_functor.hpp>
#include <boost/interprocess/sync/named_mutex.hpp>
#include <boost/interprocess/permissions.hpp>
#if defined (BOOST_INTERPROCESS_NAMED_MUTEX_USES_POSIX_SEMAPHORES)
   #include <boost/interprocess/sync/interprocess_mutex.hpp>
   #include <boost/interprocess/sync/scoped_lock.hpp>
   #include <boost/interprocess/sync/detail/condition_any_algorithm.hpp>
#else
   #include <boost/interprocess/sync/detail/locks.hpp>
#endif

//!\file
//!Describes process-shared variables interprocess_condition class

namespace boost {
namespace interprocess {
namespace ipcdetail {

/// @cond
class interprocess_tester;
/// @endcond

//! A global condition variable that can be created by name.
//! This condition variable is designed to work with named_mutex and
//! can't be placed in shared memory or memory mapped files.
class shm_named_condition
{
   /// @cond
   //Non-copyable
   shm_named_condition();
   shm_named_condition(const shm_named_condition &);
   shm_named_condition &operator=(const shm_named_condition &);
   /// @endcond
   public:
   //!Creates a global condition with a name.
   //!If the condition can't be created throws interprocess_exception
   shm_named_condition(create_only_t create_only, const char *name, const permissions &perm = permissions());

   //!Opens or creates a global condition with a name.
   //!If the condition is created, this call is equivalent to
   //!shm_named_condition(create_only_t, ... )
   //!If the condition is already created, this call is equivalent
   //!shm_named_condition(open_only_t, ... )
   //!Does not throw
   shm_named_condition(open_or_create_t open_or_create, const char *name, const permissions &perm = permissions());

   //!Opens a global condition with a name if that condition is previously
   //!created. If it is not previously created this function throws
   //!interprocess_exception.
   shm_named_condition(open_only_t open_only, const char *name);

   //!Destroys *this and indicates that the calling process is finished using
   //!the resource. The destructor function will deallocate
   //!any system resources allocated by the system for use by this process for
   //!this resource. The resource can still be opened again calling
   //!the open constructor overload. To erase the resource from the system
   //!use remove().
   ~shm_named_condition();

   //!If there is a thread waiting on *this, change that
   //!thread's state to ready. Otherwise there is no effect.*/
   void notify_one();

   //!Change the state of all threads waiting on *this to ready.
   //!If there are no waiting threads, notify_all() has no effect.
   void notify_all();

   //!Releases the lock on the named_mutex object associated with lock, blocks
   //!the current thread of execution until readied by a call to
   //!this->notify_one() or this->notify_all(), and then reacquires the lock.
   template <typename L>
   void wait(L& lock);

   //!The same as:
   //!while (!pred()) wait(lock)
   template <typename L, typename Pr>
   void wait(L& lock, Pr pred);

   //!Releases the lock on the named_mutex object associated with lock, blocks
   //!the current thread of execution until readied by a call to
   //!this->notify_one() or this->notify_all(), or until time abs_time is reached,
   //!and then reacquires the lock.
   //!Returns: false if time abs_time is reached, otherwise true.
   template <typename L>
   bool timed_wait(L& lock, const boost::posix_time::ptime &abs_time);

   //!The same as:   while (!pred()) {
   //!                  if (!timed_wait(lock, abs_time)) return pred();
   //!               } return true;
   template <typename L, typename Pr>
   bool timed_wait(L& lock, const boost::posix_time::ptime &abs_time, Pr pred);

   //!Erases a named condition from the system.
   //!Returns false on error. Never throws.
   static bool remove(const char *name);

   /// @cond
   private:

   #if defined (BOOST_INTERPROCESS_NAMED_MUTEX_USES_POSIX_SEMAPHORES)
   class internal_condition_members
   {
      public:
      typedef interprocess_mutex       mutex_type;
      typedef interprocess_condition   condvar_type;

      condvar_type&  get_condvar() {  return m_cond;  }
      mutex_type&    get_mutex()   {  return m_mtx; }

      private:
      mutex_type     m_mtx;
      condvar_type   m_cond;
   };

   typedef ipcdetail::condition_any_wrapper<internal_condition_members> internal_condition;
   #else    //defined (BOOST_INTERPROCESS_NAMED_MUTEX_USES_POSIX_SEMAPHORES)
   typedef interprocess_condition internal_condition;
   #endif   //defined (BOOST_INTERPROCESS_NAMED_MUTEX_USES_POSIX_SEMAPHORES)

   internal_condition &internal_cond()
   {  return *static_cast<internal_condition*>(m_shmem.get_user_address()); }

   friend class boost::interprocess::ipcdetail::interprocess_tester;
   void dont_close_on_destruction();

   typedef ipcdetail::managed_open_or_create_impl<shared_memory_object, 0, true, false> open_create_impl_t;
   open_create_impl_t m_shmem;

   template <class T, class Arg> friend class boost::interprocess::ipcdetail::named_creation_functor;
   typedef boost::interprocess::ipcdetail::named_creation_functor<internal_condition> construct_func_t;
   /// @endcond
};

/// @cond

inline shm_named_condition::~shm_named_condition()
{}

inline shm_named_condition::shm_named_condition(create_only_t, const char *name, const permissions &perm)
   :  m_shmem  (create_only
               ,name
               ,sizeof(internal_condition) +
                  open_create_impl_t::ManagedOpenOrCreateUserOffset
               ,read_write
               ,0
               ,construct_func_t(DoCreate)
               ,perm)
{}

inline shm_named_condition::shm_named_condition(open_or_create_t, const char *name, const permissions &perm)
   :  m_shmem  (open_or_create
               ,name
               ,sizeof(internal_condition) +
                  open_create_impl_t::ManagedOpenOrCreateUserOffset
               ,read_write
               ,0
               ,construct_func_t(DoOpenOrCreate)
               ,perm)
{}

inline shm_named_condition::shm_named_condition(open_only_t, const char *name)
   :  m_shmem  (open_only
               ,name
               ,read_write
               ,0
               ,construct_func_t(DoOpen))
{}

inline void shm_named_condition::dont_close_on_destruction()
{  interprocess_tester::dont_close_on_destruction(m_shmem);  }

inline void shm_named_condition::notify_one()
{  this->internal_cond().notify_one(); }

inline void shm_named_condition::notify_all()
{  this->internal_cond().notify_all(); }

template <typename L>
inline void shm_named_condition::wait(L& lock)
{  this->internal_cond().wait(lock); }

template <typename L, typename Pr>
inline void shm_named_condition::wait(L& lock, Pr pred)
{  this->internal_cond().wait(lock, pred); }

template <typename L>
inline bool shm_named_condition::timed_wait
   (L& lock, const boost::posix_time::ptime &abs_time)
{  return this->internal_cond().timed_wait(lock, abs_time); }

template <typename L, typename Pr>
inline bool shm_named_condition::timed_wait
   (L& lock, const boost::posix_time::ptime &abs_time, Pr pred)
{  return this->internal_cond().timed_wait(lock, abs_time, pred); }

inline bool shm_named_condition::remove(const char *name)
{  return shared_memory_object::remove(name); }

/// @endcond

}  //namespace ipcdetail
}  //namespace interprocess
}  //namespace boost

#include <boost/interprocess/detail/config_end.hpp>

#endif // BOOST_INTERPROCESS_SHM_NAMED_CONDITION_HPP

ext: hpp

max_stars_repo_name: iazarov/metrixplusplus

max_issues_repo_name: iazarov/metrixplusplus

max_forks_repo_name: iazarov/metrixplusplus


text:
/*!
 * *****************************************************************************
 *   \file faceDepthMapFrom3D_main.cpp
 *   \author moennen
 *   \brief
 *   \date 2018-03-19
 *   *****************************************************************************/

#include "utils/gl_utils.h"
#include "utils/gl_utils.inline.h"
#include "utils/imgFileLst.h"

#include "SDL2/SDL.h"
#include "SDL2/SDL_opengl.h"

// opengl
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>

// opencv
#include "utils/cv_utils.h"

// face detector / models
#include "externals/face/beFaceMModel.h"
#include "externals/face/beFaceModelInstance.h"

#include <boost/filesystem.hpp>

#include <memory>
#include <random>
#include <iostream>

using namespace std;
using namespace cv;
using namespace glm;
using namespace boost;

namespace
{
std::random_device rd{};
std::mt19937 rs_gen{rd()};

void init()
{
   glClearColor( 0.0, 0.0, 0.0, 0.0 );
   glMatrixMode( GL_PROJECTION );
   glLoadIdentity();
   // glOrtho( 0.0, windowSz.x, windowSz.y, 0.0, -10000.0, 10000.0 );
   // glEnable( GL_BLEND );
   glEnable( GL_DEPTH_TEST );
   // glFrontFace( GL_CW );
   glEnable( GL_TEXTURE_2D );
   glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
}

void drawFaceModel(
    const gl_utils::TriMeshBuffer& mdFace,
    const glm::mat4& p,
    const glm::mat4& mv,
    const glm::vec3& lightPos,
    const glm::vec3& lightCol,
    const float ambient )
{
   static gl_utils::RenderProgram faceShader;

   static GLint uniMVP = -1;
   static GLint uniMV = -1;
   static GLint uniMVN = -1;
   static GLint uniLightPos = -1;
   static GLint uniLightCol = -1;
   static GLint uniAmbient = -1;

   if ( faceShader._id == -1 )
   {
      faceShader.load(
          "/mnt/p4/avila/moennen_wkspce/sceneIllEst/faceDepthMapFrom3DMM/shaders/face_frag.glsl",
          "/mnt/p4/avila/moennen_wkspce/sceneIllEst/faceDepthMapFrom3DMM/shaders/face_vtx.glsl" );
      uniMVP = faceShader.getUniform( "mvp" );
      uniMV = faceShader.getUniform( "mv" );
      uniMVN = faceShader.getUniform( "mvn" );
      uniLightPos = faceShader.getUniform( "lightPos" );
      uniLightCol = faceShader.getUniform( "lightColor" );
      uniAmbient = faceShader.getUniform( "ambient" );
   }

   faceShader.activate();

   glUniformMatrix4fv( uniMV, 1, 0, value_ptr( mv ) );

   const mat4 mvp = p * mv;
   glUniformMatrix4fv( uniMVP, 1, 0, value_ptr( mvp ) );
   const mat4 mvt = transpose( inverse( mv ) );
   glUniformMatrix4fv( uniMVN, 1, 0, value_ptr( mvt ) );
   glUniform3fv( uniLightPos, 1, value_ptr( lightPos ) );
   glUniform3fv( uniLightCol, 1, value_ptr( lightCol ) );

   glUniform1f( uniAmbient, ambient );

   mdFace.draw();

   faceShader.deactivate();
}

void draw( GLuint tex, size_t w, size_t h )
{
   // Bind Texture
   glBindTexture( GL_TEXTURE_2D, tex );

   GLfloat Vertices[] = {(float)0,
                         (float)0,
                         0,
                         (float)0 + w,
                         (float)0,
                         0,
                         (float)0 + (float)w,
                         (float)0 + (float)h,
                         0,
                         (float)0,
                         (float)0 + (float)h,
                         0};
   GLfloat TexCoord[] = {
       0,
       0,
       1,
       0,
       1,
       1,
       0,
       1,
   };
   GLubyte indices[] = {0,
                        1,
                        2,  // first triangle (bottom left - top left - top right)
                        0,
                        2,
                        3};  // second triangle (bottom left - top right - bottom right)

   glEnableClientState( GL_VERTEX_ARRAY );
   glVertexPointer( 3, GL_FLOAT, 0, Vertices );

   glEnableClientState( GL_TEXTURE_COORD_ARRAY );
   glTexCoordPointer( 2, GL_FLOAT, 0, TexCoord );

   glDrawElements( GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, indices );

   glDisableClientState( GL_TEXTURE_COORD_ARRAY );
   glDisableClientState( GL_VERTEX_ARRAY );

   glBindTexture( GL_TEXTURE_2D, 0 );
}

void getOutUVS(
    const vector<vec2>& iuvs,
    const vector<uvec3>& ivecIdx,
    const glm::uvec3* ovecIdx,
    glm::vec2* ouvs )
{
   for ( size_t f = 0; f < ivecIdx.size(); ++f )
   {
      ouvs[ovecIdx[f].x] = iuvs[ivecIdx[f].x];
      ouvs[ovecIdx[f].y] = iuvs[ivecIdx[f].y];
      ouvs[ovecIdx[f].z] = iuvs[ivecIdx[f].z];
   }
}
}
const string keys =
    "{help h usage ? |         | print this message   }"
    "{@faceModel     |         | face detection model }"
    "{@faceInstLst   |         | face model instance files list}"
    "{@outDir        |         | output directories   }";

int main( int argc, char* argv[] )
{
   CommandLineParser parser( argc, argv, keys );
   if ( parser.has( "help" ) )
   {
      parser.printMessage();
      return ( 0 );
   }

   // Load background images
   ImgNFileLst instLst(2, parser.get<string>( "@faceInstLst" ).c_str(), "" );
   if ( instLst.size() == 0 )
   {
      cerr << "Invalid face instances list : " << parser.get<string>( "@faceInstLst" ) << endl;
      return -1;
   }

   //------------------------------------------------------------------------- Load model
   //
   const string BEfaceModelBin = parser.get<string>( "@faceModel" );
   BEFaceMModel beFaceMMd( BEfaceModelBin.c_str() );
   if ( !beFaceMMd.initialized() )
   {
      std::cerr << "Cannot import model : " << BEfaceModelBin << std::endl;
      return -1;
   }

   uvec2 imgSz( 256, 256 );

   // SDL init
   SDL_Init( SDL_INIT_EVERYTHING );
   SDL_Window* window = SDL_CreateWindow(
       "renderFaceMaps",
       SDL_WINDOWPOS_CENTERED,
       SDL_WINDOWPOS_CENTERED,
       imgSz.x,
       imgSz.y,
       SDL_WINDOW_OPENGL );
   SDL_GLContext glCtx = SDL_GL_CreateContext( window );

   // GLEW init
   GLenum err = glewInit();
   if ( GLEW_OK != err )
   {
      cerr << "Error: " << glewGetErrorString( err ) << endl;
      return -1;
   }

   // Common data alloc
   vector<vec3> vecVtx( BEFaceMModel::NumVertices, vec3( 0.0f ) );
   vector<vec3> vtxCol( BEFaceMModel::NumVertices, vec3( 0.0f ) );
   vector<vec3> vtxNorm( BEFaceMModel::NumVertices, vec3( 0.0f ) );

   // Out root path
   const filesystem::path outRootPath( parser.get<string>( "@outDir" ) );

   // Constant render params
   const float ambient(1.0);
   const vec3 lightPos(0.0);
   const vec3 lightCol = vec3(0.1);

   for ( int s = 0; s < instLst.size(); ++s )
   {
      Mat instImg = cv_utils::imread32FC4( instLst.filePath(s,0) );
      if ( instImg.empty() )
      {
         std::cerr << "Cannot load instance image : " << instLst.filePath(s,0) << std::endl;
         continue;
      }
      imgSz = uvec2( instImg.cols, instImg.rows );

      BEFaceMModelInstance instModel = { instLst.filePath(s,1) };
      if ( !instModel.initialized() )
      {
         std::cerr << "Cannot load instance model : " <<  instLst.filePath(s,1) << std::endl;
         continue;
      }

      // Set the render buffers
      gl_utils::RenderTarget renderTarget( imgSz );
      gl_utils::Texture<gl_utils::RGBA_32FP> faceColorTex( imgSz );
      gl_utils::Texture<gl_utils::RGBA_32FP> faceUVDepthTex( imgSz );
      gl_utils::Texture<gl_utils::RGBA_32FP> faceNormalsTex( imgSz );
      GLuint rTex[3] = {faceColorTex.id, faceUVDepthTex.id, faceNormalsTex.id};

      renderTarget.bind( 3, &rTex[0] );
      glClear( GL_COLOR_BUFFER_BIT );
      glClear( GL_DEPTH_BUFFER_BIT );
      renderTarget.unbind();

      // Load background
      gl_utils::uploadToTexture( faceColorTex, instImg.ptr() );

      // Create the face geometry
      beFaceMMd.get(
          instModel.getShapeCoeffs(),
          instModel.getExpCoeffs(),
          instModel.getTexCoeffs(),
          glm::value_ptr( vecVtx[0] ),
          glm::value_ptr( vtxCol[0] ),
          false );

      gl_utils::TriMeshBuffer mdFaceA;

      // vertices
      mdFaceA.load(
          vecVtx.size(),
          vecVtx.empty() ? nullptr : &vecVtx[0],
          BEFaceMModel::NumFaces,
          beFaceMMd.getFaces() );

      // color
      mdFaceA.loadAttrib( 3, value_ptr( vtxCol[0] ) );

      // normals
      gl_utils::computeNormals(
          BEFaceMModel::NumFaces,
          beFaceMMd.getFaces(),
          BEFaceMModel::NumVertices,
          &vecVtx[0],
          &vtxNorm[0] );
      mdFaceA.loadAttrib( 3, value_ptr( vtxNorm[0] ) );

      // uvs
      mdFaceA.loadAttrib( 2, value_ptr( beFaceMMd.getUVs()[0] ) );

      //  Camera projection
      const mat4 camProj = glm::ortho(0.0f, static_cast<float>(imgSz.x),
        static_cast<float>(imgSz.y), 0.0f, -10000.0f, 10000.0f );

      // Model view
      const mat4 modelView;// = instModel.getPose();

      // Draw the face
      renderTarget.bind( 3, &rTex[0] );

      glEnable( GL_DEPTH_TEST );
      glEnable( GL_CULL_FACE );
      glCullFace( GL_BACK );

      drawFaceModel( mdFaceA, camProj, modelView, lightPos, lightCol, ambient );

      renderTarget.unbind();

      // upload and write the maps
      char sampleId[16];
      sprintf( sampleId, "%08d_", s );
      const string outBasename( sampleId );
      const string outBasenameFull = ( outRootPath / filesystem::path( sampleId ) ).string();

      Mat faceColorImg( faceColorTex.sz.y, faceColorTex.sz.x, CV_32FC4 );
      Mat faceUVDepthImg( faceUVDepthTex.sz.y, faceUVDepthTex.sz.x, CV_32FC4 );
      Mat faceNormalsImg( faceNormalsTex.sz.y, faceNormalsTex.sz.x, CV_32FC4 );
      if ( gl_utils::readbackTexture( faceColorTex, faceColorImg.data ) &&
           gl_utils::readbackTexture( faceUVDepthTex, faceUVDepthImg.data ) &&
           gl_utils::readbackTexture( faceNormalsTex, faceNormalsImg.data ) )
      {
         cvtColor( faceColorImg, faceColorImg, cv::COLOR_RGBA2BGR );
         cvtColor( faceUVDepthImg, faceUVDepthImg, cv::COLOR_RGBA2BGR );
         cvtColor( faceNormalsImg, faceNormalsImg, cv::COLOR_RGBA2BGR );

         imwrite( outBasenameFull + "c.png", faceColorImg * 255.0 );
         imwrite( outBasenameFull + "uvd.exr", faceUVDepthImg );
         imwrite( outBasenameFull + "n.exr", faceNormalsImg );

         std::cout << outBasename + "c.png " << outBasename + "uvd.exr " << outBasename + "n.exr"
                   << std::endl;

         imshow( "color", faceColorImg );
         imshow( "uvdepth", faceUVDepthImg );
         imshow( "normals", faceNormalsImg );
         waitKey( 0 );
      }
   }

   SDL_Quit();

   return ( 0 );
}

ext: cpp

max_stars_repo_name: moennen/sceneIllEst

max_issues_repo_name: moennen/sceneIllEst

max_forks_repo_name: moennen/sceneIllEst


text:
/*
 * Copyright 2012 Open Source Robotics Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
#include <iomanip>
#include <boost/filesystem.hpp>
#include <boost/iostreams/filter/bzip2.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/date_time.hpp>

#include "gazebo/math/Rand.hh"

#include "gazebo/common/Assert.hh"
#include "gazebo/common/Events.hh"
#include "gazebo/common/Time.hh"
#include "gazebo/common/Console.hh"
#include "gazebo/common/Exception.hh"
#include "gazebo/common/LogRecord.hh"

#include "gazebo/gazebo_config.h"

using namespace gazebo;
using namespace common;

/// Convert binary values to base64 characters
typedef boost::archive::iterators::base64_from_binary<
        // retrieve 6 bit integers from a sequence of 8 bit bytes
        boost::archive::iterators::transform_width<const char *, 6, 8> >
        Base64Text;

//////////////////////////////////////////////////
LogRecord::LogRecord()
{
  this->running = false;
  this->paused = false;
  this->initialized = false;
  this->stopThread = false;
  this->firstUpdate = true;

  // Get the user's home directory
  // \todo getenv is not portable, and there is no generic cross-platform
  // method. Must check OS and choose a method
  char *homePath = getenv("HOME");
  GZ_ASSERT(homePath, "HOME environment variable is missing");

  if (!homePath)
    this->logBasePath = boost::filesystem::path("/tmp/gazebo");
  else
    this->logBasePath = boost::filesystem::path(homePath);

  this->logBasePath /= "/.gazebo/log/";

  this->logsEnd = this->logs.end();
}

//////////////////////////////////////////////////
LogRecord::~LogRecord()
{
  // Stop the write thread.
  this->Fini();
}

//////////////////////////////////////////////////
bool LogRecord::Init(const std::string &_subdir)
{
  if (_subdir.empty())
  {
    gzerr << "LogRecord initialization directory is empty." << std::endl;
    return false;
  }

  this->logSubDir = _subdir;

  this->ClearLogs();

  this->initialized = true;
  this->running = false;
  this->paused = false;
  this->stopThread = false;
  this->firstUpdate = true;

  return true;
}

//////////////////////////////////////////////////
bool LogRecord::Start(const std::string &_encoding)
{
  boost::mutex::scoped_lock lock(this->controlMutex);

  // Make sure ::Init has been called.
  if (!this->initialized)
  {
    gzerr << "LogRecord has not been initialized." << std::endl;
    return false;
  }

  // Check to see if the logger is already started.
  if (this->running)
  {
    /// \TODO replace this with gzlog
    gzerr << "LogRecord has already been started" << std::endl;
    return false;
  }

  // Get the current time as an ISO string.
  std::string logTimeDir = common::Time::GetWallTimeAsISOString();

  this->logCompletePath = this->logBasePath / logTimeDir / this->logSubDir;

  // Create the log directory if necessary
  if (!boost::filesystem::exists(this->logCompletePath))
    boost::filesystem::create_directories(logCompletePath);

  if (_encoding != "bz2" && _encoding != "txt")
    gzthrow("Invalid log encoding[" + _encoding +
            "]. Must be one of [bz2, txt]");

  this->encoding = _encoding;

  {
    boost::mutex::scoped_lock logLock(this->writeMutex);
    this->logsEnd = this->logs.end();

    // Start all the logs
    for (Log_M::iterator iter = this->logs.begin();
         iter != this->logsEnd; ++iter)
      iter->second->Start(logCompletePath);
  }

  // Listen to the world update event
  this->updateConnection = event::Events::ConnectWorldUpdateBegin(
        boost::bind(&LogRecord::Update, this, _1));

  // Start the writing thread if it has not already been started
  if (!this->writeThread)
    this->writeThread = new boost::thread(boost::bind(&LogRecord::Run, this));

  this->running = true;
  this->paused = false;
  this->firstUpdate = true;

  this->startTime = this->currTime = common::Time();

  return true;
}

//////////////////////////////////////////////////
const std::string &LogRecord::GetEncoding() const
{
  return this->encoding;
}

//////////////////////////////////////////////////
void LogRecord::Fini()
{
  this->stopThread = true;

  this->Stop();

  // Wait for the write thread, if it exists
  if (this->writeThread)
    this->writeThread->join();
  delete this->writeThread;
  this->writeThread = NULL;
}

//////////////////////////////////////////////////
void LogRecord::Stop()
{
  boost::mutex::scoped_lock lock(this->controlMutex);

  // Disconnect from the world update signale
  if (this->updateConnection)
    event::Events::DisconnectWorldUpdateBegin(this->updateConnection);
  this->updateConnection.reset();

  // Kick the write thread
  this->dataAvailableCondition.notify_one();

  // Remove all the logs.
  this->ClearLogs();

  // Reset the times
  this->startTime = this->currTime = common::Time();

  // Reset the flags
  this->running = false;
  this->paused = false;
}

//////////////////////////////////////////////////
void LogRecord::ClearLogs()
{
  boost::mutex::scoped_lock logLock(this->writeMutex);

  // Delete all the log objects
  for (Log_M::iterator iter = this->logs.begin();
      iter != this->logs.end(); ++iter)
  {
    delete iter->second;
  }

  this->logs.clear();
  this->logsEnd = this->logs.end();
}

//////////////////////////////////////////////////
void LogRecord::SetPaused(bool _paused)
{
  this->paused = _paused;
}

//////////////////////////////////////////////////
bool LogRecord::GetPaused() const
{
  return this->paused;
}

//////////////////////////////////////////////////
bool LogRecord::GetRunning() const
{
  return this->running;
}

//////////////////////////////////////////////////
void LogRecord::Add(const std::string &_name, const std::string &_filename,
                    boost::function<bool (std::ostringstream &)> _logCallback)
{
  boost::mutex::scoped_lock logLock(this->writeMutex);

  // Check to see if the log has already been added.
  if (this->logs.find(_name) != this->logs.end())
  {
    /// \todo Good place to use GZ_ASSERT
    /// GZ_ASSERT(this->logs.find(_name)->second != NULL);

    if (this->logs.find(_name)->second->GetRelativeFilename() != _filename)
    {
      gzthrow(std::string("Attempting to add a duplicate log object named[")
          + _name + "] with a filename of [" + _filename + "]\n");
    }
    else
    {
      return;
    }
  }

  LogRecord::Log *newLog;

  // Create a new log object
  try
  {
    newLog = new LogRecord::Log(this, _filename, _logCallback);
  }
  catch(...)
  {
    gzthrow("Unable to create log. File permissions are probably bad.");
  }

  if (this->running)
    newLog->Start(this->logCompletePath);

  // Add the log to our map
  this->logs[_name] = newLog;

  // Update the pointer to the end of the log objects list.
  this->logsEnd = this->logs.end();
}

//////////////////////////////////////////////////
bool LogRecord::Remove(const std::string &_name)
{
  boost::mutex::scoped_lock logLock(this->writeMutex);

  bool result = false;

  Log_M::iterator iter = this->logs.find(_name);
  if (iter != this->logs.end())
  {
    delete iter->second;
    this->logs.erase(iter);

    // Update the pointer to the end of the log objects list.
    this->logsEnd = this->logs.end();

    result = true;
  }

  return result;
}

//////////////////////////////////////////////////
std::string LogRecord::GetFilename(const std::string &_name) const
{
  boost::mutex::scoped_lock logLock(this->writeMutex);

  std::string result;

  Log_M::const_iterator iter = this->logs.find(_name);
  if (iter != this->logs.end())
  {
    /// \TODO GZ_ASSERT(iter->second);
    result = iter->second->GetCompleteFilename();
  }

  return result;
}

//////////////////////////////////////////////////
unsigned int LogRecord::GetFileSize(const std::string &_name) const
{
  unsigned int result = 0;

  // Get the filename of the specified log object;
  std::string filename = this->GetFilename(_name);

  // Get the size of the log file on disk.
  if (!filename.empty())
  {
    // Get the size of the file
    if (!filename.empty() && boost::filesystem::exists(filename))
      result = boost::filesystem::file_size(filename);
  }

  // Add in the contents of the write buffer. This is the data that will be
  // written to disk soon.
  {
    boost::mutex::scoped_lock lock(this->writeMutex);
    Log_M::const_iterator iter = this->logs.find(_name);

    if (iter != this->logs.end())
    {
      GZ_ASSERT(iter->second, "Log object is NULL");
      result += iter->second->GetBufferSize();
    }
  }

  return result;
}

//////////////////////////////////////////////////
void LogRecord::SetBasePath(const std::string &_path)
{
  // Make sure the  directory exists
  if (!boost::filesystem::exists(_path))
    boost::filesystem::create_directories(_path);

  // Make sure we have a directory
  if (!boost::filesystem::is_directory(_path))
  {
    gzerr << "Path " << _path << " is not a directory. Please only specify a "
           << "directory for data logging.\n";
    return;
  }

  // Make sure the path is writable.
  // Note: This is not cross-platform compatible.
  if (access(_path.c_str(), W_OK) != 0)
  {
    gzerr << "You do no have permission to write into " << _path << "\n";
    return;
  }

  this->logBasePath = _path;
}

//////////////////////////////////////////////////
std::string LogRecord::GetBasePath() const
{
  return this->logBasePath.string();
}

//////////////////////////////////////////////////
bool LogRecord::GetFirstUpdate() const
{
  return this->firstUpdate;
}

//////////////////////////////////////////////////
void LogRecord::Update(const common::UpdateInfo &_info)
{
  if (!this->paused)
  {
    unsigned int size = 0;

    {
      boost::mutex::scoped_lock lock(this->writeMutex);

      // Collect all the new log data. This will not write data to disk.
      for (this->updateIter = this->logs.begin();
          this->updateIter != this->logsEnd; ++this->updateIter)
      {
        size += this->updateIter->second->Update();
      }
    }

    if (this->firstUpdate)
    {
      this->firstUpdate = false;
      this->startTime = _info.simTime;
    }

    // Signal that new data is available.
    if (size > 0)
      this->dataAvailableCondition.notify_one();

    this->currTime = _info.simTime;
  }
}

//////////////////////////////////////////////////
void LogRecord::Run()
{
  if (!this->running)
    gzerr << "Running LogRecord before it has been started." << std::endl;

  this->stopThread = false;

  // This loop will write data to disk.
  while (!this->stopThread)
  {
    {
      // Wait for new data.
      boost::mutex::scoped_lock lock(this->writeMutex);
      this->dataAvailableCondition.wait(lock);

      // Collect all the new log data.
      for (this->updateIter = this->logs.begin();
           this->updateIter != this->logsEnd; ++this->updateIter)
      {
        this->updateIter->second->Write();
      }
    }

    // Throttle the write loop.
    common::Time::MSleep(1000);
  }
}

//////////////////////////////////////////////////
common::Time LogRecord::GetRunTime() const
{
  return this->currTime - this->startTime;
}

//////////////////////////////////////////////////
LogRecord::Log::Log(LogRecord *_parent, const std::string &_relativeFilename,
                 boost::function<bool (std::ostringstream &)> _logCB)
{
  this->parent = _parent;
  this->logCB = _logCB;

  this->relativeFilename = _relativeFilename;
  std::ostringstream stream;
  stream << "<?xml version='1.0'?>\n"
         << "<gazebo_log>\n"
         << "<header>\n"
         << "<log_version>" << GZ_LOG_VERSION << "</log_version>\n"
         << "<gazebo_version>" << GAZEBO_VERSION_FULL << "</gazebo_version>\n"
         << "<rand_seed>" << math::Rand::GetSeed() << "</rand_seed>\n"
         << "</header>\n";

  this->buffer.append(stream.str());
}

//////////////////////////////////////////////////
LogRecord::Log::~Log()
{
  std::string xmlEnd = "</gazebo_log>";
  this->logFile.write(xmlEnd.c_str(), xmlEnd.size());

  this->logFile.close();
}

//////////////////////////////////////////////////
unsigned int LogRecord::Log::Update()
{
  std::ostringstream stream;

  // Get log data via the callback.
  if (this->logCB(stream) && !stream.str().empty())
  {
    const std::string encoding = this->parent->GetEncoding();

    this->buffer.append("<chunk encoding='");
    this->buffer.append(encoding);
    this->buffer.append("'>\n");

    this->buffer.append("<![CDATA[");
    {
      // Compress the data.
      if (encoding == "bz2")
      {
        std::string str;

        // Compress to bzip2
        {
          boost::iostreams::filtering_ostream out;
          out.push(boost::iostreams::bzip2_compressor());
          out.push(std::back_inserter(str));
          out << stream.str();
          out.flush();
        }

        // Encode in base64.
        std::copy(Base64Text(str.c_str()),
                  Base64Text(str.c_str() + str.size()),
                  std::back_inserter(this->buffer));
      }
      else if (encoding == "txt")
        this->buffer.append(stream.str());
      else
        gzerr << "Unknown log file encoding[" << encoding << "]\n";
    }
    this->buffer.append("]]>\n");

    this->buffer.append("</chunk>\n");
  }

  return this->buffer.size();
}

//////////////////////////////////////////////////
void LogRecord::Log::ClearBuffer()
{
  this->buffer.clear();
}

//////////////////////////////////////////////////
unsigned int LogRecord::Log::GetBufferSize()
{
  return this->buffer.size();
}

//////////////////////////////////////////////////
std::string LogRecord::Log::GetRelativeFilename() const
{
  return this->relativeFilename;
}

//////////////////////////////////////////////////
std::string LogRecord::Log::GetCompleteFilename() const
{
  return this->completePath.string();
}

//////////////////////////////////////////////////
void LogRecord::Log::Start(const boost::filesystem::path &_path)
{
  // Make the full path for the log file
  this->completePath = _path / this->relativeFilename;

  // Make sure the file does not exist
  if (boost::filesystem::exists(this->completePath))
    gzthrow("Filename[" + this->completePath.string() + "], already exists\n");
}

//////////////////////////////////////////////////
void LogRecord::Log::Write()
{
  // Make sure the file is open for writing
  if (!this->logFile.is_open())
  {
    // Try to open it...
    this->logFile.open(this->completePath.string().c_str(),
                       std::fstream::out | std::ios::binary);

    // Throw an error if we couldn't open the file for writing.
    if (!this->logFile.is_open())
      gzthrow("Unable to open file for logging:" +
              this->completePath.string() + "]");
  }

  // Check to see if the log file still exists on disk. This will catch the
  // case when someone deletes a log file while recording.
  if (!boost::filesystem::exists(this->completePath.string().c_str()))
  {
    gzerr << "Log file[" << this->completePath << "] no longer exists. "
          << "Unable to write log data.\n";

    // We have to clear the buffer, or else it may grow indefinitely.
    this->buffer.clear();
    return;
  }

  // Write out the contents of the buffer.
  this->logFile.write(this->buffer.c_str(), this->buffer.size());
  this->logFile.flush();

  // Clear the buffer.
  this->buffer.clear();
}

ext: cc

max_stars_repo_name: thomas-moulard/gazebo-deb

max_issues_repo_name: thomas-moulard/gazebo-deb

max_forks_repo_name: thomas-moulard/gazebo-deb


text:
/**
 * @file sparse_coding_test.cpp
 *
 * Test for Sparse Coding
 */

// Note: We don't use BOOST_REQUIRE_CLOSE in the code below because we need
// to use FPC_WEAK, and it's not at all intuitive how to do that.

#include <mlpack/core.hpp>
#include <mlpack/methods/sparse_coding/sparse_coding.hpp>

#include <boost/test/unit_test.hpp>
#include "old_boost_test_definitions.hpp"

using namespace arma;
using namespace mlpack;
using namespace mlpack::regression;
using namespace mlpack::sparse_coding;

BOOST_AUTO_TEST_SUITE(SparseCodingTest);

void SCVerifyCorrectness(vec beta, vec errCorr, double lambda)
{
  const double tol = 1e-12;
  size_t nDims = beta.n_elem;
  for(size_t j = 0; j < nDims; j++)
  {
    if (beta(j) == 0)
    {
      // Make sure that errCorr(j) <= lambda.
      BOOST_REQUIRE_SMALL(std::max(fabs(errCorr(j)) - lambda, 0.0), tol);
    }
    else if (beta(j) < 0)
    {
      // Make sure that errCorr(j) == lambda.
      BOOST_REQUIRE_SMALL(errCorr(j) - lambda, tol);
    }
    else // beta(j) > 0.
    {
      // Make sure that errCorr(j) == -lambda.
      BOOST_REQUIRE_SMALL(errCorr(j) + lambda, tol);
    }
  }
}

BOOST_AUTO_TEST_CASE(SparseCodingTestCodingStepLasso)
{
  double lambda1 = 0.1;
  uword nAtoms = 25;

  mat X;
  X.load("mnist_first250_training_4s_and_9s.arm");
  uword nPoints = X.n_cols;

  // Normalize each point since these are images.
  for (uword i = 0; i < nPoints; ++i) {
    X.col(i) /= norm(X.col(i), 2);
  }

  SparseCoding<> sc(X, nAtoms, lambda1);
  sc.OptimizeCode();

  mat D = sc.Dictionary();
  mat Z = sc.Codes();

  for (uword i = 0; i < nPoints; ++i)
  {
    vec errCorr = trans(D) * (D * Z.unsafe_col(i) - X.unsafe_col(i));
    SCVerifyCorrectness(Z.unsafe_col(i), errCorr, lambda1);
  }
}

BOOST_AUTO_TEST_CASE(SparseCodingTestCodingStepElasticNet)
{
  double lambda1 = 0.1;
  double lambda2 = 0.2;
  uword nAtoms = 25;

  mat X;
  X.load("mnist_first250_training_4s_and_9s.arm");
  uword nPoints = X.n_cols;

  // Normalize each point since these are images.
  for (uword i = 0; i < nPoints; ++i)
    X.col(i) /= norm(X.col(i), 2);

  SparseCoding<> sc(X, nAtoms, lambda1, lambda2);
  sc.OptimizeCode();

  mat D = sc.Dictionary();
  mat Z = sc.Codes();

  for(uword i = 0; i < nPoints; ++i)
  {
    vec errCorr =
      (trans(D) * D + lambda2 * eye(nAtoms, nAtoms)) * Z.unsafe_col(i)
      - trans(D) * X.unsafe_col(i);

    SCVerifyCorrectness(Z.unsafe_col(i), errCorr, lambda1);
  }
}

BOOST_AUTO_TEST_CASE(SparseCodingTestDictionaryStep)
{
  const double tol = 1e-6;

  double lambda1 = 0.1;
  uword nAtoms = 25;

  mat X;
  X.load("mnist_first250_training_4s_and_9s.arm");
  uword nPoints = X.n_cols;

  // Normalize each point since these are images.
  for (uword i = 0; i < nPoints; ++i)
    X.col(i) /= norm(X.col(i), 2);

  SparseCoding<> sc(X, nAtoms, lambda1);
  sc.OptimizeCode();

  mat D = sc.Dictionary();
  mat Z = sc.Codes();

  uvec adjacencies = find(Z);
  double normGradient = sc.OptimizeDictionary(adjacencies, 1e-15);

  BOOST_REQUIRE_SMALL(normGradient, tol);
}

BOOST_AUTO_TEST_SUITE_END();

max_stars_repo_name: vj-ug/Contribution-to-mlpack

max_issues_repo_name: vj-ug/Contribution-to-mlpack

max_forks_repo_name: vj-ug/Contribution-to-mlpack


text:
#ifndef BOOST_CERTIFY_EXTENSIONS_HPP
#define BOOST_CERTIFY_EXTENSIONS_HPP

#include <boost/certify/detail/config.hpp>

#include <boost/asio/ssl/stream.hpp>
#include <boost/utility/string_view.hpp>

namespace boost
{
namespace certify
{

template<class AsyncStream>
string_view
sni_hostname(asio::ssl::stream<AsyncStream> const& stream);

template<class AsyncStream>
void
sni_hostname(asio::ssl::stream<AsyncStream>& stream,
             std::string const& hostname,
             system::error_code& ec);

template<class AsyncStream>
void
sni_hostname(asio::ssl::stream<AsyncStream>& stream,
             std::string const& hostname);

} // namespace certify
} // namespace boost

#include <boost/certify/impl/extensions.hpp>
#endif // BOOST_CERTIFY_EXTENSIONS_HPP

max_stars_repo_name: djarek/tlsverify

max_issues_repo_name: djarek/tlsverify

max_forks_repo_name: djarek/tlsverify


text:
#include "WordsApiKeyFileReader.h"

#include "gtest/gtest.h"

#include "utils/FileAccessMock.h"

#include "utils/GetProjectPath.h"
#include <boost/optional/optional_io.hpp>

using namespace ::testing;
using namespace glossary::wordDescriptionService;

namespace
{
const std::string filePathWithPathToFileWithApiKey{utils::getProjectPath("glossary") +
                                                   "config/wordsApiKeyLocation.txt"};
const std::string invalidFilePathWithApiKey{"home/invalidApiKeyFilePath.txt"};
const std::string validFilePathWithApiKey{"home/validApiKeyFilePath.txt"};
const std::string exampleApiKey{"apiKey"};
}

class WordsApiKeyFileReaderTest : public Test
{
public:
    std::shared_ptr<utils::FileAccessMock> fileAccess = std::make_shared<StrictMock<utils::FileAccessMock>>();
    WordsApiKeyFileReader apiKeyFileReader{fileAccess};
};

TEST_F(WordsApiKeyFileReaderTest, configFileWithPathToFileWithApiKeyNotExists_shouldReturnNone)
{
    EXPECT_CALL(*fileAccess, exists(filePathWithPathToFileWithApiKey)).WillOnce(Return(false));

    const auto actualApiKey = apiKeyFileReader.readApiKey();

    ASSERT_EQ(actualApiKey, boost::none);
}

TEST_F(WordsApiKeyFileReaderTest,
       configFileWithPathToFileWithApiKeyExists_filePathWithApiKeyNotExists_shouldReturnNone)
{
    EXPECT_CALL(*fileAccess, exists(filePathWithPathToFileWithApiKey)).WillOnce(Return(true));
    EXPECT_CALL(*fileAccess, readContent(filePathWithPathToFileWithApiKey))
        .WillOnce(Return(invalidFilePathWithApiKey));
    EXPECT_CALL(*fileAccess, exists(invalidFilePathWithApiKey)).WillOnce(Return(false));

    const auto actualApiKey = apiKeyFileReader.readApiKey();

    ASSERT_EQ(actualApiKey, boost::none);
}

TEST_F(WordsApiKeyFileReaderTest,
       configFileWithPathToFileWithApiKeyExists_filePathWithApiKeyExists_shouldReturnApiKey)
{
    EXPECT_CALL(*fileAccess, exists(filePathWithPathToFileWithApiKey)).WillOnce(Return(true));
    EXPECT_CALL(*fileAccess, readContent(filePathWithPathToFileWithApiKey))
        .WillOnce(Return(validFilePathWithApiKey));
    EXPECT_CALL(*fileAccess, exists(validFilePathWithApiKey)).WillOnce(Return(true));
    EXPECT_CALL(*fileAccess, readContent(validFilePathWithApiKey)).WillOnce(Return(exampleApiKey));

    const auto actualApiKey = apiKeyFileReader.readApiKey();

    ASSERT_EQ(*actualApiKey, exampleApiKey);
}

max_stars_repo_name: michalovsky/Glossary

max_issues_repo_name: michalovsky/Glossary

max_forks_repo_name: michalovsky/Glossary


text:
#define BOOST_TEST_MODULE "csvtoolstests"
#include <boost/test/unit_test.hpp>

max_stars_repo_name: SuRaMoN/csvtools

max_issues_repo_name: SuRaMoN/csvtools

max_forks_repo_name: SuRaMoN/csvtools


text:
//
// http_read_stream.hpp
// ~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2009 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// 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)
//

#ifndef URDL_DETAIL_HTTP_READ_STREAM_HPP
#define URDL_DETAIL_HTTP_READ_STREAM_HPP

#include <boost/asio/buffer.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/asio/streambuf.hpp>
#include <boost/asio/read.hpp>
#include <boost/asio/read_until.hpp>
#include <boost/asio/write.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/detail/bind_handler.hpp>
#include <algorithm>
#include <ostream>
#include <iterator>
#include "urdl/http.hpp"
#include "urdl/option_set.hpp"
#include "urdl/url.hpp"
#include "urdl/detail/connect.hpp"
#include "urdl/detail/coroutine.hpp"
#include "urdl/detail/handshake.hpp"
#include "urdl/detail/parsers.hpp"

#include "urdl/detail/abi_prefix.hpp"

namespace urdl {
namespace detail {

template <typename Stream>
class http_read_stream
{
public:
  explicit http_read_stream(boost::asio::io_service& io_service,
      option_set& options)
    : resolver_(io_service),
      socket_(io_service),
      options_(options),
      content_length_(0)
  {
  }

  template <typename Arg>
  http_read_stream(boost::asio::io_service& io_service,
      option_set& options, Arg& arg)
    : resolver_(io_service),
      socket_(io_service, arg),
      options_(options),
      content_length_(0)
  {
  }

  boost::system::error_code open(const url& u, boost::system::error_code& ec)
  {
    // Fail if the socket is already open.
    if (socket_.lowest_layer().is_open())
    {
      ec = boost::asio::error::already_open;
      return ec;
    }

    // Establish a connection to the HTTP server.
    connect(socket_.lowest_layer(), resolver_, u, ec);
    if (ec)
      return ec;

    // Perform SSL handshake if required.
    handshake(socket_, u.host(), ec);
    if (ec)
      return ec;

    // Get the HTTP options used to build the request.
    std::string request_method
      = options_.get_option<urdl::http::request_method>().value();
    std::string request_content
      = options_.get_option<urdl::http::request_content>().value();
    std::string request_content_type
      = options_.get_option<urdl::http::request_content_type>().value();
    std::string user_agent
      = options_.get_option<urdl::http::user_agent>().value();

    // Form the request. We specify the "Connection: close" header so that the
    // server will close the socket after transmitting the response. This will
    // allow us to treat all data up until the EOF as the content.
    std::ostream request_stream(&request_buffer_);
    request_stream << request_method << " ";
    request_stream << u.to_string(url::path_component | url::query_component);
    request_stream << " HTTP/1.0\r\n";
    request_stream << "Host: ";
    request_stream << u.to_string(url::host_component | url::port_component);
    request_stream << "\r\n";
    request_stream << "Accept: */*\r\n";
    if (request_content.length())
    {
      request_stream << "Content-Length: ";
      request_stream << request_content.length() << "\r\n";
      if (request_content_type.length())
      {
        request_stream << "Content-Type: ";
        request_stream << request_content_type << "\r\n";
      }
    }
    if (user_agent.length())
      request_stream << "User-Agent: " << user_agent << "\r\n";
    request_stream << "Connection: close\r\n\r\n";
    request_stream << request_content;

    // Send the request.
    boost::asio::write(socket_, request_buffer_,
        boost::asio::transfer_all(), ec);
    if (ec)
      return ec;

    int status_code = 0;
    for (;;)
    {
      // Read the reply status line.
      boost::asio::read_until(socket_, reply_buffer_, "\r\n", ec);
      if (ec)
        return ec;

      // Extract the response code from the status line.
      int version_major = 0;
      int version_minor = 0;
      if (!parse_http_status_line(
            std::istreambuf_iterator<char>(&reply_buffer_),
            std::istreambuf_iterator<char>(),
            version_major, version_minor, status_code))
      {
        ec = http::errc::malformed_status_line;
        return ec;
      }

      // A "continue" header means we need to keep waiting.
      if (status_code != http::errc::continue_request)
        break;
    }

    // Read list of headers and save them. If there's anything left in the reply
    // buffer afterwards, it's the start of the content returned by the HTTP
    // server.
    std::size_t bytes_transferred = boost::asio::read_until(
        socket_, reply_buffer_, "\r\n\r\n", ec);
    headers_.resize(bytes_transferred);
    reply_buffer_.sgetn(&headers_[0], bytes_transferred);
    if (ec)
      return ec;

    // Parse the headers to get Content-Type and Content-Length.
    if (!parse_http_headers(headers_.begin(), headers_.end(),
          content_type_, content_length_, location_))
    {
      ec = http::errc::malformed_response_headers;
      return ec;
    }

    // Check the response code to see if we got the page correctly.
    if (status_code != http::errc::ok)
      ec = make_error_code(static_cast<http::errc::errc_t>(status_code));

    return ec;
  }

  template <typename Handler>
  class open_coro : coroutine
  {
  public:
    open_coro(Handler handler, boost::asio::ip::tcp::resolver& resolver,
        Stream& socket, const option_set& options,
        boost::asio::streambuf& request_buffer,
        boost::asio::streambuf& reply_buffer, const url& u,
        std::string& headers, std::string& content_type,
        std::size_t& content_length, std::string& location)
      : handler_(handler),
        resolver_(resolver),
        socket_(socket),
        options_(options),
        request_buffer_(request_buffer),
        reply_buffer_(reply_buffer),
        url_(u),
        headers_(headers),
        status_code_(0),
        content_type_(content_type),
        content_length_(content_length),
        location_(location)
    {
    }

    void operator()(boost::system::error_code ec,
        std::size_t bytes_transferred = 0)
    {
      URDL_CORO_BEGIN;

      // Fail if the socket is already open.
      if (socket_.lowest_layer().is_open())
      {
        ec = boost::asio::error::already_open;
        URDL_CORO_YIELD(socket_.get_io_service().post(
              boost::asio::detail::bind_handler(*this, ec)));
        handler_(ec);
        return;
      }

      // Establish a connection to the HTTP server.
      URDL_CORO_YIELD(async_connect(socket_.lowest_layer(),
            resolver_, url_, *this));
      if (ec)
      {
        handler_(ec);
        return;
      }

      // Perform SSL handshake if required.
      URDL_CORO_YIELD(async_handshake(socket_, url_.host(), *this));
      if (ec)
      {
        handler_(ec);
        return;
      }

      {
        // Get the HTTP options used to build the request.
        std::string request_method
          = options_.get_option<urdl::http::request_method>().value();
        std::string request_content
          = options_.get_option<urdl::http::request_content>().value();
        std::string request_content_type
          = options_.get_option<urdl::http::request_content_type>().value();
        std::string user_agent
          = options_.get_option<urdl::http::user_agent>().value();

        // Form the request. We specify the "Connection: close" header so that
        // the server will close the socket after transmitting the response.
        // This will allow us to treat all data up until the EOF as the
        // content.
        std::ostream request_stream(&request_buffer_);
        request_stream << request_method << " ";
        request_stream << url_.to_string(
            url::path_component | url::query_component);
        request_stream << " HTTP/1.0\r\n";
        request_stream << "Host: ";
        request_stream << url_.to_string(
            url::host_component | url::port_component);
        request_stream << "\r\n";
        request_stream << "Accept: */*\r\n";
        if (request_content.length())
        {
          request_stream << "Content-Length: ";
          request_stream << request_content.length() << "\r\n";
          if (request_content_type.length())
          {
            request_stream << "Content-Type: ";
            request_stream << request_content_type << "\r\n";
          }
        }
        if (user_agent.length())
          request_stream << "User-Agent: " << user_agent << "\r\n";
        request_stream << "Connection: close\r\n\r\n";
        request_stream << request_content;
      }

      // Send the request.
      URDL_CORO_YIELD(boost::asio::async_write(socket_,
            request_buffer_, boost::asio::transfer_all(), *this));
      if (ec)
      {
        handler_(ec);
        return;
      }

      for (;;)
      {
        // Read the reply status line.
        URDL_CORO_YIELD(boost::asio::async_read_until(socket_,
              reply_buffer_, "\r\n", *this));
        if (ec)
        {
          handler_(ec);
          return;
        }

        // Check the response code to see if we got the page correctly.
        {
          int version_major = 0;
          int version_minor = 0;
          if (!parse_http_status_line(
                std::istreambuf_iterator<char>(&reply_buffer_),
                std::istreambuf_iterator<char>(),
                version_major, version_minor, status_code_))
          {
            ec = http::errc::malformed_status_line;
            handler_(ec);
            return;
          }
        }

        // A "continue" header means we need to keep waiting.
        if (status_code_ != http::errc::continue_request)
          break;
      }

      // Read list of headers and save them. If there's anything left in the
      // reply buffer afterwards, it's the start of the content returned by the
      // HTTP server.
      URDL_CORO_YIELD(boost::asio::async_read_until(socket_,
            reply_buffer_, "\r\n\r\n", *this));
      headers_.resize(bytes_transferred);
      reply_buffer_.sgetn(&headers_[0], bytes_transferred);
      if (ec)
      {
        handler_(ec);
        return;
      }

      // Parse the headers to get Content-Type and Content-Length.
      if (!parse_http_headers(headers_.begin(), headers_.end(),
            content_type_, content_length_, location_))
      {
        ec = http::errc::malformed_response_headers;
        handler_(ec);
        return;
      }

      // Check the response code to see if we got the page correctly.
      if (status_code_ != http::errc::ok)
        ec = make_error_code(static_cast<http::errc::errc_t>(status_code_));

      handler_(ec);

      URDL_CORO_END;
    }

    friend void* asio_handler_allocate(std::size_t size,
        open_coro<Handler>* this_handler)
    {
      using boost::asio::asio_handler_allocate;
      return asio_handler_allocate(size, &this_handler->handler_);
    }

    friend void asio_handler_deallocate(void* pointer, std::size_t size,
        open_coro<Handler>* this_handler)
    {
      using boost::asio::asio_handler_deallocate;
      asio_handler_deallocate(pointer, size, &this_handler->handler_);
    }

    template <typename Function>
    friend void asio_handler_invoke(const Function& function,
        open_coro<Handler>* this_handler)
    {
      using boost::asio::asio_handler_invoke;
      asio_handler_invoke(function, &this_handler->handler_);
    }

  private:
    Handler handler_;
    boost::asio::ip::tcp::resolver& resolver_;
    Stream& socket_;
    const option_set& options_;
    boost::asio::streambuf& request_buffer_;
    boost::asio::streambuf& reply_buffer_;
    url url_;
    std::string& headers_;
    int status_code_;
    std::string& content_type_;
    std::size_t& content_length_;
    std::string& location_;
  };

  template <typename Handler>
  void async_open(const url& u, Handler handler)
  {
    open_coro<Handler>(handler, resolver_, socket_, options_, request_buffer_,
        reply_buffer_, u, headers_, content_type_, content_length_, location_)(
          boost::system::error_code(), 0);
  }

  boost::system::error_code close(boost::system::error_code& ec)
  {
    resolver_.cancel();
    if (!socket_.lowest_layer().close(ec))
    {
      request_buffer_.consume(request_buffer_.size());
      reply_buffer_.consume(reply_buffer_.size());
      headers_.clear();
      content_type_.clear();
      content_length_ = 0;
      location_.clear();
    }
    return ec;
  }

  bool is_open() const
  {
    return socket_.lowest_layer().is_open();
  }

  std::string content_type() const
  {
    return content_type_;
  }

  std::size_t content_length() const
  {
    return content_length_;
  }

  std::string location() const
  {
    return location_;
  }

  std::string headers() const
  {
    return headers_;
  }

  template <typename MutableBufferSequence>
  std::size_t read_some(const MutableBufferSequence& buffers,
      boost::system::error_code& ec)
  {
    // If we have any data in the reply_buffer_, return that first.
    if (reply_buffer_.size() > 0)
    {
      std::size_t bytes_transferred = 0;
      typename MutableBufferSequence::const_iterator iter = buffers.begin();
      typename MutableBufferSequence::const_iterator end = buffers.end();
      for (; iter != end && reply_buffer_.size() > 0; ++iter)
      {
        boost::asio::mutable_buffer buffer(*iter);
        size_t length = boost::asio::buffer_size(buffer);
        if (length > 0)
        {
          bytes_transferred += reply_buffer_.sgetn(
              boost::asio::buffer_cast<char*>(buffer), length);
        }
      }
      ec = boost::system::error_code();
      return bytes_transferred;
    }

    // Otherwise we forward the call to the underlying socket.
    std::size_t bytes_transferred = socket_.read_some(buffers, ec);
    if (ec == boost::asio::error::shut_down)
      ec = boost::asio::error::eof;
    return bytes_transferred;
  }

  template <typename Handler>
  class read_handler
  {
  public:
    read_handler(Handler handler)
      : handler_(handler)
    {
    }

    void operator()(boost::system::error_code ec, std::size_t bytes_transferred)
    {
      if (ec == boost::asio::error::shut_down)
        ec = boost::asio::error::eof;
      handler_(ec, bytes_transferred);
    }

    friend void* asio_handler_allocate(std::size_t size,
        read_handler<Handler>* this_handler)
    {
      using boost::asio::asio_handler_allocate;
      return asio_handler_allocate(size, &this_handler->handler_);
    }

    friend void asio_handler_deallocate(void* pointer, std::size_t size,
        read_handler<Handler>* this_handler)
    {
      using boost::asio::asio_handler_deallocate;
      asio_handler_deallocate(pointer, size, &this_handler->handler_);
    }

    template <typename Function>
    friend void asio_handler_invoke(const Function& function,
        read_handler<Handler>* this_handler)
    {
      using boost::asio::asio_handler_invoke;
      asio_handler_invoke(function, &this_handler->handler_);
    }

  private:
    Handler handler_;
  };

  template <typename MutableBufferSequence, typename Handler>
  void async_read_some(const MutableBufferSequence& buffers, Handler handler)
  {
    // If we have any data in the reply_buffer_, return that first.
    if (reply_buffer_.size() > 0)
    {
      boost::system::error_code ec;
      std::size_t bytes_transferred = read_some(buffers, ec);
      socket_.get_io_service().post(boost::asio::detail::bind_handler(
            handler, ec, bytes_transferred));
      return;
    }

    // Otherwise we forward the call to the underlying socket.
    socket_.async_read_some(buffers, read_handler<Handler>(handler));
  }

private:
  boost::asio::ip::tcp::resolver resolver_;
  Stream socket_;
  option_set& options_;
  boost::asio::streambuf request_buffer_;
  boost::asio::streambuf reply_buffer_;
  std::string headers_;
  std::string content_type_;
  std::size_t content_length_;
  std::string location_;
};

} // namespace detail
} // namespace urdl

#include "urdl/detail/abi_suffix.hpp"

#endif // URDL_DETAIL_HTTP_READ_STREAM_HPP


text:
/**
 * itmx: SemanticMaskingImageSourceEngine.cpp
 * Copyright (c) Torr Vision Group, University of Oxford, 2019. All rights reserved.
 */

#include "imagesources/SemanticMaskingImageSourceEngine.h"
using namespace ITMLib;

#include <boost/assign/list_of.hpp>

namespace itmx {

//#################### CONSTRUCTORS ####################

SemanticMaskingImageSourceEngine::SemanticMaskingImageSourceEngine(ImageSourceEngine *normalSource, ImageSourceEngine *semanticSource, MaskingType maskingType,
                                                                   const std::set<std::string>& labelsToMask, const std::string& labelSet)
: m_maskingType(maskingType), m_normalSource(normalSource), m_semanticSource(semanticSource)
{
  // Construct a map from semantic labels to colours.
  // TODO: We should allow other label sets to be used as well.
  if(labelSet == "cityscapes")
  {
    // See: https://github.com/mcordts/cityscapesScripts/blob/master/cityscapesscripts/helpers/labels.py
    m_labelToColourMap = boost::assign::map_list_of
      ("unlabeled",            Vector3u(0,0,0))
      ("ego vehicle",          Vector3u(0,0,0))
      ("rectification border", Vector3u(0,0,0))
      ("out of roi",           Vector3u(0,0,0))
      ("static",               Vector3u(0,0,0))
      ("dynamic",              Vector3u(111,74,0))
      ("ground",               Vector3u(81,0,81))
      ("road",                 Vector3u(128,64,128))
      ("sidewalk",             Vector3u(244,35,232))
      ("parking",              Vector3u(250,170,160))
      ("rail track",           Vector3u(230,150,140))
      ("building",             Vector3u(70,70,70))
      ("wall",                 Vector3u(102,102,156))
      ("fence",                Vector3u(190,153,153))
      ("guard rail",           Vector3u(180,165,180))
      ("bridge",               Vector3u(150,100,100))
      ("tunnel",               Vector3u(150,120,90))
      ("pole",                 Vector3u(153,153,153))
      ("polegroup",            Vector3u(153,153,153))
      ("traffic light",        Vector3u(250,170,30))
      ("traffic sign",         Vector3u(220,220,0))
      ("vegetation",           Vector3u(107,142,35))
      ("terrain",              Vector3u(152,251,152))
      ("sky",                  Vector3u(70,130,180))
      ("person",               Vector3u(220,20,60))
      ("rider",                Vector3u(255,0,0))
      ("car",                  Vector3u(0,0,142))
      ("truck",                Vector3u(0,0,70))
      ("bus",                  Vector3u(0,60,100))
      ("caravan",              Vector3u(0,0,90))
      ("trailer",              Vector3u(0,0,110))
      ("train",                Vector3u(0,80,100))
      ("motorcycle",           Vector3u(0,0,230))
      ("bicycle",              Vector3u(119,11,32))
      ("license plate",        Vector3u(0,0,142))
    .convert_to_container<std::map<std::string,Vector3u> >();
  }
  else throw std::runtime_error("Error: Unknown semantic label set '" + labelSet + "'");

  // Determine which colours to mask out by looking up the labels to mask out in the map.
  m_coloursToMask.reserve(labelsToMask.size());
  for(std::set<std::string>::const_iterator it = labelsToMask.begin(), iend = labelsToMask.end(); it != iend; ++it)
  {
    std::map<std::string,Vector3u>::const_iterator jt = m_labelToColourMap.find(*it);
    if(jt != m_labelToColourMap.end())
    {
      m_coloursToMask.push_back(jt->second);
    }
  }
}

//#################### PUBLIC MEMBER FUNCTIONS ####################

ITMRGBDCalib SemanticMaskingImageSourceEngine::getCalib() const
{
  return m_normalSource->getCalib();
}

Vector2i SemanticMaskingImageSourceEngine::getDepthImageSize() const
{
  return m_normalSource->getDepthImageSize();
}

void SemanticMaskingImageSourceEngine::getImages(ORUChar4Image *rgb, ORShortImage *rawDepth)
{
  if(m_semanticSource->hasMoreImages())
  {
    if(!m_semanticImage) m_semanticImage.reset(new ORUChar4Image(rgb->noDims, true, true));

    m_normalSource->getImages(rgb, rawDepth);
    m_semanticSource->getImages(m_semanticImage.get(), rawDepth);

    const Vector4u zeroColour(0, 0, 0, 0);
    const Vector4u *semanticImage = m_semanticImage->GetData(MEMORYDEVICE_CPU);

  #ifdef WITH_OPENMP
    #pragma omp parallel for
  #endif
    for(int y = 0; y < rgb->noDims.y; ++y)
    {
      for(int x = 0; x < rgb->noDims.x; ++x)
      {
        // FIXME: Make this work even if the RGB and depth images aren't the same size.
        const int offset = y * rgb->noDims.x + x;
        const Vector3u c = semanticImage[offset].toVector3();
        for(size_t i = 0, size = m_coloursToMask.size(); i < size; ++i)
        {
          if(c == m_coloursToMask[i])
          {
            if(m_maskingType != MASK_DEPTH_ONLY) rgb->GetData(MEMORYDEVICE_CPU)[offset] = zeroColour;
            if(m_maskingType != MASK_RGB_ONLY) rawDepth->GetData(MEMORYDEVICE_CPU)[offset] = 0;
          }
        }
      }
    }
  }
  else
  {
    m_normalSource->getImages(rgb, rawDepth);
  }
}

Vector2i SemanticMaskingImageSourceEngine::getRGBImageSize() const
{
  return m_normalSource->getRGBImageSize();
}

bool SemanticMaskingImageSourceEngine::hasMoreImages() const
{
  return m_normalSource->hasMoreImages();
}

}

max_stars_repo_name: torrvision/spaint

max_issues_repo_name: torrvision/spaint

max_forks_repo_name: torrvision/spaint


text:
/*
 * Software License Agreement (BSD License)
 *
 *  Point Cloud Library (PCL) - www.pointclouds.org
 *  Copyright (c) 2011, Willow Garage, Inc.
 *
 *  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 Willow Garage, Inc. 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 THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS 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.
 *
 */

#include <pcl/gpu/kinfu_large_scale/tsdf_volume.h>
#include "internal.h"
#include <algorithm>
#include <Eigen/Core>
#include <pcl/common/time.h>

#include <iostream>

using namespace pcl;
using namespace pcl::gpu;
using namespace Eigen;
using pcl::device::device_cast;

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

pcl::gpu::TsdfVolume::TsdfVolume(const Vector3i& resolution) : resolution_(resolution)
{
  int volume_x = resolution_(0);
  int volume_y = resolution_(1);
  int volume_z = resolution_(2);

  volume_.create (volume_y * volume_z, volume_x);

  //zc:
  volume2nd_.create(volume_y * volume_z, volume_x);
  flagVolume_.create(volume_y * volume_z, volume_x);
  vrayPrevVolume_.create(volume_y * volume_z, volume_x);
  surfNormPrev_.create(volume_y * volume_z, volume_x);
  //volumeUpper_.create(volume_y * volume_z, volume_x);

  const Vector3f default_volume_size = Vector3f::Constant (3.f); //meters
  const float    default_tranc_dist  = 0.03f; //meters

  setSize(default_volume_size);
  setTsdfTruncDist(default_tranc_dist);

  reset();
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void
pcl::gpu::TsdfVolume::setSize(const Vector3f& size)
{
  size_ = size;
  setTsdfTruncDist(tranc_dist_);
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void
pcl::gpu::TsdfVolume::setTsdfTruncDist (float distance)
{
  float cx = size_(0) / resolution_(0);
  float cy = size_(1) / resolution_(1);
  float cz = size_(2) / resolution_(2);

  tranc_dist_ = std::max (distance, 1.111f * std::max (cx, std::max (cy, cz)));
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

pcl::gpu::DeviceArray2D<int>
pcl::gpu::TsdfVolume::data() const
{
  return volume_;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

const Eigen::Vector3f&
pcl::gpu::TsdfVolume::getSize() const
{
    return size_;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

const Eigen::Vector3i&
pcl::gpu::TsdfVolume::getResolution() const
{
  return resolution_;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

const Eigen::Vector3f
pcl::gpu::TsdfVolume::getVoxelSize() const
{
  return size_.array () / resolution_.array().cast<float>();
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

float
pcl::gpu::TsdfVolume::getTsdfTruncDist () const
{
  return tranc_dist_;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void
pcl::gpu::TsdfVolume::reset()
{
  device::initVolume(volume_);

  device::initFlagVolume(flagVolume_);
  device::initVrayPrevVolume(vrayPrevVolume_);
  device::initVrayPrevVolume(volume2nd_);
  device::initVrayPrevVolume(surfNormPrev_);
  //device::initVolume(volumeUpper_);

}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void
pcl::gpu::TsdfVolume::fetchCloudHost (PointCloud<PointXYZI>& cloud, bool connected26) const
{
  PointCloud<PointXYZ>::Ptr cloud_ptr_ = PointCloud<PointXYZ>::Ptr (new PointCloud<PointXYZ>);
  PointCloud<PointIntensity>::Ptr cloud_i_ptr_ = PointCloud<PointIntensity>::Ptr (new PointCloud<PointIntensity>);
  fetchCloudHost(*cloud_ptr_);
  pcl::concatenateFields (*cloud_ptr_, *cloud_i_ptr_, cloud);
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void
pcl::gpu::TsdfVolume::fetchCloudHost (PointCloud<PointType>& cloud, bool connected26) const
{
  int volume_x = resolution_(0);
  int volume_y = resolution_(1);
  int volume_z = resolution_(2);

  int cols;
  std::vector<int> volume_host;
  volume_.download (volume_host, cols);

  cloud.points.clear ();
  cloud.points.reserve (10000);

  const int DIVISOR = device::DIVISOR; // SHRT_MAX;

#define FETCH(x, y, z) volume_host[(x) + (y) * volume_x + (z) * volume_y * volume_x]

  Array3f cell_size = getVoxelSize();

  for (int x = 1; x < volume_x-1; ++x)
  {
    for (int y = 1; y < volume_y-1; ++y)
    {
      for (int z = 0; z < volume_z-1; ++z)
      {
        int tmp = FETCH (x, y, z);
        int W = reinterpret_cast<short2*>(&tmp)->y;
        int F = reinterpret_cast<short2*>(&tmp)->x;

        if (W == 0 || F == DIVISOR)
          continue;

        Vector3f V = ((Array3f(x, y, z) + 0.5f) * cell_size).matrix ();

        if (connected26)
        {
          int dz = 1;
          for (int dy = -1; dy < 2; ++dy)
            for (int dx = -1; dx < 2; ++dx)
            {
              int tmp = FETCH (x+dx, y+dy, z+dz);

              int Wn = reinterpret_cast<short2*>(&tmp)->y;
              int Fn = reinterpret_cast<short2*>(&tmp)->x;
              if (Wn == 0 || Fn == DIVISOR)
                continue;

              if ((F > 0 && Fn < 0) || (F < 0 && Fn > 0))
              {
                Vector3f Vn = ((Array3f (x+dx, y+dy, z+dz) + 0.5f) * cell_size).matrix ();
                Vector3f point = (V * abs (Fn) + Vn * abs (F)) / (abs (F) + abs (Fn));

                pcl::PointXYZ xyz;
                xyz.x = point (0);
                xyz.y = point (1);
                xyz.z = point (2);

                cloud.points.push_back (xyz);
              }
            }
          dz = 0;
          for (int dy = 0; dy < 2; ++dy)
            for (int dx = -1; dx < dy * 2; ++dx)
            {
              int tmp = FETCH (x+dx, y+dy, z+dz);

              int Wn = reinterpret_cast<short2*>(&tmp)->y;
              int Fn = reinterpret_cast<short2*>(&tmp)->x;
              if (Wn == 0 || Fn == DIVISOR)
                continue;

              if ((F > 0 && Fn < 0) || (F < 0 && Fn > 0))
              {
                Vector3f Vn = ((Array3f (x+dx, y+dy, z+dz) + 0.5f) * cell_size).matrix ();
                Vector3f point = (V * abs(Fn) + Vn * abs(F))/(abs(F) + abs (Fn));

                pcl::PointXYZ xyz;
                xyz.x = point (0);
                xyz.y = point (1);
                xyz.z = point (2);

                cloud.points.push_back (xyz);
              }
            }
        }
        else /* if (connected26) */
        {
          for (int i = 0; i < 3; ++i)
          {
            int ds[] = {0, 0, 0};
            ds[i] = 1;

            int dx = ds[0];
            int dy = ds[1];
            int dz = ds[2];

            int tmp = FETCH (x+dx, y+dy, z+dz);

            int Wn = reinterpret_cast<short2*>(&tmp)->y;
            int Fn = reinterpret_cast<short2*>(&tmp)->x;
            if (Wn == 0 || Fn == DIVISOR)
              continue;

            if ((F > 0 && Fn < 0) || (F < 0 && Fn > 0))
            {
              Vector3f Vn = ((Array3f (x+dx, y+dy, z+dz) + 0.5f) * cell_size).matrix ();
              Vector3f point = (V * abs (Fn) + Vn * abs (F)) / (abs (F) + abs (Fn));

              pcl::PointXYZ xyz;
              xyz.x = point (0);
              xyz.y = point (1);
              xyz.z = point (2);

              cloud.points.push_back (xyz);
            }
          }
        } /* if (connected26) */
      }
    }
  }
#undef FETCH
  cloud.width  = (int)cloud.points.size ();
  cloud.height = 1;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
pcl::gpu::DeviceArray<pcl::gpu::TsdfVolume::PointType>
pcl::gpu::TsdfVolume::fetchCloud (DeviceArray<PointType>& cloud_buffer, const pcl::gpu::tsdf_buffer* buffer) const
{
  if (cloud_buffer.empty ())
    cloud_buffer.create (DEFAULT_CLOUD_BUFFER_SIZE);

  float3 device_volume_size = device_cast<const float3> (size_);
  size_t size = device::extractCloud (volume_, buffer, device_volume_size, cloud_buffer);
  return (DeviceArray<PointType> (cloud_buffer.ptr (), size));
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void
pcl::gpu::TsdfVolume::fetchNormals (const DeviceArray<PointType>& cloud, DeviceArray<PointType>& normals) const
{
  normals.create (cloud.size ());
  const float3 device_volume_size = device_cast<const float3> (size_);
  device::extractNormals (volume_, device_volume_size, cloud, (device::PointType*)normals.ptr ());
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void
pcl::gpu::TsdfVolume::fetchNormalsInSpace (const DeviceArray<PointType>& cloud, const pcl::gpu::tsdf_buffer* buffer) const
{
  const float3 device_volume_size = device_cast<const float3> (size_);
  device::extractNormalsInSpace (volume_, buffer, device_volume_size, cloud);
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void
pcl::gpu::TsdfVolume::pushSlice (PointCloud<PointXYZI>::Ptr existing_data_cloud, const pcl::gpu::tsdf_buffer* buffer) const
{
  size_t gpu_array_size = existing_data_cloud->points.size ();

  if(gpu_array_size == 0)
  {
    //std::cout << "[KinfuTracker](pushSlice) Existing data cloud has no points\n";//CREATE AS PCL MESSAGE
    return;
  }

  const pcl::PointXYZI *first_point_ptr = &(existing_data_cloud->points[0]);

  pcl::gpu::DeviceArray<pcl::PointXYZI> cloud_gpu;
  cloud_gpu.upload (first_point_ptr, gpu_array_size);

  DeviceArray<float4>& cloud_cast = (DeviceArray<float4>&) cloud_gpu;
  //volume().pushCloudAsSlice (cloud_cast, &buffer_);
  pcl::device::pushCloudAsSliceGPU (volume_, cloud_cast, buffer);
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

size_t
pcl::gpu::TsdfVolume::fetchSliceAsCloud (DeviceArray<PointType>& cloud_buffer_xyz, DeviceArray<float>& cloud_buffer_intensity, const pcl::gpu::tsdf_buffer* buffer, int shiftX, int shiftY, int shiftZ ) const
{
  if (cloud_buffer_xyz.empty ())
    cloud_buffer_xyz.create (DEFAULT_CLOUD_BUFFER_SIZE);

  if (cloud_buffer_intensity.empty ()) {
    cloud_buffer_intensity.create (DEFAULT_CLOUD_BUFFER_SIZE);
  }

  float3 device_volume_size = device_cast<const float3> (size_);

  {
	  int newX = buffer->origin_GRID.x + shiftX;
	  int newY = buffer->origin_GRID.y + shiftY;
	  int newZ = buffer->origin_GRID.z + shiftZ;

	  int minBounds[ 3 ], maxBounds[ 3 ];

	  //X
	  if (newX >= 0)
	  {
		minBounds[ 0 ] = buffer->origin_GRID.x;
		maxBounds[ 0 ] = newX;
	  }
	  else
	  {
		minBounds[ 0 ] = newX + buffer->voxels_size.x - 1;
		maxBounds[ 0 ] = buffer->origin_GRID.x + buffer->voxels_size.x - 1;
	  }

	  if (minBounds[ 0 ] > maxBounds[ 0 ])
		std::swap (minBounds[ 0 ], maxBounds[ 0 ]);

	  //Y
	  if (newY >= 0)
	  {
		 minBounds[ 1 ] = buffer->origin_GRID.y;
		 maxBounds[ 1 ] = newY;
	  }
	  else
	  {
		minBounds[ 1 ] = newY + buffer->voxels_size.y - 1;
		maxBounds[ 1 ] = buffer->origin_GRID.y + buffer->voxels_size.y - 1;
	  }

	  if(minBounds[ 1 ] > maxBounds[ 1 ])
		std::swap (minBounds[ 1 ], maxBounds[ 1 ]);

	  //Z
	  if (newZ >= 0)
	  {
	   minBounds[ 2 ] = buffer->origin_GRID.z;
	   maxBounds[ 2 ] = newZ;
	  }
	  else
	  {
		minBounds[ 2 ] = newZ + buffer->voxels_size.z - 1;
		maxBounds[ 2 ] = buffer->origin_GRID.z + buffer->voxels_size.z - 1;
	  }

	  if (minBounds[ 2 ] > maxBounds[ 2 ])
		std::swap(minBounds[ 2 ], maxBounds[ 2 ]);

	  minBounds[ 0 ] -= buffer->origin_GRID.x;
	  maxBounds[ 0 ] -= buffer->origin_GRID.x;

	  minBounds[ 1 ] -= buffer->origin_GRID.y;
	  maxBounds[ 1 ] -= buffer->origin_GRID.y;

	  minBounds[ 2 ] -= buffer->origin_GRID.z;
	  maxBounds[ 2 ] -= buffer->origin_GRID.z;

	  if (minBounds[ 0 ] < 0) // We are shifting Left
	  {
		minBounds[ 0 ] += ( buffer->voxels_size.x - 1 );
		maxBounds[ 0 ] += ( buffer->voxels_size.x - 1 );
	  }

	  if (minBounds[ 1 ] < 0) // We are shifting up
	  {
		minBounds[ 1 ] += ( buffer->voxels_size.y - 1 );
		maxBounds[ 1 ] += ( buffer->voxels_size.y - 1 );
	  }

	  if (minBounds[ 2 ] < 0) // We are shifting back
	  {
		minBounds[ 2 ] += ( buffer->voxels_size.z - 1 );
		maxBounds[ 2 ] += ( buffer->voxels_size.z - 1 );
	  }
	  PCL_DEBUG( "In fetchSliceAsCloud:\n" );
	  PCL_DEBUG("Origin : %d, %d %d\n", buffer->origin_GRID.x, buffer->origin_GRID.y, buffer->origin_GRID.z );
	  PCL_DEBUG("Origin global : %f, %f %f\n", buffer->origin_GRID_global.x, buffer->origin_GRID_global.y, buffer->origin_GRID_global.z );
	  PCL_DEBUG( "Offset : %d, %d, %d\n", shiftX, shiftY, shiftZ );
      PCL_DEBUG ("X bound: [%d - %d]\n", minBounds[ 0 ], maxBounds[ 0 ]);
      PCL_DEBUG ("Y bound: [%d - %d]\n", minBounds[ 1 ], maxBounds[ 1 ]);
      PCL_DEBUG ("Z bound: [%d - %d]\n", minBounds[ 2 ], maxBounds[ 2 ]);

  }

  size_t size = pcl::device::extractSliceAsCloud (volume_, device_volume_size, buffer, shiftX, shiftY, shiftZ, cloud_buffer_xyz, cloud_buffer_intensity);

  std::cout << "SIZE IS " << size << " (maximum: " << DEFAULT_CLOUD_BUFFER_SIZE <<")" << std::endl;

  return (size);
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void
pcl::gpu::TsdfVolume::fetchNormals (const DeviceArray<PointType>& cloud, DeviceArray<NormalType>& normals) const
{
  normals.create (cloud.size ());
  const float3 device_volume_size = device_cast<const float3> (size_);
  device::extractNormals (volume_, device_volume_size, cloud, (device::float8*)normals.ptr ());
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void
pcl::gpu::TsdfVolume::downloadTsdf (std::vector<float>& tsdf) const
{
  tsdf.resize (volume_.cols() * volume_.rows());
  volume_.download(&tsdf[0], volume_.cols() * sizeof(int));

#pragma omp parallel for
  for(int i = 0; i < (int) tsdf.size(); ++i)
  {
    float tmp = reinterpret_cast<short2*>(&tsdf[i])->x;
    tsdf[i] = tmp/device::DIVISOR;
  }
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void
pcl::gpu::TsdfVolume::downloadTsdfAndWeighs (std::vector<float>& tsdf, std::vector<short>& weights) const
{
  int volumeSize = volume_.cols() * volume_.rows();
  tsdf.resize (volumeSize);
  weights.resize (volumeSize);
  {
    std::cout << std::endl;
    ScopeTime t("CUDA download");
    volume_.download(&tsdf[0], volume_.cols() * sizeof(int));
  }
 // {
	//std::cout << std::endl;
	//ScopeTime t("CUDA upload");
	//volume_.upload (&tsdf[0], volume_.cols() * sizeof(int), volume_.rows(), volume_.cols() );
 //   //volume_.download(&tsdf[0], volume_.cols() * sizeof(int));
 // }

#pragma omp parallel for
  for(int i = 0; i < (int) tsdf.size(); ++i)
  {
    short2 elem = *reinterpret_cast<short2*>(&tsdf[i]);
    tsdf[i] = (float)(elem.x)/device::DIVISOR;
    weights[i] = (short)(elem.y);
  }
}

max_stars_repo_name: GucciPrada/CuFusion

max_issues_repo_name: GucciPrada/CuFusion

max_forks_repo_name: GucciPrada/CuFusion