<commit_before>#include <stdio.h>
#include <string.h>

#include <osg/Geode>
#include <osg/Group>
#include <osg/Notify>

#include <osgDB/Registry>
#include <osgDB/FileNameUtils>

#include "ConvertToPerformer.h"
#include "ConvertFromPerformer.h"

#include <Performer/pfdu.h>
#include <Performer/pr/pfTexture.h>

extern "C" {
extern pfNode *pfdLoadFile_pfb( const char *);
extern int pfdStoreFile_pfb( pfNode *, const char *);
}

class ReaderWriterPFB : public osgDB::ReaderWriter
{

    public:

        ReaderWriterPFB();
        ~ReaderWriterPFB();

        void initPerformer();

        virtual const char* className() { return "Performer Reader/Writer"; }
        virtual bool acceptsExtension(const std::string& extension) { return extension=="pfb"; }

        virtual osg::Image* readImage(const std::string& fileName, const osgDB::ReaderWriter::Options*)
        {
            osg::notify(osg::INFO)<<   "ReaderWriterPFB::readImage( "<<fileName.c_str()<<" )\n";

            initPerformer();

            pfTexture* tex = new pfTexture;
            if (tex->loadFile(fileName.c_str()))
            {
                int s=0;
                int t=0;
                int r=0;
                int comp=0;
                unsigned int* imageData = NULL;

                tex->getImage(&imageData,&comp,&s,&t,&r);

                int internalFormat = comp;

                unsigned int pixelFormat =
                    comp == 1 ? GL_LUMINANCE :
                comp == 2 ? GL_LUMINANCE_ALPHA :
                comp == 3 ? GL_RGB :
                comp == 4 ? GL_RGBA : (GLenum)-1;

                unsigned int dataType = GL_UNSIGNED_BYTE;

                osg::Image* image = new osg::Image;
                image->setFileName(fileName.c_str());
                image->setImage(s,t,r,
                    internalFormat,
                    pixelFormat,
                    dataType,
                    (unsigned char*)imageData);

                return image;
            }

            return NULL;
        }

        virtual osg::Node* readNode(const std::string& fileName, const osgDB::ReaderWriter::Options*)
        {
            osg::notify(osg::INFO)<<   "ReaderWriterPFB::readNode( "<<fileName.c_str()<<" )\n";

            initPerformer();
            pfNode* root = pfdLoadFile_pfb(fileName.c_str());

            ConvertFromPerformer converter;
            return converter.convert(root);

        }

        virtual bool writeNode(const osg::Node& node,const std::string& fileName, const osgDB::ReaderWriter::Options*)
        {
            std::string ext = osgDB::getLowerCaseFileExtension(fileName);
            if (!acceptsExtension(ext)) return false;

            osg::notify(osg::INFO)<<   "ReaderWriterPFB::writeNode( "<<fileName.c_str()<<" )\n";
            initPerformer();
            ConvertToPerformer converter;
            pfNode* root = converter.convert(&node);
            if (root)
            {
                return pfdStoreFile_pfb(root,fileName.c_str())!=0;
            }
            else
            {
                return false;
            }
        }

    protected:

        bool _performerInitialised;

};

ReaderWriterPFB::ReaderWriterPFB()
{
    _performerInitialised = false;
}

ReaderWriterPFB::~ReaderWriterPFB()
{
}

void ReaderWriterPFB::initPerformer()
{
    if (_performerInitialised) return;

    _performerInitialised = true;

    pfMultiprocess(0);

    pfInit();

    //     FileList::iterator itr;
    //     for(itr=filelist.begin();itr!=filelist.end();++itr)
    //     {
    //         pfdInitConverter((*itr).c_str());
    //     }

    pfConfig();

}

// now register with sgRegistry to instantiate the above
// reader/writer.
osgDB::RegisterReaderWriterProxy<ReaderWriterPFB> g_readerWriter_PFB_Proxy;
<commit_msg>Added #ifdef to Performer ReaderWriterPFB so that pfdLoadFile is used under IRIX and pfdLoadFile_pfb is used under Linux.<commit_after>#include <stdio.h>
#include <string.h>

#include <osg/Geode>
#include <osg/Group>
#include <osg/Notify>

#include <osgDB/Registry>
#include <osgDB/FileNameUtils>

#include "ConvertToPerformer.h"
#include "ConvertFromPerformer.h"

#include <Performer/pfdu.h>
#include <Performer/pr/pfTexture.h>

extern "C" {
extern pfNode *pfdLoadFile_pfb( const char *);
extern int pfdStoreFile_pfb( pfNode *, const char *);
}

class ReaderWriterPFB : public osgDB::ReaderWriter
{

    public:

        ReaderWriterPFB();
        ~ReaderWriterPFB();

        void initPerformer();

        virtual const char* className() { return "Performer Reader/Writer"; }
        virtual bool acceptsExtension(const std::string& extension) { return extension=="pfb"; }

        virtual osg::Image* readImage(const std::string& fileName, const osgDB::ReaderWriter::Options*)
        {
            osg::notify(osg::INFO)<<   "ReaderWriterPFB::readImage( "<<fileName.c_str()<<" )\n";

            initPerformer();

            pfTexture* tex = new pfTexture;
            if (tex->loadFile(fileName.c_str()))
            {
                int s=0;
                int t=0;
                int r=0;
                int comp=0;
                unsigned int* imageData = NULL;

                tex->getImage(&imageData,&comp,&s,&t,&r);

                int internalFormat = comp;

                unsigned int pixelFormat =
                    comp == 1 ? GL_LUMINANCE :
                comp == 2 ? GL_LUMINANCE_ALPHA :
                comp == 3 ? GL_RGB :
                comp == 4 ? GL_RGBA : (GLenum)-1;

                unsigned int dataType = GL_UNSIGNED_BYTE;

                osg::Image* image = new osg::Image;
                image->setFileName(fileName.c_str());
                image->setImage(s,t,r,
                    internalFormat,
                    pixelFormat,
                    dataType,
                    (unsigned char*)imageData);

                return image;
            }

            return NULL;
        }

        virtual osg::Node* readNode(const std::string& fileName, const osgDB::ReaderWriter::Options*)
        {
            osg::notify(osg::INFO)<<   "ReaderWriterPFB::readNode( "<<fileName.c_str()<<" )\n";

            initPerformer();

            #ifdef __sgi
            pfNode* root = pfdLoadFile(fileName.c_str());
            #else
            pfNode* root = pfdLoadFile_pfb(fileName.c_str());
            #endif

            ConvertFromPerformer converter;
            return converter.convert(root);

        }

        virtual bool writeNode(const osg::Node& node,const std::string& fileName, const osgDB::ReaderWriter::Options*)
        {
            std::string ext = osgDB::getLowerCaseFileExtension(fileName);
            if (!acceptsExtension(ext)) return false;

            osg::notify(osg::INFO)<<   "ReaderWriterPFB::writeNode( "<<fileName.c_str()<<" )\n";
            initPerformer();
            ConvertToPerformer converter;
            pfNode* root = converter.convert(&node);
            if (root)
            {
                return pfdStoreFile_pfb(root,fileName.c_str())!=0;
            }
            else
            {
                return false;
            }
        }

    protected:

        bool _performerInitialised;

};

ReaderWriterPFB::ReaderWriterPFB()
{
    _performerInitialised = false;
}

ReaderWriterPFB::~ReaderWriterPFB()
{
}

void ReaderWriterPFB::initPerformer()
{
    if (_performerInitialised) return;

    _performerInitialised = true;

    pfMultiprocess(0);

    pfInit();

    //     FileList::iterator itr;
    //     for(itr=filelist.begin();itr!=filelist.end();++itr)
    //     {
    //         pfdInitConverter((*itr).c_str());
    //     }

    pfConfig();

}

// now register with sgRegistry to instantiate the above
// reader/writer.
osgDB::RegisterReaderWriterProxy<ReaderWriterPFB> g_readerWriter_PFB_Proxy;
<|endoftext|>


<commit_before>// -*-c++-*-

/*
 * $Id$
 *
 * STL importer for OpenSceneGraph.
 * Copyright (c)2004 Ulrich Hertlein <u.hertlein@sandbox.de>
 *
 * 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <osg/Notify>
#include <osg/Endian>

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

#include <osg/Geode>
#include <osg/Geometry>

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>

/**
 * STL importer for OpenSceneGraph.
 */
class ReaderWriterSTL : public osgDB::ReaderWriter
{
public:
    ReaderWriterSTL() {}

    virtual const char* className() const {
        return "STL Reader/Writer";
    }

    virtual bool acceptsExtension(const std::string& extension) const {
        return
            osgDB::equalCaseInsensitive(extension,"stl") ? true :
            osgDB::equalCaseInsensitive(extension,"sta") ? true : false;
    }

    virtual ReadResult readNode(const std::string& fileName, const osgDB::ReaderWriter::Options*) const;

private:

    struct ReaderObject
    {
        ReaderObject():
            _generateNormal(true),
            _numFacets(0) {}

        bool _generateNormal;
        unsigned int _numFacets;

        osg::ref_ptr<osg::Vec3Array> _vertex;
        osg::ref_ptr<osg::Vec3Array> _normal;
        osg::ref_ptr<osg::Vec4Array> _color;

        bool readStlAscii(FILE* fp);
        bool readStlBinary(FILE* fp);
    };
};

// Register with Registry to instantiate the above reader/writer.
osgDB::RegisterReaderWriterProxy<ReaderWriterSTL> g_readerWriter_STL_Proxy;

/*
 * STL
 */
struct StlHeader {
    char text[80];
    unsigned int numFacets;
};
const unsigned int sizeof_StlHeader = 84;

struct StlVector {
    float x,y,z;
};
struct StlFacet {
    StlVector normal;
    StlVector vertex[3];
    unsigned short color;
};
const unsigned int sizeof_StlFacet = 50;

const unsigned short StlHasColor = 0x8000;
const unsigned short StlColorSize = 0x1f;        // 5 bit
const float StlColorDepth = float(StlColorSize); // 2^5 - 1

