<commit_before>// Copyright (c) 2012, 2013 Pierre MOULON.

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#ifndef OPENMVG_IMAGE_IMAGE_IMAGE_IO_HPP
#define OPENMVG_IMAGE_IMAGE_IMAGE_IO_HPP

#include "openMVG/image/image_container.hpp"
#include "openMVG/image/pixel_types.hpp"

namespace openMVG {

enum Format {
  Pnm, Png, Jpg, Unknown
};

Format GetFormat(const char *c);

/// Try to load the given file in the image<T> openMVG image.
template<typename T>
int ReadImage(const char *, Image<T> *);

/// Open an png image with unsigned char as memory target.
/// The memory point must be null as input.
int ReadImage(const char *, std::vector<unsigned char> *, int * w, int * h, int * depth);
int ReadPng(const char *, std::vector<unsigned char> *, int * w, int * h, int * depth);
int ReadPngStream(FILE *, std::vector<unsigned char> *, int * w, int * h, int * depth);

template<typename T>
int WriteImage(const char *, const Image<T>&);

int WriteImage(const char *, const std::vector<unsigned char>& array, int w, int h, int depth);
int WritePng(const char *, const std::vector<unsigned char>& array, int w, int h, int depth);
int WritePngStream(FILE *,  const std::vector<unsigned char>& array, int w, int h, int depth);

template<typename T>
int WriteJpg(const char *, const Image<T>&, int quality=90);
int WriteJpg(const char *, const std::vector<unsigned char>& array, int w, int h, int depth, int quality=90);
int WriteJpgStream(FILE *, const std::vector<unsigned char>& array, int w, int h, int depth, int quality=90);

/// Open a jpg image with unsigned char as memory target.
/// The memory point must be null as input.
int ReadJpg(const char *, std::vector<unsigned char> *, int * w, int * h, int * depth);
int ReadJpgStream(FILE *, std::vector<unsigned char> *, int * w, int * h, int * depth);

int ReadPnm(const char *, std::vector<unsigned char> *, int * w, int * h, int * depth);
int ReadPnmStream(FILE *, std::vector<unsigned char> *, int * w, int * h, int * depth);

int WritePnm(const char *, const std::vector<unsigned char>& array, int w, int h, int depth);
int WritePnmStream(FILE *,  const std::vector<unsigned char>& array, int w, int h, int depth);

template<>
inline int ReadImage(const char * path, Image<unsigned char> * im)
{
  std::vector<unsigned char> ptr;
  int w, h, depth;
  int res = ReadImage(path, &ptr, &w, &h, &depth);
  if (res == 1 && depth == 1) {
    //convert raw array to Image
    (*im) = Eigen::Map<Image<unsigned char>::Base>(&ptr[0], h, w);
  }
  else
  if (res == 1 && depth == 3) {
    //-- Must convert RGB to gray
    RGBColor * ptrCol = (RGBColor*) &ptr[0];
    Image<RGBColor> rgbColIm;
    rgbColIm = Eigen::Map<Image<RGBColor>::Base>(ptrCol, h, w);
    //convert RGB to gray
    ConvertPixelType(rgbColIm, im);
  }
  else
  if (res == 1 && depth == 4) {
    //-- Must convert RGBA to gray
    RGBAColor * ptrCol = (RGBAColor*) &ptr[0];
    Image<RGBAColor> rgbaColIm;
    rgbaColIm = Eigen::Map<Image<RGBAColor>::Base>(ptrCol, h, w);
    //convert RGBA to gray
    ConvertPixelType(rgbaColIm, im);
  }
  else if (depth!=1)
    return 0;
  return res;
}

template<>
inline int ReadImage(const char * path, Image<RGBColor> * im)
{
  std::vector<unsigned char> ptr;
  int w, h, depth;
  int res = ReadImage(path, &ptr, &w, &h, &depth);
  if (res == 1 && depth == 3) {
    RGBColor * ptrCol = (RGBColor*) &ptr[0];
    //convert raw array to Image
    (*im) = Eigen::Map<Image<RGBColor>::Base>(ptrCol, h, w);
  }
  if (res == 1 && depth == 4) {
    //-- Must convert RGBA to RGB
    RGBAColor * ptrCol = (RGBAColor*) &ptr[0];
    Image<RGBAColor> rgbaColIm;
    rgbaColIm = Eigen::Map<Image<RGBAColor>::Base>(ptrCol, h, w);
    //convert RGBA to RGB
    ConvertPixelType(rgbaColIm, im);
  }
  else
    return 0;
  return res;
}

template<>
inline int ReadImage(const char * path, Image<RGBAColor> * im)
{
  std::vector<unsigned char> ptr;
  int w, h, depth;
  int res = ReadImage(path, &ptr, &w, &h, &depth);
  if (depth !=4) return 0;
  if (res == 1) {
    RGBAColor * ptrCol = (RGBAColor*) &ptr[0];
    //convert raw array to Image
    (*im) = Eigen::Map<Image<RGBAColor>::Base>(ptrCol, h, w);
  }
  return res;
}

//--------
//-- Image Writing
//--------

/// Write image to disk, support only unsigned char based type (gray, rgb, rgba)
template<typename T>
int WriteImage(const char * filename, const Image<T>& im)
{
  const unsigned char * ptr = (unsigned char*)(im.GetMat().data());
  int depth = sizeof( T ) / sizeof(unsigned char);
  std::vector<unsigned char> array( ptr , ptr + im.Width()*im.Height()*depth );
  int w = im.Width(), h = im.Height();
  return WriteImage(filename, array, w, h, depth);
}

template<typename T>
int WriteJpg(const char * filename, const Image<T>& im, int quality)
{
  const unsigned char * ptr = (unsigned char*)(im.GetMat().data());
  const int w = im.Width(), h = im.Height();
  const int depth = sizeof( T ) / sizeof(unsigned char);
  std::vector<unsigned char> array( ptr , ptr + w*h*depth );
  return WriteJpg(filename, array, w, h, depth, quality);
}

}  // namespace openMVG

#endif  // OPENMVG_IMAGE_IMAGE_IMAGE_IO_HPP
<commit_msg>Fix if else condition when reading RGB image. #121<commit_after>// Copyright (c) 2012, 2013 Pierre MOULON.

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#ifndef OPENMVG_IMAGE_IMAGE_IMAGE_IO_HPP
#define OPENMVG_IMAGE_IMAGE_IMAGE_IO_HPP

#include "openMVG/image/image_container.hpp"
#include "openMVG/image/pixel_types.hpp"

namespace openMVG {

enum Format {
  Pnm, Png, Jpg, Unknown
};

Format GetFormat(const char *c);

/// Try to load the given file in the image<T> openMVG image.
template<typename T>
int ReadImage(const char *, Image<T> *);

/// Open an png image with unsigned char as memory target.
/// The memory point must be null as input.
int ReadImage(const char *, std::vector<unsigned char> *, int * w, int * h, int * depth);
int ReadPng(const char *, std::vector<unsigned char> *, int * w, int * h, int * depth);
int ReadPngStream(FILE *, std::vector<unsigned char> *, int * w, int * h, int * depth);

template<typename T>
int WriteImage(const char *, const Image<T>&);

int WriteImage(const char *, const std::vector<unsigned char>& array, int w, int h, int depth);
int WritePng(const char *, const std::vector<unsigned char>& array, int w, int h, int depth);
int WritePngStream(FILE *,  const std::vector<unsigned char>& array, int w, int h, int depth);

template<typename T>
int WriteJpg(const char *, const Image<T>&, int quality=90);
int WriteJpg(const char *, const std::vector<unsigned char>& array, int w, int h, int depth, int quality=90);
int WriteJpgStream(FILE *, const std::vector<unsigned char>& array, int w, int h, int depth, int quality=90);

/// Open a jpg image with unsigned char as memory target.
/// The memory point must be null as input.
int ReadJpg(const char *, std::vector<unsigned char> *, int * w, int * h, int * depth);
int ReadJpgStream(FILE *, std::vector<unsigned char> *, int * w, int * h, int * depth);

int ReadPnm(const char *, std::vector<unsigned char> *, int * w, int * h, int * depth);
int ReadPnmStream(FILE *, std::vector<unsigned char> *, int * w, int * h, int * depth);

int WritePnm(const char *, const std::vector<unsigned char>& array, int w, int h, int depth);
int WritePnmStream(FILE *,  const std::vector<unsigned char>& array, int w, int h, int depth);

template<>
inline int ReadImage(const char * path, Image<unsigned char> * im)
{
  std::vector<unsigned char> ptr;
  int w, h, depth;
  int res = ReadImage(path, &ptr, &w, &h, &depth);
  if (res == 1 && depth == 1) {
    //convert raw array to Image
    (*im) = Eigen::Map<Image<unsigned char>::Base>(&ptr[0], h, w);
  }
  else
  if (res == 1 && depth == 3) {
    //-- Must convert RGB to gray
    RGBColor * ptrCol = (RGBColor*) &ptr[0];
    Image<RGBColor> rgbColIm;
    rgbColIm = Eigen::Map<Image<RGBColor>::Base>(ptrCol, h, w);
    //convert RGB to gray
    ConvertPixelType(rgbColIm, im);
  }
  else
  if (res == 1 && depth == 4) {
    //-- Must convert RGBA to gray
    RGBAColor * ptrCol = (RGBAColor*) &ptr[0];
    Image<RGBAColor> rgbaColIm;
    rgbaColIm = Eigen::Map<Image<RGBAColor>::Base>(ptrCol, h, w);
    //convert RGBA to gray
    ConvertPixelType(rgbaColIm, im);
  }
  else if (depth!=1)
    return 0;
  return res;
}

template<>
inline int ReadImage(const char * path, Image<RGBColor> * im)
{
  std::vector<unsigned char> ptr;
  int w, h, depth;
  int res = ReadImage(path, &ptr, &w, &h, &depth);
  if (res == 1 && depth == 3) {
    RGBColor * ptrCol = (RGBColor*) &ptr[0];
    //convert raw array to Image
    (*im) = Eigen::Map<Image<RGBColor>::Base>(ptrCol, h, w);
  }
  else
  if (res == 1 && depth == 4) {
    //-- Must convert RGBA to RGB
    RGBAColor * ptrCol = (RGBAColor*) &ptr[0];
    Image<RGBAColor> rgbaColIm;
    rgbaColIm = Eigen::Map<Image<RGBAColor>::Base>(ptrCol, h, w);
    //convert RGBA to RGB
    ConvertPixelType(rgbaColIm, im);
  }
  else
    return 0;
  return res;
}

template<>
inline int ReadImage(const char * path, Image<RGBAColor> * im)
{
  std::vector<unsigned char> ptr;
  int w, h, depth;
  int res = ReadImage(path, &ptr, &w, &h, &depth);
  if (depth !=4) return 0;
  if (res == 1) {
    RGBAColor * ptrCol = (RGBAColor*) &ptr[0];
    //convert raw array to Image
    (*im) = Eigen::Map<Image<RGBAColor>::Base>(ptrCol, h, w);
  }
  return res;
}

//--------
//-- Image Writing
//--------

/// Write image to disk, support only unsigned char based type (gray, rgb, rgba)
template<typename T>
int WriteImage(const char * filename, const Image<T>& im)
{
  const unsigned char * ptr = (unsigned char*)(im.GetMat().data());
  int depth = sizeof( T ) / sizeof(unsigned char);
  std::vector<unsigned char> array( ptr , ptr + im.Width()*im.Height()*depth );
  int w = im.Width(), h = im.Height();
  return WriteImage(filename, array, w, h, depth);
}

template<typename T>
int WriteJpg(const char * filename, const Image<T>& im, int quality)
{
  const unsigned char * ptr = (unsigned char*)(im.GetMat().data());
  const int w = im.Width(), h = im.Height();
  const int depth = sizeof( T ) / sizeof(unsigned char);
  std::vector<unsigned char> array( ptr , ptr + w*h*depth );
  return WriteJpg(filename, array, w, h, depth, quality);
}

}  // namespace openMVG