// Read node
osgDB::ReaderWriter::ReadResult ReaderWriterSTL::readNode(const std::string& file, const osgDB::ReaderWriter::Options* options) const
{
    std::string ext = osgDB::getLowerCaseFileExtension(file);
    if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;

    std::string fileName = osgDB::findDataFile( file, options );
    if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;

    osg::notify(osg::INFO) << "ReaderWriterSTL::readNode(" << fileName.c_str() << ")\n";

    // determine ASCII vs. binary mode
    FILE* fp = fopen(fileName.c_str(), "r");
    if (!fp) {
        return ReadResult::FILE_NOT_HANDLED;
    }

    ReaderObject readerObject;

    // assumes "unsigned int" is 4 bytes...
    StlHeader header;
    if (fread((void*) &header, sizeof(header), 1, fp) != 1) {
        fclose(fp);
        return ReadResult::FILE_NOT_HANDLED;
    }
    bool isBinary = false;

    // calculate expected file length from number of facets
    unsigned int expectFacets = header.numFacets;
    if (osg::getCpuByteOrder() == osg::BigEndian) {
        osg::swapBytes4((char*) &expectFacets);
    }
    off_t expectLen = sizeof_StlHeader + expectFacets * sizeof_StlFacet;

    struct stat stb;
    if (fstat(fileno(fp), &stb) < 0) {
        osg::notify(osg::FATAL) << "ReaderWriterSTL::readNode: Unable to stat '" << fileName << "'" << std::endl;
        fclose(fp);
        return ReadResult::FILE_NOT_HANDLED;
    }
    if (stb.st_size == expectLen) {
        // assume binary
        readerObject._numFacets = expectFacets;
        isBinary = true;
    }
    else if (strstr(header.text, "solid") != 0) {
        // assume ASCII
        isBinary = false;
    }
    else {
        osg::notify(osg::FATAL) << "ReaderWriterSTL::readNode(" << fileName.c_str() << ") unable to determine file format" << std::endl;
        fclose(fp);
        return ReadResult::FILE_NOT_HANDLED;
    }

    // read
    rewind(fp);
    bool ok = (isBinary ? readerObject.readStlBinary(fp) : readerObject.readStlAscii(fp));
    fclose(fp);

    if (!ok) {
        return ReadResult::FILE_NOT_HANDLED;
    }
    osg::notify(osg::NOTICE) << "### found " << readerObject._numFacets << " facets" << std::endl;

    /*
     * setup geometry
     */
    osg::Geometry* geom = new osg::Geometry;
    geom->setVertexArray(readerObject._vertex.get());

    geom->setNormalArray(readerObject._normal.get());
    geom->setNormalBinding(osg::Geometry::BIND_PER_PRIMITIVE);

    if (readerObject._color.valid()) {
        osg::notify(osg::NOTICE) << "### with color" << std::endl;
        geom->setColorArray(readerObject._color.get());
        geom->setColorBinding(osg::Geometry::BIND_PER_PRIMITIVE);
    }

    geom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::TRIANGLES, 0, readerObject._numFacets*3));

    osg::Geode* geode = new osg::Geode;
    geode->addDrawable(geom);

    return geode;
}

/**********************************************************************
 *
 * Private
 *
 **********************************************************************/

bool ReaderWriterSTL::ReaderObject::readStlAscii(FILE* fp)
{
    unsigned int vertexCount = 0;
    unsigned int facetIndex[] = { 0,0,0 };
    unsigned int vertexIndex = 0;
    unsigned int normalIndex = 0;

    char buf[256];
    while (fgets(buf, sizeof(buf), fp)) {

        // strip '\n' or '\r\n' and trailing whitespace
        unsigned int len = strlen(buf)-1;
        while (len && (buf[len] == '\n' || buf[len] == '\r' || isspace(buf[len]))) {
            buf[len--] = '\0';
        }
        if (len == 0 || buf[0] == '\0') {
            continue;
        }

        // strip leading whitespace
        char* bp = buf;
        while (isspace(*bp)) {
            ++bp;
        }

        if (strncmp(bp, "vertex", 6) == 0) {
            float vx,vy,vz;
            if (sscanf(bp+6, "%f %f %f", &vx,&vy,&vz) == 3) {
                if (!_vertex.valid())
                    _vertex = new osg::Vec3Array;

                vertexIndex = _vertex->size();
                if (vertexCount < 3) {
                    _vertex->push_back(osg::Vec3(vx,vy,vz));
                    facetIndex[vertexCount++] = vertexIndex;
                }
                else {
                    /*
                     * There are some invalid ASCII files around (at least one ;-)
                     * that have more than three vertices per facet - add an
                     * additional triangle.
                     */
                    _normal->push_back((*_normal)[normalIndex]);
                    _vertex->push_back((*_vertex)[facetIndex[0]]);
                    _vertex->push_back((*_vertex)[facetIndex[2]]);
                    _vertex->push_back(osg::Vec3(vx,vy,vz));
                    facetIndex[1] = facetIndex[2];
                    facetIndex[2] = vertexIndex;
                    _numFacets++;
                }
            }
        }
        else if (strncmp(bp, "facet", 5) == 0) {
            float nx,ny,nz;
            if (sscanf(bp+5, "%*s %f %f %f", &nx,&ny,&nz) == 3) {

                if (!_normal.valid())
                    _normal = new osg::Vec3Array;

                osg::Vec3 normal(nx,ny,nz);
                normal.normalize();

                normalIndex = _normal->size();
                _normal->push_back(normal);

                _numFacets++;
                vertexCount = 0;
            }
        }
        else if (strncmp(bp, "solid", 5) == 0) {
            osg::notify(osg::NOTICE) << "### parsing '" << bp + 6 << "'" << std::endl;
        }
    }

    return true;
}

bool ReaderWriterSTL::ReaderObject::readStlBinary(FILE* fp)
{
    // seek to beginning of facets
    ::fseek(fp, sizeof_StlHeader, SEEK_SET);

    StlFacet facet;
    for (unsigned int i = 0; i < _numFacets; ++i) {

        if (::fread((void*) &facet, sizeof_StlFacet, 1, fp) != 1) {
            osg::notify(osg::FATAL) << "ReaderWriterSTL::readStlBinary: Failed to read facet " << i << std::endl;
            return false;
        }

        // vertices
        if (!_vertex)
            _vertex = new osg::Vec3Array;
        osg::Vec3 v0(facet.vertex[0].x,facet.vertex[0].y,facet.vertex[0].z);
        osg::Vec3 v1(facet.vertex[1].x,facet.vertex[1].y,facet.vertex[1].z);
        osg::Vec3 v2(facet.vertex[2].x,facet.vertex[2].y,facet.vertex[2].z);
        _vertex->push_back(v0);
        _vertex->push_back(v1);
        _vertex->push_back(v2);

        // per-facet normal
        osg::Vec3 normal;
        if (_generateNormal) {
            osg::Vec3 d01 = v1 - v0;
            osg::Vec3 d02 = v2 - v0;
            normal = d01 ^ d02;
            normal.normalize();
        }
        else {
            normal.set(facet.normal.x,facet.normal.y,facet.normal.z);
        }
        if (!_normal.valid())
            _normal = new osg::Vec3Array;
        _normal->push_back(normal);

        /*
         * color extension
         * RGB555 with most-significat bit indicating if color is present
         */
        if (facet.color & StlHasColor) {
            if (!_color) {
                _color = new osg::Vec4Array;
            }
            float r = ((facet.color >> 10) & StlColorSize) / StlColorDepth;
            float g = ((facet.color >> 5) & StlColorSize) / StlColorDepth;
            float b = (facet.color & StlColorSize) / StlColorDepth;
            _color->push_back(osg::Vec4(r,g,b,1.0f));
        }
    }

    return true;
}
<commit_msg>Added smoothing and tri strip pass.<commit_after>// -*-c++-*-

/*
 * $Id$
 *
 * STL importer for OpenSceneGraph.
 * Copyright (c)2004 Ulrich Hertlein <u.hertlein@sandbox.de>
 *
 * 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <osg/Notify>
#include <osg/Endian>

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

#include <osgUtil/TriStripVisitor>
#include <osgUtil/SmoothingVisitor>

#include <osg/Geode>
#include <osg/Geometry>

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>

/**
 * STL importer for OpenSceneGraph.
 */
class ReaderWriterSTL : public osgDB::ReaderWriter
{
public:
    ReaderWriterSTL() {}

    virtual const char* className() const {
        return "STL Reader/Writer";
    }

    virtual bool acceptsExtension(const std::string& extension) const {
        return
            osgDB::equalCaseInsensitive(extension,"stl") ? true :
            osgDB::equalCaseInsensitive(extension,"sta") ? true : false;
    }

    virtual ReadResult readNode(const std::string& fileName, const osgDB::ReaderWriter::Options*) const;

private:

    struct ReaderObject
    {
        ReaderObject():
            _generateNormal(true),
            _numFacets(0) {}

        bool _generateNormal;
        unsigned int _numFacets;

        osg::ref_ptr<osg::Vec3Array> _vertex;
        osg::ref_ptr<osg::Vec3Array> _normal;
        osg::ref_ptr<osg::Vec4Array> _color;

        bool readStlAscii(FILE* fp);
        bool readStlBinary(FILE* fp);
    };
};

// Register with Registry to instantiate the above reader/writer.
osgDB::RegisterReaderWriterProxy<ReaderWriterSTL> g_readerWriter_STL_Proxy;

/*
 * STL
 */
struct StlHeader {
    char text[80];
    unsigned int numFacets;
};
const unsigned int sizeof_StlHeader = 84;

struct StlVector {
    float x,y,z;
};
struct StlFacet {
    StlVector normal;
    StlVector vertex[3];
    unsigned short color;
};
const unsigned int sizeof_StlFacet = 50;

const unsigned short StlHasColor = 0x8000;
const unsigned short StlColorSize = 0x1f;        // 5 bit
const float StlColorDepth = float(StlColorSize); // 2^5 - 1

// Read node
osgDB::ReaderWriter::ReadResult ReaderWriterSTL::readNode(const std::string& file, const osgDB::ReaderWriter::Options* options) const
{
    std::string ext = osgDB::getLowerCaseFileExtension(file);
    if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;

    std::string fileName = osgDB::findDataFile( file, options );
    if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;

    osg::notify(osg::INFO) << "ReaderWriterSTL::readNode(" << fileName.c_str() << ")\n";

    // determine ASCII vs. binary mode
    FILE* fp = fopen(fileName.c_str(), "r");
    if (!fp) {
        return ReadResult::FILE_NOT_HANDLED;
    }

    ReaderObject readerObject;

    // assumes "unsigned int" is 4 bytes...
    StlHeader header;
    if (fread((void*) &header, sizeof(header), 1, fp) != 1) {
        fclose(fp);
        return ReadResult::FILE_NOT_HANDLED;
    }
    bool isBinary = false;

    // calculate expected file length from number of facets
    unsigned int expectFacets = header.numFacets;
    if (osg::getCpuByteOrder() == osg::BigEndian) {
        osg::swapBytes4((char*) &expectFacets);
    }
    off_t expectLen = sizeof_StlHeader + expectFacets * sizeof_StlFacet;

    struct stat stb;
    if (fstat(fileno(fp), &stb) < 0) {
        osg::notify(osg::FATAL) << "ReaderWriterSTL::readNode: Unable to stat '" << fileName << "'" << std::endl;
        fclose(fp);
        return ReadResult::FILE_NOT_HANDLED;
    }
    if (stb.st_size == expectLen) {
        // assume binary
        readerObject._numFacets = expectFacets;
        isBinary = true;
    }
    else if (strstr(header.text, "solid") != 0) {
        // assume ASCII
        isBinary = false;
    }
    else {
        osg::notify(osg::FATAL) << "ReaderWriterSTL::readNode(" << fileName.c_str() << ") unable to determine file format" << std::endl;
        fclose(fp);
        return ReadResult::FILE_NOT_HANDLED;
    }

    // read
    rewind(fp);
    bool ok = (isBinary ? readerObject.readStlBinary(fp) : readerObject.readStlAscii(fp));
    fclose(fp);

    if (!ok) {
        return ReadResult::FILE_NOT_HANDLED;
    }
    osg::notify(osg::NOTICE) << "### found " << readerObject._numFacets << " facets" << std::endl;

    /*
     * setup geometry
     */
    osg::Geometry* geom = new osg::Geometry;
    geom->setVertexArray(readerObject._vertex.get());

    geom->setNormalArray(readerObject._normal.get());
    geom->setNormalBinding(osg::Geometry::BIND_PER_PRIMITIVE);

    if (readerObject._color.valid()) {
        osg::notify(osg::NOTICE) << "### with color" << std::endl;
        geom->setColorArray(readerObject._color.get());
        geom->setColorBinding(osg::Geometry::BIND_PER_PRIMITIVE);
    }

    geom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::TRIANGLES, 0, readerObject._numFacets*3));

    osg::Geode* geode = new osg::Geode;
    geode->addDrawable(geom);

    osgUtil::SmoothingVisitor smooter;
    geode->accept(smooter);

    osgUtil::TriStripVisitor tristripper;
    tristripper.stripify(*geom);

    return geode;
}

/**********************************************************************
 *
 * Private
 *
 **********************************************************************/

bool ReaderWriterSTL::ReaderObject::readStlAscii(FILE* fp)
{
    unsigned int vertexCount = 0;
    unsigned int facetIndex[] = { 0,0,0 };
    unsigned int vertexIndex = 0;
    unsigned int normalIndex = 0;

    char buf[256];
    while (fgets(buf, sizeof(buf), fp)) {

        // strip '\n' or '\r\n' and trailing whitespace
        unsigned int len = strlen(buf)-1;
        while (len && (buf[len] == '\n' || buf[len] == '\r' || isspace(buf[len]))) {
            buf[len--] = '\0';
        }
        if (len == 0 || buf[0] == '\0') {
            continue;
        }

        // strip leading whitespace
        char* bp = buf;
        while (isspace(*bp)) {
            ++bp;
        }

        if (strncmp(bp, "vertex", 6) == 0) {
            float vx,vy,vz;
            if (sscanf(bp+6, "%f %f %f", &vx,&vy,&vz) == 3) {
                if (!_vertex.valid())
                    _vertex = new osg::Vec3Array;

                vertexIndex = _vertex->size();
                if (vertexCount < 3) {
                    _vertex->push_back(osg::Vec3(vx,vy,vz));
                    facetIndex[vertexCount++] = vertexIndex;
                }
                else {
                    /*
                     * There are some invalid ASCII files around (at least one ;-)
                     * that have more than three vertices per facet - add an
                     * additional triangle.
                     */
                    _normal->push_back((*_normal)[normalIndex]);
                    _vertex->push_back((*_vertex)[facetIndex[0]]);
                    _vertex->push_back((*_vertex)[facetIndex[2]]);
                    _vertex->push_back(osg::Vec3(vx,vy,vz));
                    facetIndex[1] = facetIndex[2];
                    facetIndex[2] = vertexIndex;
                    _numFacets++;
                }
            }
        }
        else if (strncmp(bp, "facet", 5) == 0) {
            float nx,ny,nz;
            if (sscanf(bp+5, "%*s %f %f %f", &nx,&ny,&nz) == 3) {

                if (!_normal.valid())
                    _normal = new osg::Vec3Array;

                osg::Vec3 normal(nx,ny,nz);
                normal.normalize();

                normalIndex = _normal->size();
                _normal->push_back(normal);

                _numFacets++;
                vertexCount = 0;
            }
        }
        else if (strncmp(bp, "solid", 5) == 0) {
            osg::notify(osg::NOTICE) << "### parsing '" << bp + 6 << "'" << std::endl;
        }
    }

    return true;
}

bool ReaderWriterSTL::ReaderObject::readStlBinary(FILE* fp)
{
    // seek to beginning of facets
    ::fseek(fp, sizeof_StlHeader, SEEK_SET);

    StlFacet facet;
    for (unsigned int i = 0; i < _numFacets; ++i) {

        if (::fread((void*) &facet, sizeof_StlFacet, 1, fp) != 1) {
            osg::notify(osg::FATAL) << "ReaderWriterSTL::readStlBinary: Failed to read facet " << i << std::endl;
            return false;
        }

        // vertices
        if (!_vertex)
            _vertex = new osg::Vec3Array;
        osg::Vec3 v0(facet.vertex[0].x,facet.vertex[0].y,facet.vertex[0].z);
        osg::Vec3 v1(facet.vertex[1].x,facet.vertex[1].y,facet.vertex[1].z);
        osg::Vec3 v2(facet.vertex[2].x,facet.vertex[2].y,facet.vertex[2].z);
        _vertex->push_back(v0);
        _vertex->push_back(v1);
        _vertex->push_back(v2);

        // per-facet normal
        osg::Vec3 normal;
        if (_generateNormal) {
            osg::Vec3 d01 = v1 - v0;
            osg::Vec3 d02 = v2 - v0;
            normal = d01 ^ d02;
            normal.normalize();
        }
        else {
            normal.set(facet.normal.x,facet.normal.y,facet.normal.z);
        }
        if (!_normal.valid())
            _normal = new osg::Vec3Array;
        _normal->push_back(normal);

        /*
         * color extension
         * RGB555 with most-significat bit indicating if color is present
         */
        if (facet.color & StlHasColor) {
            if (!_color) {
                _color = new osg::Vec4Array;
            }
            float r = ((facet.color >> 10) & StlColorSize) / StlColorDepth;
            float g = ((facet.color >> 5) & StlColorSize) / StlColorDepth;
            float b = (facet.color & StlColorSize) / StlColorDepth;
            _color->push_back(osg::Vec4(r,g,b,1.0f));
        }
    }

    return true;
}
<|endoftext|>


<commit_before><commit_msg>lowhigh component for thresholding values (not triggering on thresholds, like "threshold". Dammit.)<commit_after><|endoftext|>