#endif  // OPENMVG_IMAGE_IMAGE_IMAGE_IO_HPP
<|endoftext|>


<commit_before>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4      *
*                (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS                    *
*                                                                             *
* This library is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU Lesser General Public License as published by    *
* the Free Software Foundation; either version 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details.                                                           *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with this library; if not, write to the Free Software Foundation,     *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *
*******************************************************************************
*                               SOFA :: Modules                               *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#define FLEXIBLE_DiffusionShapeFunction_CPP

#include "../initFlexible.h"
#include "../shapeFunction/DiffusionShapeFunction.h"
#include <sofa/core/ObjectFactory.h>

namespace sofa
{
namespace component
{
namespace shapefunction
{

using namespace defaulttype;
using namespace core::behavior;

template<class ShapeFunctionTypes,class ImageTypes>
const typename DiffusionShapeFunction<ShapeFunctionTypes,ImageTypes>::DistT DiffusionShapeFunction<ShapeFunctionTypes,ImageTypes>::MAXTEMP = (DistT)1.0;

SOFA_DECL_CLASS(DiffusionShapeFunction)

// Register in the Factory
int DiffusionShapeFunctionClass = core::RegisterObject("Computes shape functions based on diffusion in images")

        .add< DiffusionShapeFunction<ShapeFunction,ImageUC> >(true)
        .add< DiffusionShapeFunction<ShapeFunction,ImageD> >()
        ;

template class SOFA_Flexible_API DiffusionShapeFunction<ShapeFunction,ImageUC>;
template class SOFA_Flexible_API DiffusionShapeFunction<ShapeFunction,ImageD>;

}
}
}
<commit_msg>Flexible: add missing (I think) SOFA_Flexible_API<commit_after>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4      *
*                (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS                    *
*                                                                             *
* This library is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU Lesser General Public License as published by    *
* the Free Software Foundation; either version 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details.                                                           *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with this library; if not, write to the Free Software Foundation,     *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *
*******************************************************************************
*                               SOFA :: Modules                               *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#define FLEXIBLE_DiffusionShapeFunction_CPP

#include "../initFlexible.h"
#include "../shapeFunction/DiffusionShapeFunction.h"
#include <sofa/core/ObjectFactory.h>

namespace sofa
{
namespace component
{
namespace shapefunction
{

using namespace defaulttype;
using namespace core::behavior;

template<class ShapeFunctionTypes,class ImageTypes>
SOFA_Flexible_API const typename DiffusionShapeFunction<ShapeFunctionTypes,ImageTypes>::DistT DiffusionShapeFunction<ShapeFunctionTypes,ImageTypes>::MAXTEMP = (DistT)1.0;

SOFA_DECL_CLASS(DiffusionShapeFunction)

// Register in the Factory
int DiffusionShapeFunctionClass = core::RegisterObject("Computes shape functions based on diffusion in images")

        .add< DiffusionShapeFunction<ShapeFunction,ImageUC> >(true)
        .add< DiffusionShapeFunction<ShapeFunction,ImageD> >()
        ;

template class SOFA_Flexible_API DiffusionShapeFunction<ShapeFunction,ImageUC>;
template class SOFA_Flexible_API DiffusionShapeFunction<ShapeFunction,ImageD>;

}
}
}
<|endoftext|>


<commit_before>#include "FltFile.h"
#include "Registry.h"
#include "Record.h"
#include "RecordVisitor.h"
#include "ExternalRecord.h"
#include "flt2osg.h"             // ConvertFromFLT
#include "Input.h"

#include <osg/Node>
#include <osg/NodeVisitor>
#include <osg/Notify>

#include <osgDB/FileUtils>
#include <osgDB/FileNameUtils>

#include <osgSim/GeographicLocation>

#include <string>

using namespace flt;

FltFile::FltFile(
    ColorPool* pColorPool,
    TexturePool* pTexturePool,
    MaterialPool* pMaterialPool,
    LtPtAppearancePool* pLtPtAppearancePool,
    LtPtAnimationPool* pLtPtAnimationPool,
    osgDB::ReaderWriter::Options* options)
{
    _useTextureAlphaForTransparancyBinning = true;
    _doUnitsConversion = true;
    _desiredUnits = ConvertToMeters;

    if (pColorPool)
    {
        // use external color palette, ignore internal
        _useInternalColorPalette = false;
        setColorPool( pColorPool );
    }
    else
    {
        // use internal color palette
        _useInternalColorPalette = true;
        setColorPool( new ColorPool );
    }

    if (pTexturePool)
    {
        // use external texture palette, ignore internal
        _useInternalTexturePalette = false;
        setTexturePool( pTexturePool );
    }
    else
    {
        // use internal texture palette
        _useInternalTexturePalette = true;
        setTexturePool( new TexturePool );
    }

    if (pMaterialPool)
    {
        // use external material palette, ignore internal
        _useInternalMaterialPalette = false;
        setMaterialPool( pMaterialPool );
    }
    else
    {
        // use internal material palette
        _useInternalMaterialPalette = true;
        setMaterialPool( new MaterialPool );
    }

    if (pLtPtAppearancePool && pLtPtAnimationPool) // Can only be non-NULL if parent is 15.8.
    {
        // use external light point appearance and animation palettes, ignore internal
        _useInternalLtPtPalettes = false;
        setLtPtAppearancePool( pLtPtAppearancePool );
        setLtPtAnimationPool( pLtPtAnimationPool );
    }
    else
    {
        // If they aren't both set, then they must both be NULL.
        assert( (pLtPtAppearancePool==NULL) && (pLtPtAppearancePool==NULL) );
        // use internal light point palettes
        _useInternalLtPtPalettes = true;
        setLtPtAppearancePool( new LtPtAppearancePool );
        setLtPtAnimationPool( new LtPtAnimationPool );
    }

    // no support for external light palettes
    setLightPool( new LightPool );

    // instances are always internally defined
    setInstancePool( new InstancePool );

    _options = options;
}

osg::Object* FltFile::readObject(const std::string& fileName)
{
    return readNode(fileName);
}

osg::Node* FltFile::readNode(const std::string& fileName)
{
    _directory = osgDB::getFilePath(fileName);

    if (readModel(fileName))
    {
        // Convert record tree to osg scene graph
        osg::Node* model = convert();

        if (model)
        {
            // Store model origin in returned Node userData.
            osg::ref_ptr<osgSim::GeographicLocation> loc = new osgSim::GeographicLocation;
            double lat, lon;
            getOrigin( lat, lon );
            loc->set( lat, lon );
            model->setUserData( loc.get() );

            osg::notify(osg::INFO)<<"FltFile::readNode("<<fileName<<") lat="<<lat<<" lon="<<lon<<std::endl;

            return model;
        }
    }

    return NULL;
}

osg::Group* FltFile::convert()
{
    ConvertFromFLT visit;
    visit.setUseTextureAlphaForTransparancyBinning(getUseTextureAlphaForTransparancyBinning());
    visit.setDoUnitsConversion(getDoUnitsConversion());
    return visit.convert(getHeaderRecord());
}

// Read flight model (include externals)
bool FltFile::readModel(const std::string& fileName)
{
    if (readFile(fileName))
    {
        readExternals();
        return getHeaderRecord() ? true : false;
    }
    return false;
}

bool FltFile::readFile(const std::string& fileName)
{

    // havn't found file, look in OSGFILEPATH
    std::string foundFileName = osgDB::findDataFile(fileName, _options.get());
    if (foundFileName.empty()) return false;

    FileInput fin;
    if (!fin.open(foundFileName)) return false;

    Record* pRec = fin.readCreateRecord(this);
    if (pRec == NULL)
    {
        osg::notify(osg::WARN) << "File not found " << fileName << std::endl;
        return false;
    }

    _headerRecord = (HeaderRecord*)pRec;
    if (pRec->isPrimaryNode())   // Header
        pRec->readLocalData(fin);// Read rest of file

    fin.close();

    return true;
}

#define REGISTER_FLT 1

// This class was originally scoped within FltFile::readExternals() function.
// Irix 7.3 compilers hork on this.

    class ReadExternal : public RecordVisitor
    {
        public:
            ReadExternal(FltFile* fltFile)
            {
                _pFltFile = fltFile;
                setTraverseMode(RecordVisitor::TRAVERSE_ALL_CHILDREN);
            }

            virtual void apply(ExternalRecord& rec)
            {
                SExternalReference* pSExternal = (SExternalReference*)rec.getData();

                if (pSExternal)
                {
                    FltFile*        pExternalFltFile = NULL;
                    ColorPool*      pColorPool    = NULL;
                    TexturePool*    pTexturePool  = NULL;
                    MaterialPool*   pMaterialPool = NULL;
                    LtPtAppearancePool* pLtPtAppearancePool = NULL;
                    LtPtAnimationPool* pLtPtAnimationPool = NULL;
                    std::string filename( rec.getFilename() );

                    osg::notify(osg::INFO) << "External=" << filename << std::endl;

                    if (rec.getFlightVersion() > 13)
                    {
                        if (!(pSExternal->dwFlags & ExternalRecord::COLOR_PALETTE_OVERRIDE))
                            pColorPool = _pFltFile->getColorPool();

                        if (!(pSExternal->dwFlags & ExternalRecord::TEXTURE_PALETTE_OVERRIDE))
                            pTexturePool = _pFltFile->getTexturePool();

                        if (!(pSExternal->dwFlags & ExternalRecord::MATERIAL_PALETTE_OVERRIDE))
                            pMaterialPool = _pFltFile->getMaterialPool();

                        if (rec.getFlightVersion() >= 1580)
                        {
                            if (!(pSExternal->dwFlags & ExternalRecord::LIGHT_POINT_PALETTE_OVERRIDE))
                            {
                                pLtPtAppearancePool = _pFltFile->getLtPtAppearancePool();
                                pLtPtAnimationPool = _pFltFile->getLtPtAnimationPool();
                            }
                        }
                    }

                #if REGISTER_FLT
                    bool registerFLT = true;
                #else
                    bool registerFLT = false;
                #endif

                    pExternalFltFile = registerFLT ? Registry::instance()->getFltFile(filename) : NULL;
                    if (pExternalFltFile == NULL)
                    {
                        osg::ref_ptr<osgDB::ReaderWriter::Options> options =
                            _pFltFile->getOptions() ? _pFltFile->getOptions() :
                                                      new osgDB::ReaderWriter::Options;
                        //Path for Nested external references
                        osgDB::FilePathList& fpl = options->getDatabasePathList();
                        const std::string& filePath = osgDB::getFilePath(filename);
                        std::string pushAndPopPath;
                        //If absolute path
                        if( (filePath.length()>0 && filePath.find_first_of("/\\")==0) ||
                            (filePath.length()>2 && filePath.substr(1,1)==":" && filePath.find_first_of("/\\")==2) )
                        {
                            pushAndPopPath = filePath;
                        }
                        else
                        {
                            pushAndPopPath = (fpl.empty() | fpl.back().empty() ? "." : fpl.back()) + "/" + filePath;
                        }

                        char optionsString[256];
                        sprintf(optionsString,"FLT_VER %d",rec.getFlightVersion());
                        options->setOptionString(optionsString);

                        //osg::notify(osg::NOTICE)<<"Create local path"<<pushAndPopPath<<std::endl;

                        fpl.push_back(pushAndPopPath);

                        pExternalFltFile = new FltFile( pColorPool, pTexturePool, pMaterialPool,
                            pLtPtAppearancePool, pLtPtAnimationPool, options.get() );

                        if (registerFLT)
                        {
                            Registry::instance()->addFltFile(filename, pExternalFltFile);
                        }

                        pExternalFltFile->readModel(filename);

                        fpl.pop_back();
                    }

                    rec.setExternal(pExternalFltFile);
                }
            }

        public:

            FltFile* _pFltFile;
    };

void FltFile::readExternals()
{
    ReadExternal visitor(this);
    _headerRecord->accept(visitor);
}

int FltFile::getFlightVersion() const
{
    if (_headerRecord.get())
    {
        SHeader* pSHeader = (SHeader*)_headerRecord.get()->getData();
        if (pSHeader)
            return pSHeader->diFormatRevLev;
    }
    return 0;
}

void FltFile::getOrigin( double& latitude, double& longitude ) const
{
    if (_headerRecord.get())
    {
        SHeader* pSHeader = (SHeader*)_headerRecord.get()->getData();
        if (pSHeader)
        {
            latitude = pSHeader->Origin.x();
            longitude = pSHeader->Origin.y();
        }
    }
}

std::string FltFile::getDesiredUnitsString() const
{
    switch (_desiredUnits)
    {
    case ConvertToMeters:
        return "ConvertToMeters";
        break;
    case ConvertToKilometers:
        return "ConvertToKilometers";
        break;
    case ConvertToFeet:
        return "ConvertToFeet";
        break;
    case ConvertToInches:
        return "ConvertToInches";
        break;
    case ConvertToNauticalMiles:
        return "ConvertToNauticalMiles";
        break;
    default:
        return "Invalid";
        break;
    }
}

<commit_msg>From Alberto Farre, nested files bug fix.<commit_after>#include "FltFile.h"
#include "Registry.h"
#include "Record.h"
#include "RecordVisitor.h"
#include "ExternalRecord.h"
#include "flt2osg.h"             // ConvertFromFLT
#include "Input.h"

#include <osg/Node>
#include <osg/NodeVisitor>
#include <osg/Notify>

#include <osgDB/FileUtils>
#include <osgDB/FileNameUtils>

#include <osgSim/GeographicLocation>

#include <string>

using namespace flt;

FltFile::FltFile(
    ColorPool* pColorPool,
    TexturePool* pTexturePool,
    MaterialPool* pMaterialPool,
    LtPtAppearancePool* pLtPtAppearancePool,
    LtPtAnimationPool* pLtPtAnimationPool,
    osgDB::ReaderWriter::Options* options)
{
    _useTextureAlphaForTransparancyBinning = true;
    _doUnitsConversion = true;
    _desiredUnits = ConvertToMeters;

    if (pColorPool)
    {
        // use external color palette, ignore internal
        _useInternalColorPalette = false;
        setColorPool( pColorPool );
    }
    else
    {
        // use internal color palette
        _useInternalColorPalette = true;
        setColorPool( new ColorPool );
    }

    if (pTexturePool)
    {
        // use external texture palette, ignore internal
        _useInternalTexturePalette = false;
        setTexturePool( pTexturePool );
    }
    else
    {
        // use internal texture palette
        _useInternalTexturePalette = true;
        setTexturePool( new TexturePool );
    }

    if (pMaterialPool)
    {
        // use external material palette, ignore internal
        _useInternalMaterialPalette = false;
        setMaterialPool( pMaterialPool );
    }
    else
    {
        // use internal material palette
        _useInternalMaterialPalette = true;
        setMaterialPool( new MaterialPool );
    }

    if (pLtPtAppearancePool && pLtPtAnimationPool) // Can only be non-NULL if parent is 15.8.
    {
        // use external light point appearance and animation palettes, ignore internal
        _useInternalLtPtPalettes = false;
        setLtPtAppearancePool( pLtPtAppearancePool );
        setLtPtAnimationPool( pLtPtAnimationPool );
    }
    else
    {
        // If they aren't both set, then they must both be NULL.
        assert( (pLtPtAppearancePool==NULL) && (pLtPtAppearancePool==NULL) );
        // use internal light point palettes
        _useInternalLtPtPalettes = true;
        setLtPtAppearancePool( new LtPtAppearancePool );
        setLtPtAnimationPool( new LtPtAnimationPool );
    }

    // no support for external light palettes
    setLightPool( new LightPool );

    // instances are always internally defined
    setInstancePool( new InstancePool );

    _options = options;
}

osg::Object* FltFile::readObject(const std::string& fileName)
{
    return readNode(fileName);
}

osg::Node* FltFile::readNode(const std::string& fileName)
{
    _directory = osgDB::getFilePath(fileName);

    if (readModel(fileName))
    {
        // Convert record tree to osg scene graph
        osg::Node* model = convert();

        if (model)
        {
            // Store model origin in returned Node userData.
            osg::ref_ptr<osgSim::GeographicLocation> loc = new osgSim::GeographicLocation;
            double lat, lon;
            getOrigin( lat, lon );
            loc->set( lat, lon );
            model->setUserData( loc.get() );

            osg::notify(osg::INFO)<<"FltFile::readNode("<<fileName<<") lat="<<lat<<" lon="<<lon<<std::endl;

            return model;
        }
    }

    return NULL;
}

osg::Group* FltFile::convert()
{
    ConvertFromFLT visit;
    visit.setUseTextureAlphaForTransparancyBinning(getUseTextureAlphaForTransparancyBinning());
    visit.setDoUnitsConversion(getDoUnitsConversion());
    return visit.convert(getHeaderRecord());
}

// Read flight model (include externals)
bool FltFile::readModel(const std::string& fileName)
{
    if (readFile(fileName))
    {
        readExternals();
        return getHeaderRecord() ? true : false;
    }
    return false;
}

bool FltFile::readFile(const std::string& fileName)
{

    // havn't found file, look in OSGFILEPATH
    std::string foundFileName = osgDB::findDataFile(fileName, _options.get());
    if (foundFileName.empty()) return false;

    FileInput fin;
    if (!fin.open(foundFileName)) return false;

    Record* pRec = fin.readCreateRecord(this);
    if (pRec == NULL)
    {
        osg::notify(osg::WARN) << "File not found " << fileName << std::endl;
        return false;
    }

    _headerRecord = (HeaderRecord*)pRec;
    if (pRec->isPrimaryNode())   // Header
        pRec->readLocalData(fin);// Read rest of file

    fin.close();

    return true;
}

#define REGISTER_FLT 1

// This class was originally scoped within FltFile::readExternals() function.
// Irix 7.3 compilers hork on this.

    class ReadExternal : public RecordVisitor
    {
        public:
            ReadExternal(FltFile* fltFile)
            {
                _pFltFile = fltFile;
                setTraverseMode(RecordVisitor::TRAVERSE_ALL_CHILDREN);
            }

            virtual void apply(ExternalRecord& rec)
            {
                SExternalReference* pSExternal = (SExternalReference*)rec.getData();

                if (pSExternal)
                {
                    FltFile*        pExternalFltFile = NULL;
                    ColorPool*      pColorPool    = NULL;
                    TexturePool*    pTexturePool  = NULL;
                    MaterialPool*   pMaterialPool = NULL;
                    LtPtAppearancePool* pLtPtAppearancePool = NULL;
                    LtPtAnimationPool* pLtPtAnimationPool = NULL;
                    std::string filename( rec.getFilename() );

                    osg::notify(osg::INFO) << "External=" << filename << std::endl;

                    if (rec.getFlightVersion() > 13)
                    {
                        if (!(pSExternal->dwFlags & ExternalRecord::COLOR_PALETTE_OVERRIDE))
                            pColorPool = _pFltFile->getColorPool();

                        if (!(pSExternal->dwFlags & ExternalRecord::TEXTURE_PALETTE_OVERRIDE))
                            pTexturePool = _pFltFile->getTexturePool();

                        if (!(pSExternal->dwFlags & ExternalRecord::MATERIAL_PALETTE_OVERRIDE))
                            pMaterialPool = _pFltFile->getMaterialPool();

                        if (rec.getFlightVersion() >= 1580)
                        {
                            if (!(pSExternal->dwFlags & ExternalRecord::LIGHT_POINT_PALETTE_OVERRIDE))
                            {
                                pLtPtAppearancePool = _pFltFile->getLtPtAppearancePool();
                                pLtPtAnimationPool = _pFltFile->getLtPtAnimationPool();
                            }
                        }
                    }

                #if REGISTER_FLT
                    bool registerFLT = true;
                #else
                    bool registerFLT = false;
                #endif

                    pExternalFltFile = registerFLT ? Registry::instance()->getFltFile(filename) : NULL;
                    if (pExternalFltFile == NULL)
                    {
                        osg::ref_ptr<osgDB::ReaderWriter::Options> options =
                            _pFltFile->getOptions() ? _pFltFile->getOptions() :
                                                      new osgDB::ReaderWriter::Options;

                        //Path for Nested external references
                        osgDB::FilePathList& fpl = options->getDatabasePathList();
                        const std::string& filePath = osgDB::getFilePath(filename);
                        std::string pushAndPopPath;
                        //If absolute path
                        if( (filePath.length()>0 && filePath.find_first_of("/\\")==0) ||
                            (filePath.length()>2 && filePath.substr(1,1)==":" && filePath.find_first_of("/\\")==2) )
                        {
                            pushAndPopPath = filePath;
                        }
                        else
                        {
                            pushAndPopPath = (fpl.empty() | fpl.back().empty() ? "." : fpl.back()) + "/" + filePath;
                        }

                        char optionsString[256];
                        sprintf(optionsString,"FLT_VER %d",rec.getFlightVersion());
                        options->setOptionString(optionsString);

                        //osg::notify(osg::NOTICE)<<"Create local path"<<pushAndPopPath<<std::endl;

                        fpl.push_back(pushAndPopPath);

                        pExternalFltFile = new FltFile( pColorPool, pTexturePool, pMaterialPool,
                            pLtPtAppearancePool, pLtPtAnimationPool, options.get() );

                        if (registerFLT)
                        {
                            Registry::instance()->addFltFile(filename, pExternalFltFile);
                        }

                        pExternalFltFile->readModel(filename);
                    }

                    rec.setExternal(pExternalFltFile);
                }
            }

        public:

            FltFile* _pFltFile;
    };

void FltFile::readExternals()
{
    ReadExternal visitor(this);
    _headerRecord->accept(visitor);
}

int FltFile::getFlightVersion() const
{
    if (_headerRecord.get())
    {
        SHeader* pSHeader = (SHeader*)_headerRecord.get()->getData();
        if (pSHeader)
            return pSHeader->diFormatRevLev;
    }
    return 0;
}

void FltFile::getOrigin( double& latitude, double& longitude ) const
{
    if (_headerRecord.get())
    {
        SHeader* pSHeader = (SHeader*)_headerRecord.get()->getData();
        if (pSHeader)
        {
            latitude = pSHeader->Origin.x();
            longitude = pSHeader->Origin.y();
        }
    }
}

std::string FltFile::getDesiredUnitsString() const
{
    switch (_desiredUnits)
    {
    case ConvertToMeters:
        return "ConvertToMeters";
        break;
    case ConvertToKilometers:
        return "ConvertToKilometers";
        break;
    case ConvertToFeet:
        return "ConvertToFeet";
        break;
    case ConvertToInches:
        return "ConvertToInches";
        break;
    case ConvertToNauticalMiles:
        return "ConvertToNauticalMiles";
        break;
    default:
        return "Invalid";
        break;
    }
}

<|endoftext|>


<commit_before>/*
    Copyright (C) 2013  Martin Klapetek <mklapetek@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "persons-presence-model.h"
#include "persons-model.h"

#include <TelepathyQt/AccountManager>
#include <TelepathyQt/AccountFactory>
#include <TelepathyQt/ContactManager>
#include <TelepathyQt/PendingOperation>
#include <TelepathyQt/PendingReady>

#include <KTp/contact-factory.h>
#include <KTp/global-contact-manager.h>
#include <KDebug>

PersonsPresenceModel::PersonsPresenceModel(QObject *parent)
: QIdentityProxyModel(parent)
{
    Tp::AccountFactoryPtr  accountFactory = Tp::AccountFactory::create(QDBusConnection::sessionBus(),
                                                                       Tp::Features() << Tp::Account::FeatureCore
                                                                       << Tp::Account::FeatureCapabilities
                                                                       << Tp::Account::FeatureProtocolInfo
                                                                       << Tp::Account::FeatureProfile);

    Tp::ConnectionFactoryPtr connectionFactory = Tp::ConnectionFactory::create(QDBusConnection::sessionBus(),
                                                                               Tp::Features() << Tp::Connection::FeatureCore
                                                                               << Tp::Connection::FeatureRoster
                                                                               << Tp::Connection::FeatureSelfContact);

    Tp::ContactFactoryPtr contactFactory = KTp::ContactFactory::create(Tp::Features()  << Tp::Contact::FeatureAlias
                                                                        << Tp::Contact::FeatureSimplePresence
                                                                        << Tp::Contact::FeatureCapabilities
                                                                        << Tp::Contact::FeatureClientTypes);

    Tp::ChannelFactoryPtr channelFactory = Tp::ChannelFactory::create(QDBusConnection::sessionBus());

    m_accountManager = Tp::AccountManager::create(QDBusConnection::sessionBus(),
                                                  accountFactory,
                                                  connectionFactory,
                                                  channelFactory,
                                                  contactFactory);

    connect(m_accountManager->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)),
            this, SLOT(onAccountManagerReady(Tp::PendingOperation*)));
}

PersonsPresenceModel::~PersonsPresenceModel()
{

}

void PersonsPresenceModel::onAccountManagerReady(Tp::PendingOperation *op)
{
    if (op->isError()) {
        kWarning() << "Failed to initialize AccountManager:" << op->errorName();
        kWarning() << op->errorMessage();

        return;
    }

    kDebug() << "Account manager ready";

    m_contactManager = new KTp::GlobalContactManager(m_accountManager, this);
    connect(m_contactManager, SIGNAL(allKnownContactsChanged(Tp::Contacts,Tp::Contacts)),
            this, SLOT(onAllKnownContactsChanged(Tp::Contacts,Tp::Contacts)));

    onAllKnownContactsChanged(m_contactManager->allKnownContacts(), Tp::Contacts());
}

void PersonsPresenceModel::onAllKnownContactsChanged(const Tp::Contacts &contactsAdded, const Tp::Contacts &contactsRemoved)
{
    if (!m_presences.isEmpty()) {
        Q_FOREACH (const Tp::ContactPtr &contact, contactsRemoved) {
            m_presences.remove(contact->id());
        }
    }

    Q_FOREACH (const Tp::ContactPtr &contact, contactsAdded) {
        m_presences.insert(contact->id(), contact);

        connect(contact.data(), SIGNAL(presenceChanged(Tp::Presence)),
                this, SLOT(onContactChanged()));

        connect(contact.data(), SIGNAL(capabilitiesChanged(Tp::ContactCapabilities)),
                this, SLOT(onContactChanged()));

        //TODO: add other stuff here etc

        QModelIndex index = qobject_cast<PersonsModel*>(sourceModel())->findRecursively(PersonsModel::IMRole, contact->id());
        Q_EMIT dataChanged(index, index);
    }
}

void PersonsPresenceModel::onContactChanged()
{
    QString id = qobject_cast<Tp::Contact*>(sender())->id();

    QModelIndex index = qobject_cast<PersonsModel*>(sourceModel())->findRecursively(PersonsModel::IMRole, id);
    Q_EMIT dataChanged(index, index);
}

QVariant PersonsPresenceModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid()) {
        return QVariant();
    }

    if (role == PersonsModel::StatusRole) {
        if (index.data(PersonsModel::ResourceTypeRole).toUInt() == PersonsModel::Contact) {
            QString contactId = index.data(PersonsModel::IMRole).toString();
            if (m_presences.keys().contains(contactId)) {
                return m_presences.value(contactId)->presence().status();
            } else {
                return QLatin1String("unknown");
            }
        } else if (index.data(PersonsModel::ResourceTypeRole).toUInt() == PersonsModel::Person) {
            QVariantList ret;
            for (int i = 0; i < rowCount(); i++) {
                QVariant value = index.child(i, 0).data(role);
                if (!value.isNull()) {
                    ret += value;
                }
            }
            return ret;
        }
    }

    return QIdentityProxyModel::data(index, role);
}
<commit_msg>Return "offline" presence before we have presences ready<commit_after>/*
    Copyright (C) 2013  Martin Klapetek <mklapetek@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "persons-presence-model.h"
#include "persons-model.h"

#include <TelepathyQt/AccountManager>
#include <TelepathyQt/AccountFactory>
#include <TelepathyQt/ContactManager>
#include <TelepathyQt/PendingOperation>
#include <TelepathyQt/PendingReady>

#include <KTp/contact-factory.h>
#include <KTp/global-contact-manager.h>
#include <KDebug>

PersonsPresenceModel::PersonsPresenceModel(QObject *parent)
: QIdentityProxyModel(parent)
{
    Tp::AccountFactoryPtr  accountFactory = Tp::AccountFactory::create(QDBusConnection::sessionBus(),
                                                                       Tp::Features() << Tp::Account::FeatureCore
                                                                       << Tp::Account::FeatureCapabilities
                                                                       << Tp::Account::FeatureProtocolInfo
                                                                       << Tp::Account::FeatureProfile);

    Tp::ConnectionFactoryPtr connectionFactory = Tp::ConnectionFactory::create(QDBusConnection::sessionBus(),
                                                                               Tp::Features() << Tp::Connection::FeatureCore
                                                                               << Tp::Connection::FeatureRoster
                                                                               << Tp::Connection::FeatureSelfContact);

    Tp::ContactFactoryPtr contactFactory = KTp::ContactFactory::create(Tp::Features()  << Tp::Contact::FeatureAlias
                                                                        << Tp::Contact::FeatureSimplePresence
                                                                        << Tp::Contact::FeatureCapabilities
                                                                        << Tp::Contact::FeatureClientTypes);

    Tp::ChannelFactoryPtr channelFactory = Tp::ChannelFactory::create(QDBusConnection::sessionBus());

    m_accountManager = Tp::AccountManager::create(QDBusConnection::sessionBus(),
                                                  accountFactory,
                                                  connectionFactory,
                                                  channelFactory,
                                                  contactFactory);

    connect(m_accountManager->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)),
            this, SLOT(onAccountManagerReady(Tp::PendingOperation*)));
}

PersonsPresenceModel::~PersonsPresenceModel()
{

}

void PersonsPresenceModel::onAccountManagerReady(Tp::PendingOperation *op)
{
    if (op->isError()) {
        kWarning() << "Failed to initialize AccountManager:" << op->errorName();
        kWarning() << op->errorMessage();

        return;
    }

    kDebug() << "Account manager ready";

    m_contactManager = new KTp::GlobalContactManager(m_accountManager, this);
    connect(m_contactManager, SIGNAL(allKnownContactsChanged(Tp::Contacts,Tp::Contacts)),
            this, SLOT(onAllKnownContactsChanged(Tp::Contacts,Tp::Contacts)));

    onAllKnownContactsChanged(m_contactManager->allKnownContacts(), Tp::Contacts());
}

void PersonsPresenceModel::onAllKnownContactsChanged(const Tp::Contacts &contactsAdded, const Tp::Contacts &contactsRemoved)
{
    if (!m_presences.isEmpty()) {
        Q_FOREACH (const Tp::ContactPtr &contact, contactsRemoved) {
            m_presences.remove(contact->id());
        }
    }

    Q_FOREACH (const Tp::ContactPtr &contact, contactsAdded) {
        m_presences.insert(contact->id(), contact);

        connect(contact.data(), SIGNAL(presenceChanged(Tp::Presence)),
                this, SLOT(onContactChanged()));

        connect(contact.data(), SIGNAL(capabilitiesChanged(Tp::ContactCapabilities)),
                this, SLOT(onContactChanged()));

        //TODO: add other stuff here etc

        QModelIndex index = qobject_cast<PersonsModel*>(sourceModel())->findRecursively(PersonsModel::IMRole, contact->id());
        Q_EMIT dataChanged(index, index);
    }
}

void PersonsPresenceModel::onContactChanged()
{
    QString id = qobject_cast<Tp::Contact*>(sender())->id();

    QModelIndex index = qobject_cast<PersonsModel*>(sourceModel())->findRecursively(PersonsModel::IMRole, id);
    Q_EMIT dataChanged(index, index);
}

QVariant PersonsPresenceModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid()) {
        return QVariant();
    }

    if (role == PersonsModel::StatusRole) {
        if (index.data(PersonsModel::ResourceTypeRole).toUInt() == PersonsModel::Contact) {
            QString contactId = index.data(PersonsModel::IMRole).toString();
            if (m_presences.keys().contains(contactId)) {
                return m_presences.value(contactId)->presence().status();
            } else if (!contactId.isEmpty()) {
                return QLatin1String("offline");
            } else if (contactId.isEmpty()) {
                return QLatin1String("unknown");
            }
        } else if (index.data(PersonsModel::ResourceTypeRole).toUInt() == PersonsModel::Person) {
            QVariantList ret;
            for (int i = 0; i < rowCount(); i++) {
                QVariant value = index.child(i, 0).data(role);
                if (!value.isNull()) {
                    ret += value;
                }
            }
            return ret;
        }
    }

    return QIdentityProxyModel::data(index, role);
}
<|endoftext|>


<commit_before>#include "../include/carta.h"
#include "../include/textura.h"
#include "../include/to_string.h"

#define CARD_WIDTH 125
#define CARD_HEIGHT 164

using namespace std;

Carta::Carta(int num, SDL_Renderer* renderer){
	string dir = "../textures/cards/";
	int i = (num-1)/13;
	this->value = num-13*i;
	this->suit = 65+i;
	dir.append(to_string(this->value));
	dir.push_back(this->suit);
	dir.append(".png");
	this->gTexture = Textura(dir, renderer, 0, 0, CARD_WIDTH, CARD_HEIGHT);
}

void Carta::setPosition(int x, int y){
	this->gTexture.setPosition(x, y);
}

void Carta::renderCard() {
	this->gTexture.render();
}

int Carta::getValue(){
	return this->value;
}

char Carta::getSuit(){
	return this->suit;
}
<commit_msg>textura.h já está em carta.h<commit_after>#include "../include/carta.h"
#include "../include/to_string.h"

#define CARD_WIDTH 125
#define CARD_HEIGHT 164

using namespace std;

Carta::Carta(int num, SDL_Renderer* renderer){
	string dir = "../textures/cards/";
	int i = (num-1)/13;
	this->value = num-13*i;
	this->suit = 65+i;
	dir.append(to_string(this->value));
	dir.push_back(this->suit);
	dir.append(".png");
	this->gTexture = Textura(dir, renderer, 0, 0, CARD_WIDTH, CARD_HEIGHT);
}

void Carta::setPosition(int x, int y){
	this->gTexture.setPosition(x, y);
}

void Carta::renderCard() {
	this->gTexture.render();
}

int Carta::getValue(){
	return this->value;
}

char Carta::getSuit(){
	return this->suit;
}
<|endoftext|>


<commit_before>#include "clustering.hpp"

Clustering::Clustering( std::vector<IndexTransition> const & vIndexTransition, double (*distance_function)(IndexTransitionCluster const &, IndexTransitionCluster const &), double eps, uint minPts):
eps{eps}, minPts{minPts}, nowClusterNumber{0}, distance_function{distance_function}
{
    std::for_each(vIndexTransition.begin(), vIndexTransition.end(), [ this ]( IndexTransition const & indexTransition ){
        vIndexTransitionCluster.push_back( IndexTransitionCluster( indexTransition ) );
    });

    std::stable_sort( vIndexTransitionCluster.begin(), vIndexTransitionCluster.end(), []( IndexTransitionCluster const & p1, IndexTransitionCluster const & p2 ){
        if( p1.row < p2.row )
        {
            return true;
        }
        else
        {
            return false;
        }
    });
}

uint Clustering::create_new_cluster()
{
    nowClusterNumber += 1;
    return nowClusterNumber;
}

uint Clustering::get_cluster_number()
{
    return nowClusterNumber;
}

void Clustering::points_clustering( void (Clustering::*check_point_zone_function)(int) )
{
    for( int indexX = 0; indexX < vIndexTransitionCluster.size(); ++indexX )
    {
        (this->*check_point_zone_function)(indexX);
    }

    concatenate_clusters();

    remove_small_clusters_and_noise();
}

void Clustering::check_point_zone_linear( int indexX )
{
    std::vector<uint> linkedClusters;
    uint currentClusterNumber = 0;
    IndexTransitionCluster point = vIndexTransitionCluster[indexX];
    if( point.clusterNumber == 0 )
    {
        currentClusterNumber = create_new_cluster();
        point.clusterNumber = currentClusterNumber;
    }
    else
    {
        currentClusterNumber = point.clusterNumber;
    }
    linkedClusters.push_back(currentClusterNumber);

    double minX = point.row - eps;
    double maxX = point.row + eps;
    for( int i = 0; i < vIndexTransitionCluster.size(); ++i )
    {
        if( vIndexTransitionCluster[i].row < minX)
            continue;
        else
        {
            if( maxX < vIndexTransitionCluster[i].row )
            {
                break;
            }
            else
            {
                if (distance_function(point, vIndexTransitionCluster[i]) <= eps )
                {
                    if( vIndexTransitionCluster[i].clusterNumber == 0 )
                    {
                        vIndexTransitionCluster[i].clusterNumber = currentClusterNumber;
                    }
                    else
                    {
                        linkedClusters.push_back( vIndexTransitionCluster[i].clusterNumber );
                    }
                }
            }
        }
    }
    std::sort(linkedClusters.begin(),linkedClusters.end());
    linkedClusters.erase(std::unique(linkedClusters.begin(), linkedClusters.end()), linkedClusters.end());

    linkedTransform.resize(std::max(linkedClusters.back() + 1, (uint)(linkedTransform.size())), UINT32_MAX);//UINT32_MAX is one to one map (ex. if linkedTransform[2]==UINT32_MAX then cluster 2 maped to cluster2)

    uint minLinkedTransformByLinkedClusters = linkedClusters.front();//only for start, could be back() or what ever
    std::for_each( linkedClusters.begin(), linkedClusters.end(), [ this, &minLinkedTransformByLinkedClusters ]( uint cl){
        minLinkedTransformByLinkedClusters = std::min( minLinkedTransformByLinkedClusters, linkedTransform[cl] );
    });

    std::for_each( linkedClusters.begin(), linkedClusters.end(), [ this, &minLinkedTransformByLinkedClusters ]( uint cl){
        uint oldValue = linkedTransform[cl];
        std::replace( linkedTransform.begin() + 1, linkedTransform.end(), oldValue, minLinkedTransformByLinkedClusters);// +1 reserved element [0]
    });

    return;
}

void Clustering::concatenate_clusters()
{
    for(uint i = 0; i < linkedTransform.size(); ++i)//zeroes is one to one map (ex. if linkedTransform[2]==0 then cluster 2 maped to cluster 2)
    {
        if(linkedTransform[i] == UINT32_MAX)
        {
            linkedTransform[i] = i;
        }
    }

//raw cluster numbers or not
    std::vector<uint> distinctClusters(linkedTransform);
    std::sort(distinctClusters.begin(), distinctClusters.end());
    distinctClusters.erase(std::unique(distinctClusters.begin(), distinctClusters.end()), distinctClusters.end());

    std::vector<uint> transLinkedTransform(distinctClusters.back() + 1, 0);
    for(int i = 0; i < distinctClusters.size(); ++i)
    {
        transLinkedTransform[distinctClusters[i]] = i;
    }
    std::for_each(linkedTransform.begin(), linkedTransform.end(), [&transLinkedTransform](auto& lt){
        lt = transLinkedTransform[lt];
    });

    std::for_each(vIndexTransitionCluster.begin(), vIndexTransitionCluster.end(), [this](auto& itc){
        itc.clusterNumber = linkedTransform[ itc.clusterNumber ];
    });
}

void Clustering::remove_small_clusters_and_noise()
{
    auto maxClusterNumberIterator = std::max_element( vIndexTransitionCluster.begin(), vIndexTransitionCluster.end(), []( IndexTransitionCluster const & itc1, IndexTransitionCluster const & itc2){
        if( itc1.clusterNumber < itc2.clusterNumber )
        {
            return true;
        }
        else
        {
            return false;
        }
    });
    uint maxClusterNumber = maxClusterNumberIterator->clusterNumber;

    std::vector<uint>clusterOccurences(maxClusterNumber + 1, 0);
    for_each( vIndexTransitionCluster.begin(), vIndexTransitionCluster.end(), [&clusterOccurences]( IndexTransitionCluster const & itc ){
        if( itc.clusterNumber != 0 )// new itc without cluster occurrrence
        {
            clusterOccurences[itc.clusterNumber] += 1;
        }
    });

    vIndexTransitionCluster.erase(std::remove_if(vIndexTransitionCluster.begin(), vIndexTransitionCluster.end(), [this, &clusterOccurences](IndexTransitionCluster const & itc){//remove small clusters
        if( clusterOccurences[itc.clusterNumber] < minPts )
        {
            return true;
        }
        else
        {
            return false;
        }
    }), vIndexTransitionCluster.end());
}

double Distance::distance_fast( IndexTransitionCluster const & pixelA, IndexTransitionCluster const & pixelB )
{
    return abs( pixelA.row - pixelB.row ) + abs( pixelA.col - pixelB.col );
}

double Distance::distance_slow( IndexTransitionCluster const & pixelA, IndexTransitionCluster const & pixelB )
{
    return sqrt( pow( ( pixelA.row - pixelB.row ), 2.0 ) + pow( ( pixelA.col - pixelB.col ), 2.0 ) );
}<commit_msg>break if linked cluster size 0<commit_after>#include "clustering.hpp"

Clustering::Clustering( std::vector<IndexTransition> const & vIndexTransition, double (*distance_function)(IndexTransitionCluster const &, IndexTransitionCluster const &), double eps, uint minPts):
eps{eps}, minPts{minPts}, nowClusterNumber{0}, distance_function{distance_function}
{
    std::for_each(vIndexTransition.begin(), vIndexTransition.end(), [ this ]( IndexTransition const & indexTransition ){
        vIndexTransitionCluster.push_back( IndexTransitionCluster( indexTransition ) );
    });

    std::stable_sort( vIndexTransitionCluster.begin(), vIndexTransitionCluster.end(), []( IndexTransitionCluster const & p1, IndexTransitionCluster const & p2 ){
        if( p1.row < p2.row )
        {
            return true;
        }
        else
        {
            return false;
        }
    });
}

uint Clustering::create_new_cluster()
{
    nowClusterNumber += 1;
    return nowClusterNumber;
}

uint Clustering::get_cluster_number()
{
    return nowClusterNumber;
}

void Clustering::points_clustering( void (Clustering::*check_point_zone_function)(int) )
{
    for( int indexX = 0; indexX < vIndexTransitionCluster.size(); ++indexX )
    {
        (this->*check_point_zone_function)(indexX);
    }
    if( linkedTransform.size() == 0 )
        return;

    concatenate_clusters();

    remove_small_clusters_and_noise();
}

void Clustering::check_point_zone_linear( int indexX )
{
    std::vector<uint> linkedClusters;
    uint currentClusterNumber = 0;
    IndexTransitionCluster point = vIndexTransitionCluster[indexX];
    if( point.clusterNumber == 0 )
    {
        currentClusterNumber = create_new_cluster();
        point.clusterNumber = currentClusterNumber;
    }
    else
    {
        currentClusterNumber = point.clusterNumber;
    }
    linkedClusters.push_back(currentClusterNumber);

    double minX = point.row - eps;
    double maxX = point.row + eps;
    for( int i = 0; i < vIndexTransitionCluster.size(); ++i )
    {
        if( vIndexTransitionCluster[i].row < minX)
            continue;
        else
        {
            if( maxX < vIndexTransitionCluster[i].row )
            {
                break;
            }
            else
            {
                if (distance_function(point, vIndexTransitionCluster[i]) <= eps )
                {
                    if( vIndexTransitionCluster[i].clusterNumber == 0 )
                    {
                        vIndexTransitionCluster[i].clusterNumber = currentClusterNumber;
                    }
                    else
                    {
                        linkedClusters.push_back( vIndexTransitionCluster[i].clusterNumber );
                    }
                }
            }
        }
    }
    std::sort(linkedClusters.begin(),linkedClusters.end());
    linkedClusters.erase(std::unique(linkedClusters.begin(), linkedClusters.end()), linkedClusters.end());

    linkedTransform.resize(std::max(linkedClusters.back() + 1, (uint)(linkedTransform.size())), UINT32_MAX);//UINT32_MAX is one to one map (ex. if linkedTransform[2]==UINT32_MAX then cluster 2 maped to cluster2)

    uint minLinkedTransformByLinkedClusters = linkedClusters.front();//only for start, could be back() or what ever
    std::for_each( linkedClusters.begin(), linkedClusters.end(), [ this, &minLinkedTransformByLinkedClusters ]( uint cl){
        minLinkedTransformByLinkedClusters = std::min( minLinkedTransformByLinkedClusters, linkedTransform[cl] );
    });

    std::for_each( linkedClusters.begin(), linkedClusters.end(), [ this, &minLinkedTransformByLinkedClusters ]( uint cl){
        uint oldValue = linkedTransform[cl];
        std::replace( linkedTransform.begin() + 1, linkedTransform.end(), oldValue, minLinkedTransformByLinkedClusters);// +1 reserved element [0]
    });

    return;
}

void Clustering::concatenate_clusters()
{
    for(uint i = 0; i < linkedTransform.size(); ++i)//zeroes is one to one map (ex. if linkedTransform[2]==0 then cluster 2 maped to cluster 2)
    {
        if(linkedTransform[i] == UINT32_MAX)
        {
            linkedTransform[i] = i;
        }
    }

//raw cluster numbers or not code below
    std::vector<uint> distinctClusters(linkedTransform);
    std::sort(distinctClusters.begin(), distinctClusters.end());
    distinctClusters.erase(std::unique(distinctClusters.begin(), distinctClusters.end()), distinctClusters.end());

    std::vector<uint> transLinkedTransform(distinctClusters.back() + 1, 0);
    for(int i = 0; i < distinctClusters.size(); ++i)
    {
        transLinkedTransform[distinctClusters[i]] = i;
    }
    std::for_each(linkedTransform.begin(), linkedTransform.end(), [&transLinkedTransform](auto& lt){
        lt = transLinkedTransform[lt];
    });

    std::for_each(vIndexTransitionCluster.begin(), vIndexTransitionCluster.end(), [this](auto& itc){
        itc.clusterNumber = linkedTransform[ itc.clusterNumber ];
    });
}

void Clustering::remove_small_clusters_and_noise()
{
    auto maxClusterNumberIterator = std::max_element( vIndexTransitionCluster.begin(), vIndexTransitionCluster.end(), []( IndexTransitionCluster const & itc1, IndexTransitionCluster const & itc2){
        if( itc1.clusterNumber < itc2.clusterNumber )
        {
            return true;
        }
        else
        {
            return false;
        }
    });
    uint maxClusterNumber = maxClusterNumberIterator->clusterNumber;

    std::vector<uint>clusterOccurences(maxClusterNumber + 1, 0);
    for_each( vIndexTransitionCluster.begin(), vIndexTransitionCluster.end(), [&clusterOccurences]( IndexTransitionCluster const & itc ){
        if( itc.clusterNumber != 0 )// new itc without cluster occurrrence
        {
            clusterOccurences[itc.clusterNumber] += 1;
        }
    });

    vIndexTransitionCluster.erase(std::remove_if(vIndexTransitionCluster.begin(), vIndexTransitionCluster.end(), [this, &clusterOccurences](IndexTransitionCluster const & itc){//remove small clusters
        if( clusterOccurences[itc.clusterNumber] < minPts )
        {
            return true;
        }
        else
        {
            return false;
        }
    }), vIndexTransitionCluster.end());
}

double Distance::distance_fast( IndexTransitionCluster const & pixelA, IndexTransitionCluster const & pixelB )
{
    return abs( pixelA.row - pixelB.row ) + abs( pixelA.col - pixelB.col );
}

double Distance::distance_slow( IndexTransitionCluster const & pixelA, IndexTransitionCluster const & pixelB )
{
    return sqrt( pow( ( pixelA.row - pixelB.row ), 2.0 ) + pow( ( pixelA.col - pixelB.col ), 2.0 ) );
}<|endoftext|>


<commit_before>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0
#include <bse/bsemain.hh>
#include <bse/testing.hh>
#include "bse/internal.hh"

using Bse::printerr;
typedef Bse::IntegrityCheck::TestFunc TestFunc;

// == BSE_INTEGRITY_TEST Registry ==
struct TestEntry {
  TestFunc    test;
  const char *func;
  const char *file;
  int         line;
  TestEntry (const char *_file, int _line, const char *_func, TestFunc _test) :
    test (_test), func (_func), file (_file), line (_line)
  {}
};
static std::vector<TestEntry> *tests = NULL; // NOTE, this must be available for high priority early constructors

// == BSE_INTEGRITY_CHECK Activation ==
namespace Bse {
// Override Bse weak symbol to enable Bse's internal integrity tests, see bcore.hh
const bool IntegrityCheck::enabled = true;
// Registration function called for all integrity tests
void
IntegrityCheck::Test::register_test (const char *file, int line, const char *func, TestFunc test)
{
  if (!tests)
    tests = new std::vector<TestEntry>();
  tests->push_back (TestEntry (file, line, func, test));
}
} // Bse

static int      // for backtrace tests
my_compare_func (const void*, const void*)
{
  BSE_BACKTRACE();
  _Exit (0);
}

// == Main test program ==
static int
test_main (int argc, char *argv[])
{
  if (argc >= 2 && String ("--backtrace") == argv[1])
    {
      char dummy_array[3] = { 1, 2, 3 };
      qsort (dummy_array, 3, 1, my_compare_func);
    }
  else if (argc >= 2 && String ("--assert_return1") == argv[1])
    {
      assert_return (1, 0);
      return 0;
    }
  else if (argc >= 2 && String ("--assert_return0") == argv[1])
    {
      assert_return (0, 0);
      return 0;
    }
  else if (argc >= 2 && String ("--assert_return_unreached") == argv[1])
    {
      assert_return_unreached (0);
      return 0;
    }
  else if (argc >= 2 && String ("--fatal_error") == argv[1])
    {
      Bse::fatal_error ("got argument --fatal_error");
      return 0;
    }
  else if (argc >= 2 && String ("--return_unless0") == argv[1])
    {
      return_unless (0, 7);
      return 0;
    }
  else if (argc >= 2 && String ("--return_unless1") == argv[1])
    {
      return_unless (1, 8);
      return 0;
    }

  // integrity tests
  assert_return (Bse::IntegrityCheck::checks_enabled() == true, -1);

  if (tests)
    for (const auto &te : *tests)
      { // note, more than one space after "TESTING:" confuses emacs file:line matches
        printerr ("  TESTING: %s:%u: %s…\n", te.file, te.line, te.func);
        te.test();
        printerr ("    …DONE  (%s)\n", te.func);
      }

  return 0;
}

int
main (int argc, char *argv[])
{
  Bse::set_debug_flags (Bse::DebugFlags::SIGQUIT_ON_ABORT);
  return bse_init_and_test (&argc, argv, [&]() { return test_main (argc, argv); });
}
<commit_msg>BSE: integrity.cc: sort integrity tests by function name<commit_after>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0
#include <bse/bsemain.hh>
#include <bse/testing.hh>
#include "bse/internal.hh"

using Bse::printerr;
typedef Bse::IntegrityCheck::TestFunc TestFunc;

// == BSE_INTEGRITY_TEST Registry ==
struct TestEntry {
  TestFunc    test;
  const char *func;
  const char *file;
  int         line;
  TestEntry (const char *_file, int _line, const char *_func, TestFunc _test) :
    test (_test), func (_func), file (_file), line (_line)
  {}
};
static std::vector<TestEntry> *tests = NULL; // NOTE, this must be available for high priority early constructors

// == BSE_INTEGRITY_CHECK Activation ==
namespace Bse {
// Override Bse weak symbol to enable Bse's internal integrity tests, see bcore.hh
const bool IntegrityCheck::enabled = true;
// Registration function called for all integrity tests
void
IntegrityCheck::Test::register_test (const char *file, int line, const char *func, TestFunc test)
{
  if (!tests)
    tests = new std::vector<TestEntry>();
  tests->push_back (TestEntry (file, line, func, test));
}
} // Bse

static int      // for backtrace tests
my_compare_func (const void*, const void*)
{
  BSE_BACKTRACE();
  _Exit (0);
}

// == Main test program ==
static int
test_main (int argc, char *argv[])
{
  if (argc >= 2 && String ("--backtrace") == argv[1])
    {
      char dummy_array[3] = { 1, 2, 3 };
      qsort (dummy_array, 3, 1, my_compare_func);
    }
  else if (argc >= 2 && String ("--assert_return1") == argv[1])
    {
      assert_return (1, 0);
      return 0;
    }
  else if (argc >= 2 && String ("--assert_return0") == argv[1])
    {
      assert_return (0, 0);
      return 0;
    }
  else if (argc >= 2 && String ("--assert_return_unreached") == argv[1])
    {
      assert_return_unreached (0);
      return 0;
    }
  else if (argc >= 2 && String ("--fatal_error") == argv[1])
    {
      Bse::fatal_error ("got argument --fatal_error");
      return 0;
    }
  else if (argc >= 2 && String ("--return_unless0") == argv[1])
    {
      return_unless (0, 7);
      return 0;
    }
  else if (argc >= 2 && String ("--return_unless1") == argv[1])
    {
      return_unless (1, 8);
      return 0;
    }

  // integrity tests
  assert_return (Bse::IntegrityCheck::checks_enabled() == true, -1);

  if (!tests)
    return 0;

  std::sort (tests->begin(), tests->end(), [] (const TestEntry &a, const TestEntry &b) { return strcmp (a.func ? a.func : "", b.func ? b.func : "") < 0; });
  for (const auto &te : *tests)
    { // note, more than one space after "TESTING:" confuses emacs file:line matches
      printerr ("  TESTING: %s:%u: %s…\n", te.file, te.line, te.func);
      te.test();
      printerr ("    …DONE  (%s)\n", te.func);
    }

  return 0;
}

int
main (int argc, char *argv[])
{
  Bse::set_debug_flags (Bse::DebugFlags::SIGQUIT_ON_ABORT);
  return bse_init_and_test (&argc, argv, [&]() { return test_main (argc, argv); });
}
<|endoftext|>


<commit_before>//MIT License
//
//Copyright(c) 2016 Matthias Moeller
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files(the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions :
//
//The above copyright notice and this permission notice shall be included in all
//copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//SOFTWARE.

#ifndef __TYTI_STEAM_VDF_PARSER_H__
#define __TYTI_STEAM_VDF_PARSER_H__

#include <vector>
#include <unordered_map>
#include <utility>
#include <fstream>

#include <memory>
#include <stack>

namespace tyti
{
    namespace vdf
    {
        template<typename CharT>
        struct basic_object;

        template<typename iStreamT, typename charT = typename iStreamT::char_type>
        basic_object<charT> read(iStreamT& inStream, bool *ok = 0);

        namespace detail
        {
            ///////////////////////////////////////////////////////////////////////////
            //  Helper functions selecting the right encoding (char/wchar_T)
            ///////////////////////////////////////////////////////////////////////////

            template<typename T>
            struct literal_macro_help
            {
                static const char* result(const char* c, const wchar_t* wc)
                {
                    return c;
                }
                static const char result(char c, wchar_t wc)
                {
                    return c;
                }
            };

            template<>
            struct literal_macro_help<wchar_t>
            {
                static const wchar_t* result(const char* c, const wchar_t* wc)
                {
                    return wc;
                }
                static const wchar_t result(char c, wchar_t wc)
                {
                    return wc;
                }
            };
#define TYTI_L(type, text) vdf::detail::literal_macro_help<type>::result(text, L##text)

            ///////////////////////////////////////////////////////////////////////////
            //  Writer helper functions
            ///////////////////////////////////////////////////////////////////////////

            struct tabs
            {
                size_t t;
                tabs(size_t i) :t(i) {}
            };

            template<typename oStreamT>
            oStreamT& operator<<(oStreamT& s, tabs t)
            {
                for (; t.t > 0; --t.t)
                    s << "\t";
                return s;
            }
        } // end namespace detail

        ///////////////////////////////////////////////////////////////////////////
        //  Interface
        ///////////////////////////////////////////////////////////////////////////

        /// basic object node. Every object has a name and can contains attributes saved as key_value pairs or childrens
        template<typename CharT>
        struct basic_object
        {
            typedef CharT char_type;
            std::basic_string<char_type> name;
            std::unordered_map<std::basic_string<char_type>, std::basic_string<char_type> > attribs;
            std::unordered_map<std::basic_string<char_type>, std::shared_ptr< basic_object<char_type> > > childs;
        };

        typedef basic_object<char> object;
        typedef basic_object<wchar_t> wobject;

        /** \brief writes given object tree in vdf format to given stream.
        Uses tabs instead of whitespaces.
        */
        template<typename oStreamT, typename charT = typename oStreamT::char_type>
        void write(oStreamT& s, const basic_object<charT>& r, size_t t = 0)
        {
            using namespace detail;
            s << tabs(t) << TYTI_L(charT, '"') << r.name << TYTI_L(charT, "\"\n") << tabs(t) << TYTI_L(charT, "{\n");
            for (auto& i : r.attribs)
                s << tabs(t + 1) << TYTI_L(charT, '"') << i.first << TYTI_L(charT, "\"\t\t\"") << i.second << TYTI_L(charT, "\"\n");
            for (auto& i : r.childs)
                write(s, i, t + 1);
            s << tabs(t) << TYTI_L(charT, "}\n");
        }

        /** \brief Read VDF formatted sequences defined by the range [first, last).
        If the file is mailformatted, parser will try to read it until it can.
        @param first begin iterator
        @param end end iterator
        @param ok output bool. true, if parser successed, false, if parser failed
        */

        template<typename IterT, typename charT = typename IterT::value_type>
        basic_object<charT> read(IterT first, IterT last, bool* ok = 0)
        {
			if (ok)
				*ok = true;

			basic_object<charT> root;
			basic_object<charT>* cur = &root;
			std::stack< basic_object<charT>* > lvls;
			//read header
			// first, quoted name
			auto b = std::find(first, last, TYTI_L(charT, '\"'));
			auto bend = std::find(b + 1, last, TYTI_L(charT, '\"'));
			root.name = std::basic_string<charT>(b+1, bend);
			// second, get {}
			b = std::find(bend, last, TYTI_L(charT,'{'));
			lvls.push(&root);
			while (!lvls.empty() && b != last)
			{
				const std::basic_string<charT> startsym = TYTI_L(charT, "\"}");

				//find first starting attrib/child, or ending
				b = std::find_first_of(b, last, std::cbegin(startsym), std::cend(startsym));
				if (*b == '\"')
				{
					bend = std::find(b+1, last, TYTI_L(charT, '\"'));
					std::basic_string<charT> curName(b + 1, bend);
					b = bend + 1;

					const std::basic_string<charT> ecspsym = TYTI_L(charT, "\"{");
					b = std::find_first_of(b, last, std::cbegin(ecspsym), std::cend(ecspsym));
					if (*b == '\"')
					{
						bend = std::find(b+1, last, TYTI_L(charT, '\"'));
						auto value = std::basic_string<charT>(b + 1, bend);
						b = bend + 1;

						if (curName != TYTI_L(charT, "#include") && curName != TYTI_L(charT, "#base"))
							cur->attribs[curName] = value;
						else
						{
							std::basic_ifstream<charT> i(value);
							auto n = std::make_shared<basic_object<charT>>(read(i, ok));
							cur->childs[n->name] = n;
						}
					}
					else if (*b == '{')
					{
						lvls.push(cur);
						auto n = std::make_shared<basic_object<charT>>();
						cur->childs[curName] = n;
						cur = n.get();
						cur->name = curName;
						++b;
					}
				}
				else if (*b == '}')
				{
					cur = lvls.top();
					lvls.pop();
					++b;
				}
			}
            return root;
        }

        /** \brief Loads a stream (e.g. filestream) into the memory and parses the vdf formatted data.
        */
        template<typename iStreamT, typename charT>
        basic_object<charT> read(iStreamT& inStream, bool *ok)
        {
            // cache the file
            std::basic_string<charT> str;
            inStream.seekg(0, std::ios::end);
            str.resize(inStream.tellg());
            if (str.empty())
                return basic_object<charT>();

            inStream.seekg(0, std::ios::beg);
            inStream.read(&str[0], str.size());
            inStream.close();

            // parse it
            return read(str.begin(), str.end(), ok);
        }

    } // end namespace vdf
} // end namespace tyti
#ifndef TYTI_NO_L_UNDEF
#undef TYTI_L
#endif