<commit_before>
void ConfigureEMCALRecoUtils(
                             AliEMCALRecoUtils* reco,
                             Bool_t  bMC   = kFALSE,
                             TGeoHMatrix* matrix[10],
                             TString path  = "",
                             Int_t   run   = 0,
                             TString pass  = "pass2"
                             )
{

  // Configure RecoUtils with OADB objects

  printf("**** Configure AliEMCALRecoUtils, LOAD AODB ***\n");
  printf("\t run %d, pass %s\n",run,pass.Data());

  // Exotic cells removal
  reco->SwitchOnRejectExoticCell() ;
  reco->SetExoticCellDiffTimeCut(10000); // Open
  reco->SetExoticCellFractionCut(0.95);  // 1-Ecross/Ecell > 0.95 -> out
  reco->SetExoticCellMinAmplitudeCut(2); // 2 GeV

  gSystem->Load("libOADB");

  // Instantiate EMCAL geometry for the first time

  AliEMCALGeometry*   geom = 0;
  if   (run < 140000) geom = AliEMCALGeometry::GetInstance("EMCAL_FIRSTYEARV1");
  else                geom = AliEMCALGeometry::GetInstance("EMCAL_COMPLETEV1");

  Int_t nSM = geom->GetNumberOfSuperModules();

  // Geometry settings and field

  TGeoManager::Import("geometry.root") ; //need file "geometry.root" in local dir!!!!

  // Put the automatic initialization like in tender somewhere in the clusterizer or reader!!!
  if(run > 140000 && run < 160000)
    TGeoGlobalMagField::Instance()->SetField(new AliMagF("Maps","Maps", -1., -1., AliMagF::k5kG)); // for (--)
  else if(run > 160000)
    TGeoGlobalMagField::Instance()->SetField(new AliMagF("Maps","Maps",  1.,  1., AliMagF::k5kG)); // for (++)
  else if (run < 140000 && run > 138280)
    TGeoGlobalMagField::Instance()->SetField(new AliMagF("Maps","Maps",  1.,  1., AliMagF::k5kG)); // for (++)
  else if (run < 138280 && run > 122000)
    TGeoGlobalMagField::Instance()->SetField(new AliMagF("Maps","Maps", -1., -1., AliMagF::k5kG)); // for (--)
  else if(run > 119100 && run < 122000)
    TGeoGlobalMagField::Instance()->SetField(new AliMagF("Maps","Maps",  1.,  1., AliMagF::k5kG)); // for (++)
  else if(run < 119100 && run > 11900)
    TGeoGlobalMagField::Instance()->SetField(new AliMagF("Maps","Maps",  0.,  0., AliMagF::k5kG)); // for (0)
  else if(run < 119000 && run > 115800)
    TGeoGlobalMagField::Instance()->SetField(new AliMagF("Maps","Maps",  1.,  1., AliMagF::k5kG)); // for (++)
  else if(run < 115800)
    TGeoGlobalMagField::Instance()->SetField(new AliMagF("Maps","Maps", -1., -1., AliMagF::k5kG)); // for (--)

  // Alignment matrices

  TString fileName="$ALICE_ROOT/OADB/EMCAL/EMCALlocal2master.root";
  if(path!="") fileName=path+"EMCALlocal2master.root";

  AliOADBContainer EMCALgeoCont("AliEMCALgeo");
  EMCALgeoCont.InitFromFile((char*)fileName.Data(),"AliEMCALgeo");
  TObjArray *mobj=(TObjArray*)EMCALgeoCont.GetObject(run,"EmcalMatrices");
  for (Int_t mod=0;mod<nSM;mod++)
    {
      matrix[mod] = (TGeoHMatrix*) mobj->At(mod);
      //matrix[mod]->Print();
    }

  reco->SetPositionAlgorithm(AliEMCALRecoUtils::kPosTowerGlobal);

  //----------------------------------------------

  Bool_t bRecal  = kTRUE;
  Bool_t bBad    = kTRUE;
  if(pass == "pass3"){
    bRecal = kFALSE;
    bBad   = kFALSE;
  }

  if(bMC){
    bRecal = kFALSE;
  }

  //Recalibration factors
  if(bRecal){

    fileName="$ALICE_ROOT/OADB/EMCAL/EMCALRecalib.root";
    if(path!="") fileName=path+"EMCALRecalib.root";

    AliOADBContainer *contRF=new AliOADBContainer("");
    contRF->InitFromFile((char*)fileName.Data(),"AliEMCALRecalib");

    TObjArray *recal=(TObjArray*)contRF->GetObject(run);
    if(recal){
      TObjArray *recalpass=(TObjArray*)recal->FindObject(pass);
      if(recalpass){
        TObjArray *recalib=(TObjArray*)recalpass->FindObject("Recalib");
        if(recalib){
          reco->SwitchOnRecalibration();
          printf("AliEMCALRecoUtils - RECALIBRATE \n");
          for (Int_t i=0; i<nSM; ++i) {
            TH2F *h = reco->GetEMCALChannelRecalibrationFactors(i);
            if (h)
              delete h;
            h = (TH2F*)recalib->FindObject(Form("EMCALRecalFactors_SM%d",i));
            if (!h) {
              AliError(Form("Could not load EMCALRecalFactors_SM%d",i));
              continue;
            }
            h->SetDirectory(0);
            reco->SetEMCALChannelRecalibrationFactors(i,h);
          }
        }else printf("AliEMCALRecoUtils ---Do NOT recalibrate 1\n");
      }else printf("AliEMCALRecoUtils ---Do NOT recalibrate 2\n");
    }else printf("AliEMCALRecoUtils ---Do NOT recalibrate 3\n");

    //TFile * f = new TFile("RecalibrationFactors.root","read");
    //for(Int_t i =0; i< 10; i++)  reco->SetEMCALChannelRecalibrationFactors( i, (TH2F*) f->Get(Form("EMCALRecalFactors_SM%d",i)));
    // //  reco->SwitchOnTimeDepCorrection();
    // //  //char cmd[200] ;
    // //  //sprintf(cmd, ".!tar xvfz CorrectionFiles.tgz") ;
    // //  //gROOT->ProcessLine(cmd) ;
    // //

  } else printf("AliEMCALRecoUtils ---Do NOT recalibrate\n");

  // Remove EMCAL hot channels

  if(bBad){

    fileName="$ALICE_ROOT/OADB/EMCAL/EMCALBadChannels.root";
    if(path!="") fileName=path+"EMCALBadChannels.root";

    AliOADBContainer *contBC=new AliOADBContainer("");
    contBC->InitFromFile((char*)fileName.Data(),"AliEMCALBadChannels");
    TObjArray *arrayBC=(TObjArray*)contBC->GetObject(run);
    if(arrayBC){
      TObjArray *arrayBCpass=(TObjArray*)arrayBC->FindObject(pass);
      if(arrayBCpass){

        reco->SwitchOnBadChannelsRemoval();
        reco->SwitchOnDistToBadChannelRecalculation();
        printf("AliEMCALRecoUtils - REMOVE bad cells \n");

        for (Int_t i=0; i<nSM; ++i) {
          TH2I *hbm = reco->GetEMCALChannelStatusMap(i);
          if (hbm)
            delete hbm;
          hbm=(TH2I*)arrayBCpass->FindObject(Form("EMCALBadChannelMap_Mod%d",i));

          if (!hbm) {
            AliError(Form("Can not get EMCALBadChannelMap_Mod%d",i));
            continue;
          }

          hbm->SetDirectory(0);
          reco->SetEMCALChannelStatusMap(i,hbm);
        }
      } else printf("AliEMCALRecoUtils ---Do NOT remove bad channels 1\n");
    }  else printf("AliEMCALRecoUtils ---Do NOT remove bad channels 2\n");
  } else printf("AliEMCALRecoUtils ---Do NOT remove bad channels 3 \n");

  /*
    Int_t iCol = -1, iRow = -1, iSM =-1, iMod = -1,iIphi =-1,iIeta = -1;
    Int_t badAbsID[]={74, 103};

    for(Int_t i=0;i < sizeof(badAbsID)/sizeof(Int_t); i++){
      geom->GetCellIndex(badAbsID[i],iSM,iMod,iIphi,iIeta);
      // Gives SuperModule and Tower numbers
      geom->GetCellPhiEtaIndexInSModule(iSM,iMod,
					iIphi, iIeta,iRow,iCol);
      //printf("bad ID %d, col %d, row %d, sm %d\n",badAbsID[i],iCol,iRow,iSM);
      reco->SetEMCALChannelStatus(iSM , iCol, iRow,1);
    }

    }
   */

  reco->SwitchOnTimeRecalibration();

  //Waiting for OADB, meanwhile

  TFile * ftime = 0;
  //TString path ="./";
  TString path = "alien:///alice/cern.ch/user/g/germain/RecalDB/Time";
  //TGrid::Connect("alien://");

  if     (run > 140000 && run < 146500 )
    ftime = TFile::Open(Form("%s/RefLHC11apass1-7TeV.root",path.Data()));
  else if(run > 146500 && run <= 146860 )
    ftime = TFile::Open(Form("%s/RefLHC11apass3-2.76TeV.root",path.Data()));
  else if(run > 146860 && run < 156477 )
    ftime = TFile::Open(Form("%s/RefLHC11cpass1-7TeV.root",path.Data()));
  else if(run >= 156477)
    ftime = TFile::Open(Form("%s/RefLHC11cpass1-7TeV.root",path.Data()));
  else if(run <  140000 && run > 136850)
    ftime = TFile::Open(Form("%s/RefLHC10hpass2PbPb2.76TeV.root",path.Data()));
  else if(run < 136850)
    ftime = TFile::Open(Form("%s/RefLHC10dpass2-7TeV.root",path.Data()));
  else printf("Run %d, not considered for time calibration\n",run);

  if(ftime){
    printf("AliEMCALRecoUtils - Time recalibration ON\n");

    for(Int_t i =0; i< 4; i++)  reco->SetEMCALChannelTimeRecalibrationFactors( i, (TH1F*) ftime->Get(Form("hAllTimeAvBC%d",i)));
  }
  else printf("AliEMCALRecoUtils --- Time recalibration OFF\n");

}

<commit_msg>correct correction file name for LHC11d period<commit_after>
void ConfigureEMCALRecoUtils(
                             AliEMCALRecoUtils* reco,
                             Bool_t  bMC   = kFALSE,
                             TGeoHMatrix* matrix[10],
                             TString path  = "",
                             Int_t   run   = 0,
                             TString pass  = "pass2"
                             )
{

  // Configure RecoUtils with OADB objects

  printf("**** Configure AliEMCALRecoUtils, LOAD AODB ***\n");
  printf("\t run %d, pass %s\n",run,pass.Data());

  // Exotic cells removal
  reco->SwitchOnRejectExoticCell() ;
  reco->SetExoticCellDiffTimeCut(10000); // Open
  reco->SetExoticCellFractionCut(0.95);  // 1-Ecross/Ecell > 0.95 -> out
  reco->SetExoticCellMinAmplitudeCut(2); // 2 GeV

  gSystem->Load("libOADB");

  // Instantiate EMCAL geometry for the first time

  AliEMCALGeometry*   geom = 0;
  if   (run < 140000) geom = AliEMCALGeometry::GetInstance("EMCAL_FIRSTYEARV1");
  else                geom = AliEMCALGeometry::GetInstance("EMCAL_COMPLETEV1");

  Int_t nSM = geom->GetNumberOfSuperModules();

  // Geometry settings and field

  TGeoManager::Import("geometry.root") ; //need file "geometry.root" in local dir!!!!

  // Put the automatic initialization like in tender somewhere in the clusterizer or reader!!!
  if(run > 140000 && run < 160000)
    TGeoGlobalMagField::Instance()->SetField(new AliMagF("Maps","Maps", -1., -1., AliMagF::k5kG)); // for (--)
  else if(run > 160000)
    TGeoGlobalMagField::Instance()->SetField(new AliMagF("Maps","Maps",  1.,  1., AliMagF::k5kG)); // for (++)
  else if (run < 140000 && run > 138280)
    TGeoGlobalMagField::Instance()->SetField(new AliMagF("Maps","Maps",  1.,  1., AliMagF::k5kG)); // for (++)
  else if (run < 138280 && run > 122000)
    TGeoGlobalMagField::Instance()->SetField(new AliMagF("Maps","Maps", -1., -1., AliMagF::k5kG)); // for (--)
  else if(run > 119100 && run < 122000)
    TGeoGlobalMagField::Instance()->SetField(new AliMagF("Maps","Maps",  1.,  1., AliMagF::k5kG)); // for (++)
  else if(run < 119100 && run > 11900)
    TGeoGlobalMagField::Instance()->SetField(new AliMagF("Maps","Maps",  0.,  0., AliMagF::k5kG)); // for (0)
  else if(run < 119000 && run > 115800)
    TGeoGlobalMagField::Instance()->SetField(new AliMagF("Maps","Maps",  1.,  1., AliMagF::k5kG)); // for (++)
  else if(run < 115800)
    TGeoGlobalMagField::Instance()->SetField(new AliMagF("Maps","Maps", -1., -1., AliMagF::k5kG)); // for (--)

  // Alignment matrices

  TString fileName="$ALICE_ROOT/OADB/EMCAL/EMCALlocal2master.root";
  if(path!="") fileName=path+"EMCALlocal2master.root";

  AliOADBContainer EMCALgeoCont("AliEMCALgeo");
  EMCALgeoCont.InitFromFile((char*)fileName.Data(),"AliEMCALgeo");
  TObjArray *mobj=(TObjArray*)EMCALgeoCont.GetObject(run,"EmcalMatrices");
  for (Int_t mod=0;mod<nSM;mod++)
    {
      matrix[mod] = (TGeoHMatrix*) mobj->At(mod);
      //matrix[mod]->Print();
    }

  reco->SetPositionAlgorithm(AliEMCALRecoUtils::kPosTowerGlobal);

  //----------------------------------------------

  Bool_t bRecal  = kTRUE;
  Bool_t bBad    = kTRUE;
  if(pass == "pass3"){
    bRecal = kFALSE;
    bBad   = kFALSE;
  }

  if(bMC){
    bRecal = kFALSE;
  }

  //Recalibration factors
  if(bRecal){

    fileName="$ALICE_ROOT/OADB/EMCAL/EMCALRecalib.root";
    if(path!="") fileName=path+"EMCALRecalib.root";

    AliOADBContainer *contRF=new AliOADBContainer("");
    contRF->InitFromFile((char*)fileName.Data(),"AliEMCALRecalib");

    TObjArray *recal=(TObjArray*)contRF->GetObject(run);
    if(recal){
      TObjArray *recalpass=(TObjArray*)recal->FindObject(pass);
      if(recalpass){
        TObjArray *recalib=(TObjArray*)recalpass->FindObject("Recalib");
        if(recalib){
          reco->SwitchOnRecalibration();
          printf("AliEMCALRecoUtils - RECALIBRATE \n");
          for (Int_t i=0; i<nSM; ++i) {
            TH2F *h = reco->GetEMCALChannelRecalibrationFactors(i);
            if (h)
              delete h;
            h = (TH2F*)recalib->FindObject(Form("EMCALRecalFactors_SM%d",i));
            if (!h) {
              AliError(Form("Could not load EMCALRecalFactors_SM%d",i));
              continue;
            }
            h->SetDirectory(0);
            reco->SetEMCALChannelRecalibrationFactors(i,h);
          }
        }else printf("AliEMCALRecoUtils ---Do NOT recalibrate 1\n");
      }else printf("AliEMCALRecoUtils ---Do NOT recalibrate 2\n");
    }else printf("AliEMCALRecoUtils ---Do NOT recalibrate 3\n");

    //TFile * f = new TFile("RecalibrationFactors.root","read");
    //for(Int_t i =0; i< 10; i++)  reco->SetEMCALChannelRecalibrationFactors( i, (TH2F*) f->Get(Form("EMCALRecalFactors_SM%d",i)));
    // //  reco->SwitchOnTimeDepCorrection();
    // //  //char cmd[200] ;
    // //  //sprintf(cmd, ".!tar xvfz CorrectionFiles.tgz") ;
    // //  //gROOT->ProcessLine(cmd) ;
    // //

  } else printf("AliEMCALRecoUtils ---Do NOT recalibrate\n");

  // Remove EMCAL hot channels

  if(bBad){

    fileName="$ALICE_ROOT/OADB/EMCAL/EMCALBadChannels.root";
    if(path!="") fileName=path+"EMCALBadChannels.root";

    AliOADBContainer *contBC=new AliOADBContainer("");
    contBC->InitFromFile((char*)fileName.Data(),"AliEMCALBadChannels");
    TObjArray *arrayBC=(TObjArray*)contBC->GetObject(run);
    if(arrayBC){
      TObjArray *arrayBCpass=(TObjArray*)arrayBC->FindObject(pass);
      if(arrayBCpass){

        reco->SwitchOnBadChannelsRemoval();
        reco->SwitchOnDistToBadChannelRecalculation();
        printf("AliEMCALRecoUtils - REMOVE bad cells \n");

        for (Int_t i=0; i<nSM; ++i) {
          TH2I *hbm = reco->GetEMCALChannelStatusMap(i);
          if (hbm)
            delete hbm;
          hbm=(TH2I*)arrayBCpass->FindObject(Form("EMCALBadChannelMap_Mod%d",i));

          if (!hbm) {
            AliError(Form("Can not get EMCALBadChannelMap_Mod%d",i));
            continue;
          }

          hbm->SetDirectory(0);
          reco->SetEMCALChannelStatusMap(i,hbm);
        }
      } else printf("AliEMCALRecoUtils ---Do NOT remove bad channels 1\n");
    }  else printf("AliEMCALRecoUtils ---Do NOT remove bad channels 2\n");
  } else printf("AliEMCALRecoUtils ---Do NOT remove bad channels 3 \n");

  /*
    Int_t iCol = -1, iRow = -1, iSM =-1, iMod = -1,iIphi =-1,iIeta = -1;
    Int_t badAbsID[]={74, 103};

    for(Int_t i=0;i < sizeof(badAbsID)/sizeof(Int_t); i++){
      geom->GetCellIndex(badAbsID[i],iSM,iMod,iIphi,iIeta);
      // Gives SuperModule and Tower numbers
      geom->GetCellPhiEtaIndexInSModule(iSM,iMod,
					iIphi, iIeta,iRow,iCol);
      //printf("bad ID %d, col %d, row %d, sm %d\n",badAbsID[i],iCol,iRow,iSM);
      reco->SetEMCALChannelStatus(iSM , iCol, iRow,1);
    }

    }
   */

  reco->SwitchOnTimeRecalibration();

  //Waiting for OADB, meanwhile

  TFile * ftime = 0;
  //TString path ="./";
  TString path = "alien:///alice/cern.ch/user/g/germain/RecalDB/Time";
  //TGrid::Connect("alien://");

  if     (run > 140000 && run < 146500 )
    ftime = TFile::Open(Form("%s/RefLHC11apass1-7TeV.root",path.Data()));
  else if(run > 146500 && run <= 146860 )
    ftime = TFile::Open(Form("%s/RefLHC11apass3-2.76TeV.root",path.Data()));
  else if(run > 146860 && run < 156477 )
    ftime = TFile::Open(Form("%s/RefLHC11cpass1-7TeV.root",path.Data()));
  else if(run >= 156477)
    ftime = TFile::Open(Form("%s/RefLHC11dpass1-7TeV.root",path.Data()));
  else if(run <  140000 && run > 136850)
    ftime = TFile::Open(Form("%s/RefLHC10hpass2PbPb2.76TeV.root",path.Data()));
  else if(run < 136850)
    ftime = TFile::Open(Form("%s/RefLHC10dpass2-7TeV.root",path.Data()));
  else printf("Run %d, not considered for time calibration\n",run);

  if(ftime){
    printf("AliEMCALRecoUtils - Time recalibration ON\n");

    for(Int_t i =0; i< 4; i++)  reco->SetEMCALChannelTimeRecalibrationFactors( i, (TH1F*) ftime->Get(Form("hAllTimeAvBC%d",i)));
  }
  else printf("AliEMCALRecoUtils --- Time recalibration OFF\n");

}

<|endoftext|>


<commit_before>#include "application.h"

// This #include statement was automatically added by the Spark IDE.
#include "flipflop.h"

// This #include statement was automatically added by the Spark IDE.
#include "hmc5883l.h"

/*
    HMC5883l Watermeter Reader
    Author: Keith Baker
    Email: kbaker at alumni dot ithaca dot edu

    Very loosely based off of: MAG3110 Breakout Example Code
                           by: Aaron Weiss, aaron at sparkfun dot com

    Track magnetic impeller of a water meter using a digital compass.

*/

hmc5883l hmc = hmc5883l();
flipflop counter = flipflop();
unsigned long last = millis();
unsigned long now = millis();
byte mps = 0;
unsigned long last_count = 0;
float avg = 0;
bool blink = false;

#define LED        D7

void setup()
{
  Serial.begin(115200);  // start serial for output
  Serial.println("Cloud!");

  //let us know we are connected to cloud so we can re-flash bad code
  pinMode(LED, OUTPUT);
  digitalWrite(LED,HIGH);
  unsigned long time = millis();
  while (millis() < time + 10000 or SPARK_FLASH_UPDATE){
     SPARK_WLAN_Loop();
  }
  digitalWrite(LED,LOW);

  //to late, hold on tight!
  Serial.println("Starting...");
  Wire.begin(true);        // join i2c bus at high speed
  hmc.config();        // turn the HMC5883l on
  Serial.println("Configured");
  RGB.control(true);
}

void loop()
{
  now = millis();
  if (hmc.ready(now)){
    digitalWrite(LED,HIGH);
    if (hmc.fastread()){
      Serial.println("I2C Read Error");
    }
    digitalWrite(LED,LOW);
  }
  else if (hmc.available()){
    counter.append(hmc.getz());
    //counter.debug();
    hmc.advance();
    mps ++;
  }
  if (now - last > 1000){
    last = now;
    int delta = counter.count - last_count;
    last_count = counter.count;
    avg = ((avg * 59.0) + delta) / 60.0;
    Serial.print(delta);
    Serial.print(" ");
    Serial.print(avg);
    Serial.print(" ");
    Serial.println(mps);
    if (blink){
      blink = false;
    }
    else {
      blink = true;
    }
    RGB.color(delta * 10, (int)(avg * 10.0), (int)blink * 255);
    mps = 0;
  }

}
<commit_msg>screw the cloud...  it takes too much time from my code<commit_after>#include "application.h"

// This #include statement was automatically added by the Spark IDE.
#include "flipflop.h"

// This #include statement was automatically added by the Spark IDE.
#include "hmc5883l.h"