#endif //__TYTI_STEAM_VDF_PARSER_H__<commit_msg>remove forward decl<commit_after>//MIT License
//
//Copyright(c) 2016 Matthias Moeller
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files(the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions :
//
//The above copyright notice and this permission notice shall be included in all
//copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//SOFTWARE.

#ifndef __TYTI_STEAM_VDF_PARSER_H__
#define __TYTI_STEAM_VDF_PARSER_H__

#include <vector>
#include <unordered_map>
#include <utility>
#include <fstream>

#include <memory>
#include <stack>

namespace tyti
{
    namespace vdf
    {
        namespace detail
        {
            ///////////////////////////////////////////////////////////////////////////
            //  Helper functions selecting the right encoding (char/wchar_T)
            ///////////////////////////////////////////////////////////////////////////

            template<typename T>
            struct literal_macro_help
            {
                static const char* result(const char* c, const wchar_t* wc)
                {
                    return c;
                }
                static const char result(char c, wchar_t wc)
                {
                    return c;
                }
            };

            template<>
            struct literal_macro_help<wchar_t>
            {
                static const wchar_t* result(const char* c, const wchar_t* wc)
                {
                    return wc;
                }
                static const wchar_t result(char c, wchar_t wc)
                {
                    return wc;
                }
            };
#define TYTI_L(type, text) vdf::detail::literal_macro_help<type>::result(text, L##text)

            ///////////////////////////////////////////////////////////////////////////
            //  Writer helper functions
            ///////////////////////////////////////////////////////////////////////////

            struct tabs
            {
                size_t t;
                tabs(size_t i) :t(i) {}
            };

            template<typename oStreamT>
            oStreamT& operator<<(oStreamT& s, tabs t)
            {
                for (; t.t > 0; --t.t)
                    s << "\t";
                return s;
            }
        } // end namespace detail

        ///////////////////////////////////////////////////////////////////////////
        //  Interface
        ///////////////////////////////////////////////////////////////////////////

        /// basic object node. Every object has a name and can contains attributes saved as key_value pairs or childrens
        template<typename CharT>
        struct basic_object
        {
            typedef CharT char_type;
            std::basic_string<char_type> name;
            std::unordered_map<std::basic_string<char_type>, std::basic_string<char_type> > attribs;
            std::unordered_map<std::basic_string<char_type>, std::shared_ptr< basic_object<char_type> > > childs;
        };

        typedef basic_object<char> object;
        typedef basic_object<wchar_t> wobject;

        /** \brief writes given object tree in vdf format to given stream.
        Uses tabs instead of whitespaces.
        */
        template<typename oStreamT, typename charT = typename oStreamT::char_type>
        void write(oStreamT& s, const basic_object<charT>& r, size_t t = 0)
        {
            using namespace detail;
            s << tabs(t) << TYTI_L(charT, '"') << r.name << TYTI_L(charT, "\"\n") << tabs(t) << TYTI_L(charT, "{\n");
            for (auto& i : r.attribs)
                s << tabs(t + 1) << TYTI_L(charT, '"') << i.first << TYTI_L(charT, "\"\t\t\"") << i.second << TYTI_L(charT, "\"\n");
            for (auto& i : r.childs)
                write(s, i, t + 1);
            s << tabs(t) << TYTI_L(charT, "}\n");
        }

        /** \brief Read VDF formatted sequences defined by the range [first, last).
        If the file is mailformatted, parser will try to read it until it can.
        @param first begin iterator
        @param end end iterator
        @param ok output bool. true, if parser successed, false, if parser failed
        */

        template<typename IterT, typename charT = typename IterT::value_type>
        basic_object<charT> read(IterT first, IterT last, bool* ok = 0)
        {
			//todo: error handling
			if (ok)
				*ok = true;

			basic_object<charT> root;
			basic_object<charT>* cur = &root;
			std::stack< basic_object<charT>* > lvls;
			//read header
			// first, quoted name
			auto b = std::find(first, last, TYTI_L(charT, '\"'));
			auto bend = std::find(b + 1, last, TYTI_L(charT, '\"'));
			root.name = std::basic_string<charT>(b+1, bend);
			// second, get {}
			b = std::find(bend, last, TYTI_L(charT,'{'));
			lvls.push(&root);
			while (!lvls.empty() && b != last)
			{
				const std::basic_string<charT> startsym = TYTI_L(charT, "\"}");

				//find first starting attrib/child, or ending
				b = std::find_first_of(b, last, std::cbegin(startsym), std::cend(startsym));
				if (*b == '\"')
				{
					bend = std::find(b+1, last, TYTI_L(charT, '\"'));
					std::basic_string<charT> curName(b + 1, bend);
					b = bend + 1;

					const std::basic_string<charT> ecspsym = TYTI_L(charT, "\"{");
					b = std::find_first_of(b, last, std::cbegin(ecspsym), std::cend(ecspsym));
					if (*b == '\"')
					{
						bend = std::find(b+1, last, TYTI_L(charT, '\"'));
						auto value = std::basic_string<charT>(b + 1, bend);
						b = bend + 1;

						if (curName != TYTI_L(charT, "#include") && curName != TYTI_L(charT, "#base"))
							cur->attribs[curName] = value;
						else
						{
							std::basic_ifstream<charT> i(value);
							auto n = std::make_shared<basic_object<charT>>(read(i, ok));
							cur->childs[n->name] = n;
						}
					}
					else if (*b == '{')
					{
						lvls.push(cur);
						auto n = std::make_shared<basic_object<charT>>();
						cur->childs[curName] = n;
						cur = n.get();
						cur->name = curName;
						++b;
					}
				}
				else if (*b == '}')
				{
					cur = lvls.top();
					lvls.pop();
					++b;
				}
			}
            return root;
        }

        /** \brief Loads a stream (e.g. filestream) into the memory and parses the vdf formatted data.
        */
        template<typename iStreamT, typename charT = iStreamT::char_type >
        basic_object<charT> read(iStreamT& inStream, bool *ok = 0)
        {
            // cache the file
            std::basic_string<charT> str;
            inStream.seekg(0, std::ios::end);
            str.resize(inStream.tellg());
            if (str.empty())
                return basic_object<charT>();

            inStream.seekg(0, std::ios::beg);
            inStream.read(&str[0], str.size());
            inStream.close();

            // parse it
            return read(str.begin(), str.end(), ok);
        }

    } // end namespace vdf
} // end namespace tyti
#ifndef TYTI_NO_L_UNDEF
#undef TYTI_L
#endif

#endif //__TYTI_STEAM_VDF_PARSER_H__<|endoftext|>


<commit_before>/******************************************************************************
 *                    _   _____   __________                                  *
 *                   | | / / _ | / __/_  __/     Visibility                   *
 *                   | |/ / __ |_\ \  / /          Across                     *
 *                   |___/_/ |_/___/ /_/       Space and Time                 *
 *                                                                            *
 * This file is part of VAST. It is subject to the license terms in the       *
 * LICENSE file found in the top-level directory of this distribution and at  *
 * http://vast.io/license. No part of VAST, including this file, may be       *
 * copied, modified, propagated, or distributed except according to the terms *
 * contained in the LICENSE file.                                             *
 ******************************************************************************/

#include "vast/system/configuration.hpp"

#include <algorithm>
#include <iostream>

#include "vast/config.hpp"

#include <caf/message_builder.hpp>
#include <caf/io/middleman.hpp>
#ifdef VAST_USE_OPENCL
#include <caf/opencl/manager.hpp>
#endif
#ifdef VAST_USE_OPENSSL
#include <caf/openssl/manager.hpp>
#endif

#include "vast/detail/add_error_categories.hpp"
#include "vast/detail/add_message_types.hpp"
#include "vast/detail/adjust_resource_consumption.hpp"
#include "vast/detail/assert.hpp"
#include "vast/detail/string.hpp"
#include "vast/detail/system.hpp"
#include "vast/filesystem.hpp"
#include "vast/synopsis_factory.hpp"
#include "vast/table_slice_builder_factory.hpp"
#include "vast/table_slice_factory.hpp"
#include "vast/value_index.hpp"
#include "vast/value_index_factory.hpp"

using namespace caf;

namespace vast::system {

namespace {

template <class... Ts>
void initialize_factories() {
  (factory<Ts>::initialize(), ...);
}

} // namespace <anonymous>

configuration::configuration() {
  detail::add_message_types(*this);
  detail::add_error_categories(*this);
  // Use 'vast.conf' instead of generic 'caf-application.ini' and fall back to
  // $PREFIX/etc/vast if no local vast.conf exists.
  if ((path::current() / "vast.conf").is_regular_file()) {
    config_file_path = "vast.conf";
  } else {
    auto global_conf = path{VAST_INSTALL_PREFIX} / "etc" / "vast";
    config_file_path = global_conf.str();
  }
  // Load I/O module.
  load<io::middleman>();
  // GPU acceleration.
#ifdef VAST_USE_OPENCL
  load<opencl::manager>();
#endif
  opt_group{custom_options_, "vast"}
  .add<size_t>("table-slice-size",
               "Maximum size for sources that generate table slices.");

  initialize_factories<synopsis, table_slice, table_slice_builder,
                       value_index>();
}

caf::error configuration::parse(int argc, char** argv) {
  VAST_ASSERT(argc > 0);
  VAST_ASSERT(argv != nullptr);
  command_line.assign(argv + 1, argv + argc);
  // Move CAF options to the end of the command line, parse them, and then
  // remove them.
  auto is_vast_opt = [](auto& x) { return !starts_with(x, "--caf#"); };
  auto caf_opt = std::stable_partition(command_line.begin(),
                                       command_line.end(), is_vast_opt);
  std::vector<std::string> caf_args;
  std::move(caf_opt, command_line.end(), std::back_inserter(caf_args));
  command_line.erase(caf_opt, command_line.end());
  // Remove caf# suffix for CAF parser.
  for (auto& arg : caf_args)
    arg.erase(2, 4);
  return actor_system_config::parse(std::move(caf_args));
}

} // namespace vast::system
<commit_msg>Put global config file in its own directory<commit_after>/******************************************************************************
 *                    _   _____   __________                                  *
 *                   | | / / _ | / __/_  __/     Visibility                   *
 *                   | |/ / __ |_\ \  / /          Across                     *
 *                   |___/_/ |_/___/ /_/       Space and Time                 *
 *                                                                            *
 * This file is part of VAST. It is subject to the license terms in the       *
 * LICENSE file found in the top-level directory of this distribution and at  *
 * http://vast.io/license. No part of VAST, including this file, may be       *
 * copied, modified, propagated, or distributed except according to the terms *
 * contained in the LICENSE file.                                             *
 ******************************************************************************/

#include "vast/system/configuration.hpp"

#include <algorithm>
#include <iostream>

#include "vast/config.hpp"

#include <caf/message_builder.hpp>
#include <caf/io/middleman.hpp>
#ifdef VAST_USE_OPENCL
#include <caf/opencl/manager.hpp>
#endif
#ifdef VAST_USE_OPENSSL
#include <caf/openssl/manager.hpp>
#endif

#include "vast/detail/add_error_categories.hpp"
#include "vast/detail/add_message_types.hpp"
#include "vast/detail/adjust_resource_consumption.hpp"
#include "vast/detail/assert.hpp"
#include "vast/detail/string.hpp"
#include "vast/detail/system.hpp"
#include "vast/filesystem.hpp"
#include "vast/synopsis_factory.hpp"
#include "vast/table_slice_builder_factory.hpp"
#include "vast/table_slice_factory.hpp"
#include "vast/value_index.hpp"
#include "vast/value_index_factory.hpp"

using namespace caf;

namespace vast::system {

namespace {

template <class... Ts>
void initialize_factories() {
  (factory<Ts>::initialize(), ...);
}

} // namespace <anonymous>

configuration::configuration() {
  detail::add_message_types(*this);
  detail::add_error_categories(*this);
  // Use 'vast.conf' instead of generic 'caf-application.ini' and fall back to
  // $PREFIX/etc/vast if no local vast.conf exists.
  if ((path::current() / "vast.conf").is_regular_file()) {
    config_file_path = "vast.conf";
  } else {
    auto global_conf = path{VAST_INSTALL_PREFIX} / "etc" / "vast" / "vast.conf";
    config_file_path = global_conf.str();
  }
  // Load I/O module.
  load<io::middleman>();
  // GPU acceleration.
#ifdef VAST_USE_OPENCL
  load<opencl::manager>();
#endif
  opt_group{custom_options_, "vast"}
  .add<size_t>("table-slice-size",
               "Maximum size for sources that generate table slices.");

  initialize_factories<synopsis, table_slice, table_slice_builder,
                       value_index>();
}

caf::error configuration::parse(int argc, char** argv) {
  VAST_ASSERT(argc > 0);
  VAST_ASSERT(argv != nullptr);
  command_line.assign(argv + 1, argv + argc);
  // Move CAF options to the end of the command line, parse them, and then
  // remove them.
  auto is_vast_opt = [](auto& x) { return !starts_with(x, "--caf#"); };
  auto caf_opt = std::stable_partition(command_line.begin(),
                                       command_line.end(), is_vast_opt);
  std::vector<std::string> caf_args;
  std::move(caf_opt, command_line.end(), std::back_inserter(caf_args));
  command_line.erase(caf_opt, command_line.end());
  // Remove caf# suffix for CAF parser.
  for (auto& arg : caf_args)
    arg.erase(2, 4);
  return actor_system_config::parse(std::move(caf_args));
}

} // namespace vast::system
<|endoftext|>