/*
    HMC5883l Watermeter Reader
    Author: Keith Baker
    Email: kbaker at alumni dot ithaca dot edu

    Very loosely based off of: MAG3110 Breakout Example Code
                           by: Aaron Weiss, aaron at sparkfun dot com

    Track magnetic impeller of a water meter using a digital compass.

*/

hmc5883l hmc = hmc5883l();
flipflop counter = flipflop();
unsigned long last = millis();
unsigned long now = millis();
byte mps = 0;
unsigned long last_count = 0;
float avg = 0;
bool blink = false;

#define LED        D7

void setup()
{
  Serial.begin(115200);  // start serial for output
  Serial.println("Cloud!");

  //let us know we are connected to cloud so we can re-flash bad code
  pinMode(LED, OUTPUT);
  digitalWrite(LED,HIGH);
  unsigned long time = millis();
  while (millis() < time + 10000 or SPARK_FLASH_UPDATE){
     SPARK_WLAN_Loop();
  }
  digitalWrite(LED,LOW);

  Spark.disconnect(); // We don't need any cloud after we allow re-flash, takes a ton of cycles
  //to late, hold on tight!
  Serial.println("Starting...");
  Wire.begin(true);        // join i2c bus at high speed
  hmc.config();        // turn the HMC5883l on
  Serial.println("Configured");
  RGB.control(true);
}

void loop()
{
  now = millis();
  if (hmc.ready(now)){
    digitalWrite(LED,HIGH);
    if (hmc.fastread()){
      Serial.println("I2C Read Error");
    }
    digitalWrite(LED,LOW);
  }
  else if (hmc.available()){
    counter.append(hmc.getz());
    //counter.debug();
    hmc.advance();
    mps ++;
  }
  if (now - last > 1000){
    last = now;
    int delta = counter.count - last_count;
    last_count = counter.count;
    avg = ((avg * 59.0) + delta) / 60.0;
    Serial.print(delta);
    Serial.print(" ");
    Serial.print(avg);
    Serial.print(" ");
    Serial.println(mps);
    if (blink){
      blink = false;
    }
    else {
      blink = true;
    }
    RGB.color(delta * 10, (int)(avg * 10.0), (int)blink * 255);
    mps = 0;
  }

}
<|endoftext|>


<commit_before>//______________________________________________________________________________
// creates an AliAnalysisTaskCEP and the output containers
//
AliAnalysisTaskSE* AddTaskCEPAnalysis (
  TString taskname        = TString("CEPAnalysis"),
  UInt_t  taskconfig      = AliCEPBase::kBitConfigurationSet,
  Int_t rnummin,
  Int_t rnummax,
  Int_t   numTracksMax    = 6,
  Double_t fracDG         = 1.0,
  Double_t fracNDG        = 0.0,
  UInt_t  ETmaskDG        = AliCEPBase::kBitBaseLine,
  UInt_t  ETpatternDG     = AliCEPBase::kBitBaseLine,
  UInt_t  ETmaskNDG       = AliCEPBase::kBitBaseLine,
  UInt_t  ETpatternNDG    = AliCEPBase::kBitBaseLine,
  UInt_t  TTmask          = AliCEPBase::kTTBaseLine,
  UInt_t  TTpattern       = AliCEPBase::kTTBaseLine
  )
{

	// get the manager and task
	AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();

  // check for MonteCarlo
  Bool_t isMC = (taskconfig&AliCEPBase::kBitisMC)==AliCEPBase::kBitisMC;
  if (isMC) {
    AliMCEventHandler* MChandler = new AliMCEventHandler;
    MChandler->SetReadTR(kFALSE);
    mgr->SetMCtruthEventHandler(MChandler);
  }

  // create the analysis task
	AliAnalysisTaskCEP *task = new AliAnalysisTaskCEP (
    taskname.Data(),taskconfig,
    rnummin,rnummax,
    numTracksMax,
    fracDG,fracNDG,
    ETmaskDG,ETpatternDG,ETmaskNDG,ETpatternNDG,TTmask,TTpattern
  );

	// get input and output managers
	AliAnalysisDataContainer *aadci  = mgr->GetCommonInputContainer();
	AliAnalysisDataContainer *aadco1 = mgr->CreateContainer
	(
		Form("CEPHist"),
		TList::Class(),
		AliAnalysisManager::kOutputContainer,
		Form("%s", AliAnalysisManager::GetCommonFileName())
	);

	AliAnalysisDataContainer *aadco2 = mgr->CreateContainer
	(
		Form("CEPTree"),
		TTree::Class(),
		AliAnalysisManager::kOutputContainer,
		Form("%s", AliAnalysisManager::GetCommonFileName())
	);

	// add task and connect input and output managers
	mgr->AddTask(task);
	mgr->ConnectInput (task,0,aadci);
	mgr->ConnectOutput(task,1,aadco1);
	mgr->ConnectOutput(task,2,aadco2);

	// return pointer to Task
	return task;

}

//______________________________________________________________________________

<commit_msg>In AddTaskCEPAnalysis.C changed AliCEPBase::kBit* AliCEPBase::kET*<commit_after>//______________________________________________________________________________
// creates an AliAnalysisTaskCEP and the output containers
//
AliAnalysisTaskSE* AddTaskCEPAnalysis (
  TString taskname        = TString("CEPAnalysis"),
  UInt_t  taskconfig      = AliCEPBase::kBitConfigurationSet,
  Int_t rnummin,
  Int_t rnummax,
  Int_t   numTracksMax    = 6,
  Double_t fracDG         = 1.0,
  Double_t fracNDG        = 0.0,
  UInt_t  ETmaskDG        = AliCEPBase::kETBaseLine,
  UInt_t  ETpatternDG     = AliCEPBase::kETBaseLine,
  UInt_t  ETmaskNDG       = AliCEPBase::kETBaseLine,
  UInt_t  ETpatternNDG    = AliCEPBase::kETBaseLine,
  UInt_t  TTmask          = AliCEPBase::kTTBaseLine,
  UInt_t  TTpattern       = AliCEPBase::kTTBaseLine
  )
{

	// get the manager and task
	AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();

  // check for MonteCarlo
  Bool_t isMC = (taskconfig&AliCEPBase::kBitisMC)==AliCEPBase::kBitisMC;
  if (isMC) {
    AliMCEventHandler* MChandler = new AliMCEventHandler;
    MChandler->SetReadTR(kFALSE);
    mgr->SetMCtruthEventHandler(MChandler);
  }

  // create the analysis task
	AliAnalysisTaskCEP *task = new AliAnalysisTaskCEP (
    taskname.Data(),taskconfig,
    rnummin,rnummax,
    numTracksMax,
    fracDG,fracNDG,
    ETmaskDG,ETpatternDG,ETmaskNDG,ETpatternNDG,TTmask,TTpattern
  );

	// get input and output managers
	AliAnalysisDataContainer *aadci  = mgr->GetCommonInputContainer();
	AliAnalysisDataContainer *aadco1 = mgr->CreateContainer
	(
		Form("CEPHist"),
		TList::Class(),
		AliAnalysisManager::kOutputContainer,
		Form("%s", AliAnalysisManager::GetCommonFileName())
	);

	AliAnalysisDataContainer *aadco2 = mgr->CreateContainer
	(
		Form("CEPTree"),
		TTree::Class(),
		AliAnalysisManager::kOutputContainer,
		Form("%s", AliAnalysisManager::GetCommonFileName())
	);

	// add task and connect input and output managers
	mgr->AddTask(task);
	mgr->ConnectInput (task,0,aadci);
	mgr->ConnectOutput(task,1,aadco1);
	mgr->ConnectOutput(task,2,aadco2);

	// return pointer to Task
	return task;

}

//______________________________________________________________________________

<|endoftext|>


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

#include <iostream>

#include <boost/scoped_ptr.hpp>

#include <pdal/Stage.hpp>
#include <pdal/StageIterator.hpp>
#include <pdal/FileUtils.hpp>
#include <pdal/PointBuffer.hpp>
#include <pdal/filters/Stats.hpp>

#ifdef PDAL_HAVE_LIBXML2
#include <pdal/XMLSchema.hpp>
#endif

#include <boost/property_tree/xml_parser.hpp>
#include <boost/property_tree/json_parser.hpp>

#include "AppSupport.hpp"
#include "Application.hpp"

using namespace pdal;

class PcInfo : public Application
{
public:
    PcInfo(int argc, char* argv[]);
    int execute(); // overrride

private:
    void addSwitches(); // overrride
    void validateSwitches(); // overrride

    void dumpOnePoint(const Stage&) const;
    void dumpStats(pdal::filters::Stats& filter) const;
    void dumpSchema(const Stage&) const;
    void dumpStage(const Stage&) const;
    void dumpMetadata(const Stage&) const;
    void dumpSDO_PCMetadata(Stage const&) const;

    std::string m_inputFile;
    bool m_showStats;
    bool m_showSchema;
    bool m_showStage;
    bool m_showMetadata;
    bool m_showSDOPCMetadata;
    pdal::Options m_options;
    boost::uint64_t m_pointNumber;
    std::ostream* m_outputStream;
    boost::uint32_t m_seed;
    boost::uint32_t m_sample_size;
    bool m_useXML;
    std::string m_Dimensions;
};

PcInfo::PcInfo(int argc, char* argv[])
    : Application(argc, argv, "pcinfo")
    , m_inputFile("")
    , m_showStats(false)
    , m_showSchema(false)
    , m_showStage(false)
    , m_showMetadata(false)
    , m_showSDOPCMetadata(false)
    , m_pointNumber((std::numeric_limits<boost::uint64_t>::max)())
    , m_outputStream(0)
    , m_useXML(false)
{
    return;
}

void PcInfo::validateSwitches()
{

    const bool got_something =
        (m_pointNumber != (std::numeric_limits<boost::uint64_t>::max)()) ||
        m_showStats ||
        m_showSchema ||
        m_showMetadata ||
        m_showSDOPCMetadata ||
        m_showStage;
    if (!got_something)
    {
        throw app_usage_error("no action option specified");
    }

    return;
}

void PcInfo::addSwitches()
{
    namespace po = boost::program_options;

    po::options_description* file_options = new po::options_description("file options");

    file_options->add_options()
        ("input,i", po::value<std::string>(&m_inputFile)->default_value(""), "input file name")
        ;

    addSwitchSet(file_options);

    po::options_description* processing_options = new po::options_description("processing options");

    processing_options->add_options()
        ("point,p", po::value<boost::uint64_t>(&m_pointNumber)->implicit_value(0), "point to dump")
        ("stats,a", po::value<bool>(&m_showStats)->zero_tokens()->implicit_value(true), "dump stats on all points (reads entire dataset)")
        ("dimensions", po::value<std::string >(&m_Dimensions), "dump stats on all points (reads entire dataset)")
        ("schema,s", po::value<bool>(&m_showSchema)->zero_tokens()->implicit_value(true), "dump the schema")
        ("metadata,m", po::value<bool>(&m_showMetadata)->zero_tokens()->implicit_value(true), "dump the metadata")
        ("sdo_pc", po::value<bool>(&m_showSDOPCMetadata)->zero_tokens()->implicit_value(true), "dump the SDO_PC Oracle Metadata")
        ("stage,r", po::value<bool>(&m_showStage)->zero_tokens()->implicit_value(true), "dump the stage info")
        ("xml", po::value<bool>(&m_useXML)->zero_tokens()->implicit_value(true), "dump XML instead of JSON")
        ("seed", po::value<boost::uint32_t>(&m_seed)->default_value(0), "Seed value for random sample")
        ("sample_size", po::value<boost::uint32_t>(&m_sample_size)->default_value(1000), "Sample size for random sample")
        ;

    addSwitchSet(processing_options);

    addPositionalSwitch("input", 1);

    return;
}

void PcInfo::dumpOnePoint(const Stage& stage) const
{
    const Schema& schema = stage.getSchema();

    PointBuffer data(schema, 1);

    boost::scoped_ptr<StageSequentialIterator> iter(stage.createSequentialIterator(data));
    iter->skip(m_pointNumber);

    const boost::uint32_t numRead = iter->read(data);
    if (numRead != 1)
    {
        std::ostringstream oss;
        oss << "problem reading point number " << m_pointNumber;
        throw app_runtime_error(oss.str());
    }

    boost::property_tree::ptree tree = data.toPTree();

    std::ostream& ostr = m_outputStream ? *m_outputStream : std::cout;

    boost::property_tree::ptree output;
    output.add_child("point", tree.get_child("0"));
    if (m_useXML)
        write_xml(ostr, output);
    else
        write_json(ostr, tree.get_child("0"));

    return;
}

void PcInfo::dumpStats(pdal::filters::Stats& filter) const
{

    const Schema& schema = filter.getSchema();

    boost::uint32_t chunkSize(131072);
    if (filter.getNumPoints() > 0 )
    {
        chunkSize = filter.getNumPoints();
    }

    PointBuffer data(schema, chunkSize);

    boost::scoped_ptr<StageSequentialIterator> iter(filter.createSequentialIterator(data));

    boost::uint64_t totRead = 0;
    while (!iter->atEnd())
    {

        const boost::uint32_t numRead = iter->read(data);
        totRead += numRead;
    }

    pdal::Metadata output = static_cast<pdal::filters::iterators::sequential::Stats*>(iter.get())->toMetadata();

    boost::property_tree::ptree tree;
    tree.add_child("stats", output.toPTree());
    std::ostream& ostr = m_outputStream ? *m_outputStream : std::cout;

    if (m_useXML)
        write_xml(ostr, tree);
    else
        write_json(ostr, tree);

    return;
}

void PcInfo::dumpSchema(const Stage& stage) const
{
    const Schema& schema = stage.getSchema();

    boost::property_tree::ptree schema_tree = schema.toPTree();

    std::ostream& ostr = m_outputStream ? *m_outputStream : std::cout;

    boost::property_tree::ptree tree;
    tree.add_child("schema", schema_tree);

    if (m_useXML)
        write_xml(ostr, tree);
    else
        write_json(ostr, tree);

    return;
}

void PcInfo::dumpSDO_PCMetadata(const Stage& stage) const
{
    boost::property_tree::ptree metadata = stage.serializePipeline();

    const Schema& schema = stage.getSchema();

    std::string xml = pdal::Schema::to_xml(schema, &metadata);

    std::ostream& ostr = m_outputStream ? *m_outputStream : std::cout;

    ostr << xml;

}

void PcInfo::dumpStage(const Stage& stage) const
{
    boost::property_tree::ptree tree = stage.toPTree();

    std::ostream& ostr = m_outputStream ? *m_outputStream : std::cout;

    boost::property_tree::ptree output;
    output.add_child("stage", tree);
    if (m_useXML)
        write_xml(ostr, output);
    else
        write_json(ostr, tree);

    return;
}

void PcInfo::dumpMetadata(const Stage& stage) const
{
    boost::property_tree::ptree tree = stage.serializePipeline();
    std::ostream& ostr = m_outputStream ? *m_outputStream : std::cout;

    if (m_useXML)
        write_xml(ostr, tree);
    else
        write_json(ostr, tree);

    return;
}

int PcInfo::execute()
{

    Options readerOptions;
    {
        if (m_usestdin)
            m_inputFile = "STDIN";
        readerOptions.add<std::string>("filename", m_inputFile);
        readerOptions.add<bool>("debug", isDebug());
        readerOptions.add<boost::uint32_t>("verbose", getVerboseLevel());
    }

    Stage* reader = AppSupport::makeReader(readerOptions);

    if (m_seed != 0)
    {
        Option seed_option("seed", m_seed, "seed value");
        m_options.add(seed_option);
    }

    Option sample_size("sample_size", m_sample_size, "sample size for random sample");
    m_options.add(sample_size);

    Option cls("exact_count", "Classification", "use exact counts for classification stats");
    Option rn("exact_count", "ReturnNumber", "use exact counts for ReturnNumber stats");
    Option nr("exact_count", "NumberOfReturns", "use exact counts for ReturnNumber stats");
    m_options.add(cls);
    m_options.add(rn);
    m_options.add(nr);
    if (m_Dimensions.size())
    {
        Option dimensions("dimensions", m_Dimensions, "Use explicit list of dimensions");
        m_options.add(dimensions);
    }

    pdal::Options options = m_options + readerOptions;

    pdal::filters::Stats* filter = new pdal::filters::Stats(*reader, options);

    filter->initialize();

    if (m_pointNumber != (std::numeric_limits<boost::uint64_t>::max)())
    {
        dumpOnePoint(*filter);
    }

    if (m_showStats)
    {
        dumpStats(*filter);
    }

    if (m_showSchema)
    {
        dumpSchema(*reader);
    }

    if (m_showMetadata)
    {
        dumpMetadata(*reader);
    }
    if (m_showStage)
    {
        dumpStage(*reader);
    }

    if (m_showSDOPCMetadata)
    {
        dumpSDO_PCMetadata(*reader);
    }

    std::ostream& ostr = m_outputStream ? *m_outputStream : std::cout;
    ostr << std::endl;

    delete filter;
    delete reader;

    if (m_outputStream)
    {
        FileUtils::closeFile(m_outputStream);
    }

    return 0;
}

int main(int argc, char* argv[])
{
    PcInfo app(argc, argv);
    return app.run();
}

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

#include <iostream>

#include <boost/scoped_ptr.hpp>

#include <pdal/Stage.hpp>
#include <pdal/StageIterator.hpp>
#include <pdal/FileUtils.hpp>
#include <pdal/PointBuffer.hpp>
#include <pdal/filters/Stats.hpp>

#ifdef PDAL_HAVE_LIBXML2
#include <pdal/XMLSchema.hpp>
#endif

#include <boost/property_tree/xml_parser.hpp>
#include <boost/property_tree/json_parser.hpp>

#include "AppSupport.hpp"
#include "Application.hpp"

using namespace pdal;

class PcInfo : public Application
{
public:
    PcInfo(int argc, char* argv[]);
    int execute(); // overrride

private:
    void addSwitches(); // overrride
    void validateSwitches(); // overrride

    void dumpOnePoint(const Stage&) const;
    void dumpStats(pdal::filters::Stats& filter) const;
    void dumpSchema(const Stage&) const;
    void dumpStage(const Stage&) const;
    void dumpMetadata(const Stage&) const;
    void dumpSDO_PCMetadata(Stage const&) const;

    std::string m_inputFile;
    bool m_showStats;
    bool m_showSchema;
    bool m_showStage;
    bool m_showMetadata;
    bool m_showSDOPCMetadata;
    pdal::Options m_options;
    boost::uint64_t m_pointNumber;
    std::ostream* m_outputStream;
    boost::uint32_t m_seed;
    boost::uint32_t m_sample_size;
    bool m_useXML;
    std::string m_Dimensions;
};

PcInfo::PcInfo(int argc, char* argv[])
    : Application(argc, argv, "pcinfo")
    , m_inputFile("")
    , m_showStats(false)
    , m_showSchema(false)
    , m_showStage(false)
    , m_showMetadata(false)
    , m_showSDOPCMetadata(false)
    , m_pointNumber((std::numeric_limits<boost::uint64_t>::max)())
    , m_outputStream(0)
    , m_useXML(false)
{
    return;
}

void PcInfo::validateSwitches()
{

    const bool got_something =
        (m_pointNumber != (std::numeric_limits<boost::uint64_t>::max)()) ||
        m_showStats ||
        m_showSchema ||
        m_showMetadata ||
        m_showSDOPCMetadata ||
        m_showStage;
    if (!got_something)
    {
        throw app_usage_error("no action option specified");
    }

    return;
}

void PcInfo::addSwitches()
{
    namespace po = boost::program_options;

    po::options_description* file_options = new po::options_description("file options");

    file_options->add_options()
        ("input,i", po::value<std::string>(&m_inputFile)->default_value(""), "input file name")
        ;

    addSwitchSet(file_options);

    po::options_description* processing_options = new po::options_description("processing options");

    processing_options->add_options()
        ("point,p", po::value<boost::uint64_t>(&m_pointNumber)->implicit_value(0), "point to dump")
        ("stats,a", po::value<bool>(&m_showStats)->zero_tokens()->implicit_value(true), "dump stats on all points (reads entire dataset)")
        ("dimensions", po::value<std::string >(&m_Dimensions), "dump stats on all points (reads entire dataset)")
        ("schema,s", po::value<bool>(&m_showSchema)->zero_tokens()->implicit_value(true), "dump the schema")
        ("metadata,m", po::value<bool>(&m_showMetadata)->zero_tokens()->implicit_value(true), "dump the metadata")
        ("sdo_pc", po::value<bool>(&m_showSDOPCMetadata)->zero_tokens()->implicit_value(true), "dump the SDO_PC Oracle Metadata")
        ("stage,r", po::value<bool>(&m_showStage)->zero_tokens()->implicit_value(true), "dump the stage info")
        ("xml", po::value<bool>(&m_useXML)->zero_tokens()->implicit_value(true), "dump XML instead of JSON")
        ("seed", po::value<boost::uint32_t>(&m_seed)->default_value(0), "Seed value for random sample")
        ("sample_size", po::value<boost::uint32_t>(&m_sample_size)->default_value(1000), "Sample size for random sample")
        ;

    addSwitchSet(processing_options);

    addPositionalSwitch("input", 1);

    return;
}

void PcInfo::dumpOnePoint(const Stage& stage) const
{
    const Schema& schema = stage.getSchema();

    PointBuffer data(schema, 1);

    boost::scoped_ptr<StageSequentialIterator> iter(stage.createSequentialIterator(data));
    iter->skip(m_pointNumber);

    const boost::uint32_t numRead = iter->read(data);
    if (numRead != 1)
    {
        std::ostringstream oss;
        oss << "problem reading point number " << m_pointNumber;
        throw app_runtime_error(oss.str());
    }

    boost::property_tree::ptree tree = data.toPTree();

    std::ostream& ostr = m_outputStream ? *m_outputStream : std::cout;

    boost::property_tree::ptree output;
    output.add_child("point", tree.get_child("0"));
    if (m_useXML)
        write_xml(ostr, output);
    else
        write_json(ostr, tree.get_child("0"));

    return;
}

void PcInfo::dumpStats(pdal::filters::Stats& filter) const
{

    const Schema& schema = filter.getSchema();

    boost::uint32_t chunkSize(131072);
    if (filter.getNumPoints() > 0 )
    {
        chunkSize = filter.getNumPoints();
    }

    PointBuffer data(schema, chunkSize);

    boost::scoped_ptr<StageSequentialIterator> iter(filter.createSequentialIterator(data));

    boost::uint64_t totRead = 0;
    while (!iter->atEnd())
    {

        const boost::uint32_t numRead = iter->read(data);
        totRead += numRead;
    }

    pdal::Metadata output = static_cast<pdal::filters::iterators::sequential::Stats*>(iter.get())->toMetadata();

    boost::property_tree::ptree tree;
    tree.add_child("stats", output.toPTree());
    std::ostream& ostr = m_outputStream ? *m_outputStream : std::cout;

    if (m_useXML)
        write_xml(ostr, tree);
    else
        write_json(ostr, tree);

    return;
}

void PcInfo::dumpSchema(const Stage& stage) const
{
    const Schema& schema = stage.getSchema();

    boost::property_tree::ptree schema_tree = schema.toPTree();

    std::ostream& ostr = m_outputStream ? *m_outputStream : std::cout;

    boost::property_tree::ptree tree;
    tree.add_child("schema", schema_tree);

    if (m_useXML)
        write_xml(ostr, tree);
    else
        write_json(ostr, tree);

    return;
}

void PcInfo::dumpSDO_PCMetadata(const Stage& stage) const
{
    boost::property_tree::ptree metadata = stage.serializePipeline();

    const Schema& schema = stage.getSchema();

    std::string xml = pdal::Schema::to_xml(schema, &metadata);

    std::ostream& ostr = m_outputStream ? *m_outputStream : std::cout;

    ostr << xml;

}

void PcInfo::dumpStage(const Stage& stage) const
{
    boost::property_tree::ptree tree = stage.toPTree();

    std::ostream& ostr = m_outputStream ? *m_outputStream : std::cout;

    boost::property_tree::ptree output;
    output.add_child("stage", tree);
    if (m_useXML)
        write_xml(ostr, output);
    else
        write_json(ostr, tree);

    return;
}

void PcInfo::dumpMetadata(const Stage& stage) const
{
    boost::property_tree::ptree tree = stage.serializePipeline();
    std::ostream& ostr = m_outputStream ? *m_outputStream : std::cout;

    if (m_useXML)
        write_xml(ostr, tree);
    else
        write_json(ostr, tree);

    return;
}

int PcInfo::execute()
{

    Options readerOptions;
    {
        if (m_usestdin)
            m_inputFile = "STDIN";
        readerOptions.add<std::string>("filename", m_inputFile);
        readerOptions.add<bool>("debug", isDebug());
        readerOptions.add<boost::uint32_t>("verbose", getVerboseLevel());
    }

    Stage* reader = AppSupport::makeReader(readerOptions);

    if (m_seed != 0)
    {
        Option seed_option("seed", m_seed, "seed value");
        m_options.add(seed_option);
    }

    Option sample_size("sample_size", m_sample_size, "sample size for random sample");
    m_options.add(sample_size);

    Option cls("exact_count", "Classification", "use exact counts for classification stats");
    Option rn("exact_count", "ReturnNumber", "use exact counts for ReturnNumber stats");
    Option nr("exact_count", "NumberOfReturns", "use exact counts for ReturnNumber stats");
    m_options.add(cls);
    m_options.add(rn);
    m_options.add(nr);
    if (m_Dimensions.size())
    {
        Option dimensions("dimensions", m_Dimensions, "Use explicit list of dimensions");
        m_options.add(dimensions);
        Option do_sample("do_sample", false, "Dont do sampling");
        m_options.add(do_sample);
    }

    pdal::Options options = m_options + readerOptions;

    pdal::filters::Stats* filter = new pdal::filters::Stats(*reader, options);

    filter->initialize();

    if (m_pointNumber != (std::numeric_limits<boost::uint64_t>::max)())
    {
        dumpOnePoint(*filter);
    }

    if (m_showStats)
    {
        dumpStats(*filter);
    }

    if (m_showSchema)
    {
        dumpSchema(*reader);
    }

    if (m_showMetadata)
    {
        dumpMetadata(*reader);
    }
    if (m_showStage)
    {
        dumpStage(*reader);
    }

    if (m_showSDOPCMetadata)
    {
        dumpSDO_PCMetadata(*reader);
    }

    std::ostream& ostr = m_outputStream ? *m_outputStream : std::cout;
    ostr << std::endl;

    delete filter;
    delete reader;

    if (m_outputStream)
    {
        FileUtils::closeFile(m_outputStream);
    }

    return 0;
}

int main(int argc, char* argv[])
{
    PcInfo app(argc, argv);
    return app.run();
}

<|endoftext|>


<commit_before>#include "AppDelegate.h"
#include "HelloWorldScene.h"

USING_NS_CC;

static cocos2d::Size designResolutionSize = cocos2d::Size(480, 320);
static cocos2d::Size smallResolutionSize = cocos2d::Size(480, 320);
static cocos2d::Size mediumResolutionSize = cocos2d::Size(1024, 768);
static cocos2d::Size largeResolutionSize = cocos2d::Size(2048, 1536);

AppDelegate::AppDelegate() {

}

AppDelegate::~AppDelegate()
{
}

//if you want a different context,just modify the value of glContextAttrs
//it will takes effect on all platforms
void AppDelegate::initGLContextAttrs()
{
    //set OpenGL context attributions,now can only set six attributions:
    //red,green,blue,alpha,depth,stencil
    GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8};

    GLView::setGLContextAttrs(glContextAttrs);
}

// If you want to use packages manager to install more packages,
// don't modify or remove this function
static int register_all_packages()
{
    return 0; //flag for packages manager
}

bool AppDelegate::applicationDidFinishLaunching() {
    // initialize director
    auto director = Director::getInstance();
    auto glview = director->getOpenGLView();
    if(!glview) {
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) || (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX)
        glview = GLViewImpl::createWithRect("testProject", Rect(0, 0, designResolutionSize.width, designResolutionSize.height));
#else
        glview = GLViewImpl::create("testProject");
#endif
        director->setOpenGLView(glview);
    }

    // turn on display FPS
    director->setDisplayStats(true);

    // set FPS. the default value is 1.0/60 if you don't call this
    director->setAnimationInterval(1.0 / 60);

    // Set the design resolution
    glview->setDesignResolutionSize(designResolutionSize.width, designResolutionSize.height, ResolutionPolicy::NO_BORDER);
    Size frameSize = glview->getFrameSize();
    // if the frame's height is larger than the height of medium size.
    if (frameSize.height > mediumResolutionSize.height)
    {
        director->setContentScaleFactor(MIN(largeResolutionSize.height/designResolutionSize.height, largeResolutionSize.width/designResolutionSize.width));
    }
    // if the frame's height is larger than the height of small size.
    else if (frameSize.height > smallResolutionSize.height)
    {
        director->setContentScaleFactor(MIN(mediumResolutionSize.height/designResolutionSize.height, mediumResolutionSize.width/designResolutionSize.width));
    }
    // if the frame's height is smaller than the height of medium size.
    else
    {
        director->setContentScaleFactor(MIN(smallResolutionSize.height/designResolutionSize.height, smallResolutionSize.width/designResolutionSize.width));
    }

    register_all_packages();

    // create a scene. it's an autorelease object
    auto scene = HelloWorld::createScene();

    // run
    director->runWithScene(scene);

    return true;
}

// This function will be called when the app is inactive. When comes a phone call,it's be invoked too
void AppDelegate::applicationDidEnterBackground() {
    Director::getInstance()->stopAnimation();

    // if you use SimpleAudioEngine, it must be pause
    // SimpleAudioEngine::getInstance()->pauseBackgroundMusic();
}

// this function will be called when the app is active again
void AppDelegate::applicationWillEnterForeground() {
    Director::getInstance()->startAnimation();

    // if you use SimpleAudioEngine, it must resume here
    // SimpleAudioEngine::getInstance()->resumeBackgroundMusic();
}
<commit_msg>Return!<commit_after><|endoftext|>