<commit_before>#include <osg/GLExtensions>
#include <osg/Node>
#include <osg/Geometry>
#include <osg/Notify>
#include <osg/MatrixTransform>
#include <osg/Texture2D>
#include <osg/Stencil>
#include <osg/ColorMask>
#include <osg/Depth>
#include <osg/Billboard>
#include <osg/Material>

#include <osgUtil/TransformCallback>
#include <osgUtil/SmoothingVisitor>
#include <osgUtil/UpdateVisitor>

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

#include <osgProducer/Viewer>
#include <Producer/Camera>
#include <Producer/CameraConfig>

osg::ref_ptr<Producer::Camera> gPBufferCamera;
osg::ref_ptr<osgProducer::OsgSceneHandler> gPBufferSceneHandler;

// call back which cretes a deformation field to oscilate the model.
class MyGeometryCallback :
    public osg::Drawable::UpdateCallback,
    public osg::Drawable::AttributeFunctor
{
    public:

        MyGeometryCallback(const osg::Vec3& o,
                           const osg::Vec3& x,const osg::Vec3& y,const osg::Vec3& z,
                           double period,double xphase,double amplitude):
            _firstCall(true),
            _startTime(0.0),
            _time(0.0),
            _period(period),
            _xphase(xphase),
            _amplitude(amplitude),
            _origin(o),
            _xAxis(x),
            _yAxis(y),
            _zAxis(z) {}

        virtual void update(osg::NodeVisitor* nv,osg::Drawable* drawable)
        {
            const osg::FrameStamp* fs = nv->getFrameStamp();
            double referenceTime = fs->getReferenceTime();
            if (_firstCall)
            {
                _firstCall = false;
                _startTime = referenceTime;
            }

            _time = referenceTime-_startTime;

            drawable->accept(*this);
            drawable->dirtyBound();

            osg::Geometry* geometry = dynamic_cast<osg::Geometry*>(drawable);
            if (geometry)
            {
                osgUtil::SmoothingVisitor::smooth(*geometry);
            }

        }

        virtual void apply(osg::Drawable::AttributeType type,unsigned int count,osg::Vec3* begin)
        {
            if (type == osg::Drawable::VERTICES)
            {
                const float TwoPI=2.0f*osg::PI;
                const float phase = -_time/_period;

                osg::Vec3* end = begin+count;
                for (osg::Vec3* itr=begin;itr<end;++itr)
                {
                    osg::Vec3 dv(*itr-_origin);
                    osg::Vec3 local(dv*_xAxis,dv*_yAxis,dv*_zAxis);

                    local.z() = local.x()*_amplitude*
                                sinf(TwoPI*(phase+local.x()*_xphase));

                    (*itr) = _origin +
                             _xAxis*local.x()+
                             _yAxis*local.y()+
                             _zAxis*local.z();
                }
            }
        }

        bool    _firstCall;

        double  _startTime;
        double  _time;

        double  _period;
        double  _xphase;
        float   _amplitude;

        osg::Vec3   _origin;
        osg::Vec3   _xAxis;
        osg::Vec3   _yAxis;
        osg::Vec3   _zAxis;

};

// Custom Texture subload callback, just acts the the standard subload modes in osg::Texture right now
// but code be used to define your own style callbacks.
class MyTextureSubloadCallback : public osg::Texture2D::SubloadCallback
{
    public:

        MyTextureSubloadCallback() {}

        virtual void load(const osg::Texture2D& texture,osg::State&) const
        {
            osg::notify(osg::INFO)<<"doing load"<<std::endl;
            glTexImage2D( GL_TEXTURE_2D, 0, texture.getInternalFormat(), texture.getTextureWidth(), texture.getTextureHeight(), 0, GL_RGB, GL_FLOAT, 0 );
        }

        virtual void subload(const osg::Texture2D& ,osg::State&) const
        {
            osg::notify(osg::INFO)<<"doing subload"<<std::endl;
            gPBufferCamera->getRenderSurface()->bindPBufferToTexture(Producer::RenderSurface::FrontBuffer);
        }
};

osg::Node* createTexturedFlag(unsigned int width, unsigned int height)
{
    // create the quad to visualize.
    osg::Geometry* polyGeom = new osg::Geometry();

    polyGeom->setSupportsDisplayList(false);

    osg::Vec3 origin(0.0f,0.0f,0.0f);
    osg::Vec3 xAxis(1.0f,0.0f,0.0f);
    osg::Vec3 yAxis(0.0f,0.0f,1.0f);
    osg::Vec3 zAxis(0.0f,-1.0f,0.0f);
    float flag_height = 100.0f;
    float flag_width = 200.0f;
    int noSteps = 20;

    osg::Vec3Array* vertices = new osg::Vec3Array;
    osg::Vec3 bottom = origin;
    osg::Vec3 top = origin; top.z()+= flag_height;
    osg::Vec3 dv = xAxis*(flag_width/((float)(noSteps-1)));

    osg::Vec2Array* texcoords = new osg::Vec2Array;
    osg::Vec2 bottom_texcoord(0.0f,0.0f);
    osg::Vec2 top_texcoord(0.0f,1.0f);
    osg::Vec2 dv_texcoord(1.0f/(float)(noSteps-1),0.0f);

    for(int i=0;i<noSteps;++i)
    {
        vertices->push_back(top);
        vertices->push_back(bottom);
        top+=dv;
        bottom+=dv;

        texcoords->push_back(top_texcoord);
        texcoords->push_back(bottom_texcoord);
        top_texcoord+=dv_texcoord;
        bottom_texcoord+=dv_texcoord;
    }

    // pass the created vertex array to the points geometry object.
    polyGeom->setVertexArray(vertices);

    polyGeom->setTexCoordArray(0,texcoords);

    osg::Vec4Array* colors = new osg::Vec4Array;
    colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
    polyGeom->setColorArray(colors);
    polyGeom->setColorBinding(osg::Geometry::BIND_OVERALL);

    polyGeom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUAD_STRIP,0,vertices->size()));

    // new we need to add the texture to the Drawable, we do so by creating a
    // StateSet to contain the Texture StateAttribute.
    osg::StateSet* stateset = new osg::StateSet;

    // Dynamic texture filled with data from pbuffer.
    osg::Texture2D* texture = new osg::Texture2D;
    //texture->setSubloadMode(osg::Texture::IF_DIRTY);
    texture->setInternalFormat(GL_RGB);
    texture->setTextureSize(width,height);
    texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
    texture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
    texture->setWrap(osg::Texture2D::WRAP_S,osg::Texture2D::CLAMP);
    texture->setWrap(osg::Texture2D::WRAP_T,osg::Texture2D::CLAMP);
    texture->setSubloadCallback(new MyTextureSubloadCallback());
    stateset->setTextureAttributeAndModes(0, texture,osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);

    polyGeom->setStateSet(stateset);

    polyGeom->setUpdateCallback(new MyGeometryCallback(origin,xAxis,yAxis,zAxis,1.0,1.0/flag_width,0.2f));

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

    osg::Group* parent = new osg::Group;
    parent->addChild(geode);

    return parent;
}

void InitPBufferCamera(osg::Node* subgraph, unsigned int width, unsigned int height)
{
    if (!subgraph) return;

    gPBufferCamera = new Producer::Camera;
    gPBufferCamera->getRenderSurface()->setDrawableType( Producer::RenderSurface::DrawableType_PBuffer );
    gPBufferCamera->getRenderSurface()->setWindowRectangle( 0, 0, width, height );
    gPBufferCamera->getRenderSurface()->setRenderToTextureMode(Producer::RenderSurface::RenderToRGBTexture);

    gPBufferSceneHandler = new osgProducer::OsgSceneHandler;
    gPBufferSceneHandler->getSceneView()->setDefaults();
    gPBufferSceneHandler->getSceneView()->setSceneData(subgraph);

    gPBufferCamera->setSceneHandler( gPBufferSceneHandler.get());

    gPBufferCamera->setClearColor( 0.1f,0.9f,0.3f,1.0f );

    const osg::BoundingSphere& bs = subgraph->getBound();
    if (!bs.valid())
    {
        osg::notify(osg::WARN) << "bb invalid"<<subgraph<<std::endl;
        return;
    }

    float znear = 1.0f*bs.radius();
    float zfar  = 3.0f*bs.radius();

    // 2:1 aspect ratio as per flag geomtry below.
    float top   = 0.25f*znear;
    float right = 0.5f*znear;

    znear *= 0.9f;
    zfar *= 1.1f;

    osg::Vec3 eye(bs.center() + osg::Vec3(0.0f, 2.0f, 0.0f)*bs.radius());

    gPBufferCamera->setViewByLookat(
        eye.x(), eye.y(), eye.z(),
        bs.center().x(), bs.center().y(), bs.center().z(),
        0.0f, 0.0f, 1.0f);

    gPBufferCamera->setLensFrustum(-right,right,-top,top,znear,zfar);

    // The Producer PBuffer example says:
    //
    //      "This line is not necessary on glX pbuffer examples, but Windows
    //       seems to  not like rendering to the back buffer on pbuffers"
    //
    // but I've found that doing this causes a flickering texture.  Everything
    // works fine for me (on Windows) if I just comment it out.

    //gPBufferSceneHandler->getSceneView()->setDrawBufferValue( GL_FRONT );
}

int main( int argc, char **argv )
{
    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    osg::DisplaySettings::instance()->readCommandLine(arguments);

    // set up the usage document, in case we need to print out how to use this program.
    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use pbuffers and render to texture..");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
    arguments.getApplicationUsage()->addCommandLineOption("--width <integer>","Set the width of the pbuffer & texture");
    arguments.getApplicationUsage()->addCommandLineOption("--height <integer>","Set the height of the pbuffer & texture");

    // construct the viewer.
    osgProducer::Viewer viewer(arguments);

    // set up the value with sensible default event handlers.
    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);

    // get details on keyboard and mouse bindings used by the viewer.
    viewer.getUsage(*arguments.getApplicationUsage());

    unsigned int width=1024;
    unsigned int height=512;

    while (arguments.read("--width",width)) {}
    while (arguments.read("--height",height)) {}

    // if user request help write it out to cout.
    if (arguments.read("-h") || arguments.read("--help"))
    {
        arguments.getApplicationUsage()->write(std::cout);
        return 1;
    }

    // any option left unread are converted into errors to write out later.
    arguments.reportRemainingOptionsAsUnrecognized();

    // report any errors if they have occured when parsing the program aguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }

    if (arguments.argc()<=1)
    {
        arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
        return 1;
    }

    // load the nodes from the commandline arguments.
    osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments);

    if (!loadedModel)
    {
//        write_usage(osg::notify(osg::NOTICE),argv[0]);
        return 1;
    }

    // create a transform to spin the model.
    osg::MatrixTransform* loadedModelTransform = new osg::MatrixTransform;
    loadedModelTransform->addChild(loadedModel.get());

    osg::NodeCallback* nc = new osgUtil::TransformCallback(loadedModelTransform->getBound().center(),osg::Vec3(0.0f,0.0f,1.0f),osg::inDegrees(45.0f));
    loadedModelTransform->setUpdateCallback(nc);

    osg::Group* rootNode = new osg::Group();

    // Create a waving rectangle that will use the pbuffer as a texture.
    rootNode->addChild(createTexturedFlag(width,height));

    // Set up a camera that will render a view of the model to the pbuffer.
    InitPBufferCamera(loadedModelTransform,width, height);

    // set the scene to render
    viewer.setSceneData(rootNode);

    // create the windows and run the threads.
    viewer.realize();

#if defined(GLX_VERSION_1_1)
    // This determins where Pixel reads occur from.  The main Camera will
    // set the pBuffer camera's rendersurface as the buffer to read from.
    Producer::Camera* camera = viewer.getCamera(0);
    camera->getRenderSurface()->setReadDrawable( gPBufferCamera->getRenderSurface());
#endif

    while( !viewer.done() )
    {
        // wait for all cull and draw threads to complete.
        viewer.sync();

        // update the scene by traversing it with the the update visitor which will
        // call all node update callbacks and animations.
        loadedModelTransform->accept(*viewer.getUpdateVisitor());
        viewer.update();

        // fire off the cull and draw traversals of the scene.
        // first the pbuffer draw
        gPBufferCamera->frame();

        // then the main view draw.
        viewer.frame();
    }

    // wait for all cull and draw threads to complete before exit.
    viewer.sync();

    gPBufferCamera = 0;
    gPBufferSceneHandler = 0;

    return 0;
}
<commit_msg>Added destructor to fix Cygwin build problem.<commit_after>#include <osg/GLExtensions>
#include <osg/Node>
#include <osg/Geometry>
#include <osg/Notify>
#include <osg/MatrixTransform>
#include <osg/Texture2D>
#include <osg/Stencil>
#include <osg/ColorMask>
#include <osg/Depth>
#include <osg/Billboard>
#include <osg/Material>

#include <osgUtil/TransformCallback>
#include <osgUtil/SmoothingVisitor>
#include <osgUtil/UpdateVisitor>

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

#include <osgProducer/Viewer>
#include <Producer/Camera>
#include <Producer/CameraConfig>

osg::ref_ptr<Producer::Camera> gPBufferCamera;
osg::ref_ptr<osgProducer::OsgSceneHandler> gPBufferSceneHandler;

// call back which cretes a deformation field to oscilate the model.
class MyGeometryCallback :
    public osg::Drawable::UpdateCallback,
    public osg::Drawable::AttributeFunctor
{
    public:

        MyGeometryCallback(const osg::Vec3& o,
                           const osg::Vec3& x,const osg::Vec3& y,const osg::Vec3& z,
                           double period,double xphase,double amplitude):
            _firstCall(true),
            _startTime(0.0),
            _time(0.0),
            _period(period),
            _xphase(xphase),
            _amplitude(amplitude),
            _origin(o),
            _xAxis(x),
            _yAxis(y),
            _zAxis(z) {}

        virtual void update(osg::NodeVisitor* nv,osg::Drawable* drawable)
        {
            const osg::FrameStamp* fs = nv->getFrameStamp();
            double referenceTime = fs->getReferenceTime();
            if (_firstCall)
            {
                _firstCall = false;
                _startTime = referenceTime;
            }

            _time = referenceTime-_startTime;

            drawable->accept(*this);
            drawable->dirtyBound();

            osg::Geometry* geometry = dynamic_cast<osg::Geometry*>(drawable);
            if (geometry)
            {
                osgUtil::SmoothingVisitor::smooth(*geometry);
            }

        }

        virtual void apply(osg::Drawable::AttributeType type,unsigned int count,osg::Vec3* begin)
        {
            if (type == osg::Drawable::VERTICES)
            {
                const float TwoPI=2.0f*osg::PI;
                const float phase = -_time/_period;

                osg::Vec3* end = begin+count;
                for (osg::Vec3* itr=begin;itr<end;++itr)
                {
                    osg::Vec3 dv(*itr-_origin);
                    osg::Vec3 local(dv*_xAxis,dv*_yAxis,dv*_zAxis);

                    local.z() = local.x()*_amplitude*
                                sinf(TwoPI*(phase+local.x()*_xphase));

                    (*itr) = _origin +
                             _xAxis*local.x()+
                             _yAxis*local.y()+
                             _zAxis*local.z();
                }
            }
        }

        bool    _firstCall;

        double  _startTime;
        double  _time;

        double  _period;
        double  _xphase;
        float   _amplitude;

        osg::Vec3   _origin;
        osg::Vec3   _xAxis;
        osg::Vec3   _yAxis;
        osg::Vec3   _zAxis;

};

// Custom Texture subload callback, just acts the the standard subload modes in osg::Texture right now
// but code be used to define your own style callbacks.
class MyTextureSubloadCallback : public osg::Texture2D::SubloadCallback
{
    public:

        MyTextureSubloadCallback() {}

        virtual ~MyTextureSubloadCallback() {}

        virtual void load(const osg::Texture2D& texture,osg::State&) const
        {
            osg::notify(osg::INFO)<<"doing load"<<std::endl;
            glTexImage2D( GL_TEXTURE_2D, 0, texture.getInternalFormat(), texture.getTextureWidth(), texture.getTextureHeight(), 0, GL_RGB, GL_FLOAT, 0 );
        }

        virtual void subload(const osg::Texture2D& ,osg::State&) const
        {
            osg::notify(osg::INFO)<<"doing subload"<<std::endl;
            gPBufferCamera->getRenderSurface()->bindPBufferToTexture(Producer::RenderSurface::FrontBuffer);
        }
};

osg::Node* createTexturedFlag(unsigned int width, unsigned int height)
{
    // create the quad to visualize.
    osg::Geometry* polyGeom = new osg::Geometry();

    polyGeom->setSupportsDisplayList(false);

    osg::Vec3 origin(0.0f,0.0f,0.0f);
    osg::Vec3 xAxis(1.0f,0.0f,0.0f);
    osg::Vec3 yAxis(0.0f,0.0f,1.0f);
    osg::Vec3 zAxis(0.0f,-1.0f,0.0f);
    float flag_height = 100.0f;
    float flag_width = 200.0f;
    int noSteps = 20;

    osg::Vec3Array* vertices = new osg::Vec3Array;
    osg::Vec3 bottom = origin;
    osg::Vec3 top = origin; top.z()+= flag_height;
    osg::Vec3 dv = xAxis*(flag_width/((float)(noSteps-1)));

    osg::Vec2Array* texcoords = new osg::Vec2Array;
    osg::Vec2 bottom_texcoord(0.0f,0.0f);
    osg::Vec2 top_texcoord(0.0f,1.0f);
    osg::Vec2 dv_texcoord(1.0f/(float)(noSteps-1),0.0f);

    for(int i=0;i<noSteps;++i)
    {
        vertices->push_back(top);
        vertices->push_back(bottom);
        top+=dv;
        bottom+=dv;

        texcoords->push_back(top_texcoord);
        texcoords->push_back(bottom_texcoord);
        top_texcoord+=dv_texcoord;
        bottom_texcoord+=dv_texcoord;
    }

    // pass the created vertex array to the points geometry object.
    polyGeom->setVertexArray(vertices);

    polyGeom->setTexCoordArray(0,texcoords);

    osg::Vec4Array* colors = new osg::Vec4Array;
    colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
    polyGeom->setColorArray(colors);
    polyGeom->setColorBinding(osg::Geometry::BIND_OVERALL);

    polyGeom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUAD_STRIP,0,vertices->size()));

    // new we need to add the texture to the Drawable, we do so by creating a
    // StateSet to contain the Texture StateAttribute.
    osg::StateSet* stateset = new osg::StateSet;

    // Dynamic texture filled with data from pbuffer.
    osg::Texture2D* texture = new osg::Texture2D;
    //texture->setSubloadMode(osg::Texture::IF_DIRTY);
    texture->setInternalFormat(GL_RGB);
    texture->setTextureSize(width,height);
    texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
    texture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
    texture->setWrap(osg::Texture2D::WRAP_S,osg::Texture2D::CLAMP);
    texture->setWrap(osg::Texture2D::WRAP_T,osg::Texture2D::CLAMP);
    texture->setSubloadCallback(new MyTextureSubloadCallback());
    stateset->setTextureAttributeAndModes(0, texture,osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);

    polyGeom->setStateSet(stateset);

    polyGeom->setUpdateCallback(new MyGeometryCallback(origin,xAxis,yAxis,zAxis,1.0,1.0/flag_width,0.2f));

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

    osg::Group* parent = new osg::Group;
    parent->addChild(geode);

    return parent;
}

void InitPBufferCamera(osg::Node* subgraph, unsigned int width, unsigned int height)
{
    if (!subgraph) return;

    gPBufferCamera = new Producer::Camera;
    gPBufferCamera->getRenderSurface()->setDrawableType( Producer::RenderSurface::DrawableType_PBuffer );
    gPBufferCamera->getRenderSurface()->setWindowRectangle( 0, 0, width, height );
    gPBufferCamera->getRenderSurface()->setRenderToTextureMode(Producer::RenderSurface::RenderToRGBTexture);

    gPBufferSceneHandler = new osgProducer::OsgSceneHandler;
    gPBufferSceneHandler->getSceneView()->setDefaults();
    gPBufferSceneHandler->getSceneView()->setSceneData(subgraph);

    gPBufferCamera->setSceneHandler( gPBufferSceneHandler.get());

    gPBufferCamera->setClearColor( 0.1f,0.9f,0.3f,1.0f );

    const osg::BoundingSphere& bs = subgraph->getBound();
    if (!bs.valid())
    {
        osg::notify(osg::WARN) << "bb invalid"<<subgraph<<std::endl;
        return;
    }

    float znear = 1.0f*bs.radius();
    float zfar  = 3.0f*bs.radius();

    // 2:1 aspect ratio as per flag geomtry below.
    float top   = 0.25f*znear;
    float right = 0.5f*znear;

    znear *= 0.9f;
    zfar *= 1.1f;

    osg::Vec3 eye(bs.center() + osg::Vec3(0.0f, 2.0f, 0.0f)*bs.radius());

    gPBufferCamera->setViewByLookat(
        eye.x(), eye.y(), eye.z(),
        bs.center().x(), bs.center().y(), bs.center().z(),
        0.0f, 0.0f, 1.0f);

    gPBufferCamera->setLensFrustum(-right,right,-top,top,znear,zfar);

    // The Producer PBuffer example says:
    //
    //      "This line is not necessary on glX pbuffer examples, but Windows
    //       seems to  not like rendering to the back buffer on pbuffers"
    //
    // but I've found that doing this causes a flickering texture.  Everything
    // works fine for me (on Windows) if I just comment it out.

    //gPBufferSceneHandler->getSceneView()->setDrawBufferValue( GL_FRONT );
}

int main( int argc, char **argv )
{
    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    osg::DisplaySettings::instance()->readCommandLine(arguments);

    // set up the usage document, in case we need to print out how to use this program.
    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use pbuffers and render to texture..");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
    arguments.getApplicationUsage()->addCommandLineOption("--width <integer>","Set the width of the pbuffer & texture");
    arguments.getApplicationUsage()->addCommandLineOption("--height <integer>","Set the height of the pbuffer & texture");

    // construct the viewer.
    osgProducer::Viewer viewer(arguments);

    // set up the value with sensible default event handlers.
    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);

    // get details on keyboard and mouse bindings used by the viewer.
    viewer.getUsage(*arguments.getApplicationUsage());

    unsigned int width=1024;
    unsigned int height=512;

    while (arguments.read("--width",width)) {}
    while (arguments.read("--height",height)) {}

    // if user request help write it out to cout.
    if (arguments.read("-h") || arguments.read("--help"))
    {
        arguments.getApplicationUsage()->write(std::cout);
        return 1;
    }

    // any option left unread are converted into errors to write out later.
    arguments.reportRemainingOptionsAsUnrecognized();

    // report any errors if they have occured when parsing the program aguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }

    if (arguments.argc()<=1)
    {
        arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
        return 1;
    }

    // load the nodes from the commandline arguments.
    osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments);

    if (!loadedModel)
    {
//        write_usage(osg::notify(osg::NOTICE),argv[0]);
        return 1;
    }

    // create a transform to spin the model.
    osg::MatrixTransform* loadedModelTransform = new osg::MatrixTransform;
    loadedModelTransform->addChild(loadedModel.get());

    osg::NodeCallback* nc = new osgUtil::TransformCallback(loadedModelTransform->getBound().center(),osg::Vec3(0.0f,0.0f,1.0f),osg::inDegrees(45.0f));
    loadedModelTransform->setUpdateCallback(nc);

    osg::Group* rootNode = new osg::Group();

    // Create a waving rectangle that will use the pbuffer as a texture.
    rootNode->addChild(createTexturedFlag(width,height));

    // Set up a camera that will render a view of the model to the pbuffer.
    InitPBufferCamera(loadedModelTransform,width, height);

    // set the scene to render
    viewer.setSceneData(rootNode);

    // create the windows and run the threads.
    viewer.realize();

#if defined(GLX_VERSION_1_1)
    // This determins where Pixel reads occur from.  The main Camera will
    // set the pBuffer camera's rendersurface as the buffer to read from.
    Producer::Camera* camera = viewer.getCamera(0);
    camera->getRenderSurface()->setReadDrawable( gPBufferCamera->getRenderSurface());
#endif

    while( !viewer.done() )
    {
        // wait for all cull and draw threads to complete.
        viewer.sync();

        // update the scene by traversing it with the the update visitor which will
        // call all node update callbacks and animations.
        loadedModelTransform->accept(*viewer.getUpdateVisitor());
        viewer.update();

        // fire off the cull and draw traversals of the scene.
        // first the pbuffer draw
        gPBufferCamera->frame();

        // then the main view draw.
        viewer.frame();
    }

    // wait for all cull and draw threads to complete before exit.
    viewer.sync();

    gPBufferCamera = 0;
    gPBufferSceneHandler = 0;

    return 0;
}
<|endoftext|>


<commit_before>#pragma once

#include <type_traits>
#include <ostream>

using std::ostream;
using std::enable_if;
using std::is_same;

template <typename T, size_t N>
typename enable_if<!is_same<T, char>::value, ostream &>::type
operator<<(ostream & os, const T (&arr)[N]) {
  os << seq::delimBegin;

  if (N > 0) {
    os << arr[0];

    for (unsigned int idx{1}; idx < N; ++idx) {
      os << seq::delimSep << arr[idx];
    }
  }

  return os << seq::delimEnd;
}
<commit_msg>noexcept for raw print<commit_after>#pragma once

#include <type_traits>
#include <ostream>

using std::ostream;
using std::enable_if;
using std::is_same;

template <typename T, size_t N>
typename enable_if<!is_same<T, char>::value, ostream &>::type
operator<<(ostream & os, const T (&arr)[N]) noexcept {
  os << seq::delimBegin;

  if (N > 0) {
    os << arr[0];

    for (unsigned int idx{1}; idx < N; ++idx) {
      os << seq::delimSep << arr[idx];
    }
  }

  return os << seq::delimEnd;
}
<|endoftext|>


<commit_before><commit_msg>Fixed build error<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: statusbarwrapper.cxx,v $
 * $Revision: 1.7 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_framework.hxx"

#include <uielement/statusbarwrapper.hxx>

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________
#include <threadhelp/resetableguard.hxx>
#include <helper/actiontriggerhelper.hxx>
#include <uielement/constitemcontainer.hxx>
#include <uielement/rootitemcontainer.hxx>
#include <uielement/statusbar.hxx>
#include <helpid.hrc>

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/awt/XSystemDependentMenuPeer.hpp>
#include <com/sun/star/awt/XMenuBar.hpp>
#include <com/sun/star/container/XIndexContainer.hpp>
#include <com/sun/star/container/XNameAccess.hpp>
#include <com/sun/star/ui/UIElementType.hpp>

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________
#include <comphelper/processfactory.hxx>
#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_
#include <toolkit/unohlp.hxx>
#endif

#include <tools/solar.h>
#include <vcl/svapp.hxx>
#include <rtl/logfile.hxx>

using namespace rtl;
using namespace com::sun::star::uno;
using namespace com::sun::star::beans;
using namespace com::sun::star::frame;
using namespace com::sun::star::lang;
using namespace com::sun::star::container;
using namespace com::sun::star::awt;
using namespace ::com::sun::star::ui;

namespace framework
{

StatusBarWrapper::StatusBarWrapper(
    const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& xServiceManager
    )
 :  UIConfigElementWrapperBase( UIElementType::STATUSBAR ),
    m_xServiceFactory( xServiceManager )
{
}

StatusBarWrapper::~StatusBarWrapper()
{
}

const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& StatusBarWrapper::getServiceFactory()
{
    ResetableGuard aLock( m_aLock );
    if ( m_bDisposed )
        throw DisposedException();

    return m_xServiceFactory;
}

void SAL_CALL StatusBarWrapper::dispose() throw (::com::sun::star::uno::RuntimeException)
{
    Reference< XComponent > xThis( static_cast< OWeakObject* >(this), UNO_QUERY );

    com::sun::star::lang::EventObject aEvent( xThis );
    m_aListenerContainer.disposeAndClear( aEvent );

    ResetableGuard aLock( m_aLock );
    if ( !m_bDisposed )
    {
        if ( m_xStatusBarManager.is() )
            m_xStatusBarManager->dispose();
        m_xStatusBarManager.clear();
        m_xConfigSource.clear();
        m_xConfigData.clear();
        m_xServiceFactory.clear();

        m_bDisposed = sal_True;
    }
    else
        throw DisposedException();
}

// XInitialization
void SAL_CALL StatusBarWrapper::initialize( const Sequence< Any >& aArguments ) throw ( Exception, RuntimeException )
{
    ResetableGuard aLock( m_aLock );

    if ( m_bDisposed )
        throw DisposedException();

    if ( !m_bInitialized )
    {
        UIConfigElementWrapperBase::initialize( aArguments );

        Reference< XFrame > xFrame( m_xWeakFrame );
        if ( xFrame.is() && m_xConfigSource.is() )
        {
            // Create VCL based toolbar which will be filled with settings data
            StatusBar*        pStatusBar( 0 );
            StatusBarManager* pStatusBarManager( 0 );
            {
                vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
                Window* pWindow = VCLUnoHelper::GetWindow( xFrame->getContainerWindow() );
                if ( pWindow )
                {
                    ULONG nStyles = WinBits( WB_LEFT | WB_3DLOOK );

                    pStatusBar = new FrameworkStatusBar( pWindow, nStyles );
                    pStatusBarManager = new StatusBarManager( m_xServiceFactory, xFrame, m_aResourceURL, pStatusBar );
                    ((FrameworkStatusBar*)pStatusBar)->SetStatusBarManager( pStatusBarManager );
                    m_xStatusBarManager = Reference< XComponent >( static_cast< OWeakObject *>( pStatusBarManager ), UNO_QUERY );
                    pStatusBar->SetUniqueId( HID_STATUSBAR );
                }
            }

            try
            {
                m_xConfigData = m_xConfigSource->getSettings( m_aResourceURL, sal_False );
                if ( m_xConfigData.is() && pStatusBar && pStatusBarManager )
                {
                    // Fill statusbar with container contents
                    pStatusBarManager->FillStatusBar( m_xConfigData );
                }
            }
            catch ( NoSuchElementException& )
            {
            }
        }
    }
}

// XUIElementSettings
void SAL_CALL StatusBarWrapper::updateSettings() throw ( RuntimeException )
{
    ResetableGuard aLock( m_aLock );

    if ( m_bDisposed )
        throw DisposedException();

    if ( m_bPersistent &&
         m_xConfigSource.is() &&
         m_xStatusBarManager.is() )
    {
        try
        {
            StatusBarManager* pStatusBarManager = static_cast< StatusBarManager *>( m_xStatusBarManager.get() );

            m_xConfigData = m_xConfigSource->getSettings( m_aResourceURL, sal_False );
            if ( m_xConfigData.is() )
                pStatusBarManager->FillStatusBar( m_xConfigData );
        }
        catch ( NoSuchElementException& )
        {
        }
    }
}

void SAL_CALL StatusBarWrapper::setSettings( const Reference< XIndexAccess >& xSettings ) throw ( RuntimeException )
{
    ResetableGuard aLock( m_aLock );

    if ( m_bDisposed )
        throw DisposedException();

    if ( xSettings.is() )
    {
        // Create a copy of the data if the container is not const
        Reference< XIndexReplace > xReplace( xSettings, UNO_QUERY );
        if ( xReplace.is() )
            m_xConfigData = Reference< XIndexAccess >( static_cast< OWeakObject * >( new ConstItemContainer( xSettings ) ), UNO_QUERY );
        else
            m_xConfigData = xSettings;

        if ( m_xConfigSource.is() && m_bPersistent )
        {
            OUString aResourceURL( m_aResourceURL );
            Reference< XUIConfigurationManager > xUICfgMgr( m_xConfigSource );

            aLock.unlock();

            try
            {
                xUICfgMgr->replaceSettings( aResourceURL, m_xConfigData );
            }
            catch( NoSuchElementException& )
            {
            }
        }
    }
}

Reference< XIndexAccess > SAL_CALL StatusBarWrapper::getSettings( sal_Bool bWriteable ) throw ( RuntimeException )
{
    ResetableGuard aLock( m_aLock );

    if ( m_bDisposed )
        throw DisposedException();

    if ( bWriteable )
        return Reference< XIndexAccess >( static_cast< OWeakObject * >( new RootItemContainer( m_xConfigData ) ), UNO_QUERY );
    else
        return m_xConfigData;
}

Reference< XInterface > SAL_CALL StatusBarWrapper::getRealInterface() throw ( RuntimeException )
{
    ResetableGuard aLock( m_aLock );

    if ( m_xStatusBarManager.is() )
    {
        StatusBarManager* pStatusBarManager = static_cast< StatusBarManager *>( m_xStatusBarManager.get() );
        if ( pStatusBarManager )
        {
            Window* pWindow = (Window *)pStatusBarManager->GetStatusBar();
            if ( pWindow )
                return Reference< XInterface >( VCLUnoHelper::GetInterface( pWindow ), UNO_QUERY );
        }
    }

    return Reference< XInterface >();
}

} // namespace framework
<commit_msg>INTEGRATION: CWS obo30 (1.7.40); FILE MERGED 2008/06/05 14:55:32 obo 1.7.40.2: #i90100# missing EOL 2008/05/29 14:43:46 obo 1.7.40.1: #i90100# ambigous Reference during ENABLE_PCH build<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: statusbarwrapper.cxx,v $
 * $Revision: 1.8 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_framework.hxx"

#include <uielement/statusbarwrapper.hxx>

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________
#include <threadhelp/resetableguard.hxx>
#include <helper/actiontriggerhelper.hxx>
#include <uielement/constitemcontainer.hxx>
#include <uielement/rootitemcontainer.hxx>
#include <uielement/statusbar.hxx>
#include <helpid.hrc>

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/awt/XSystemDependentMenuPeer.hpp>
#include <com/sun/star/awt/XMenuBar.hpp>
#include <com/sun/star/container/XIndexContainer.hpp>
#include <com/sun/star/container/XNameAccess.hpp>
#include <com/sun/star/ui/UIElementType.hpp>

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________
#include <comphelper/processfactory.hxx>
#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_
#include <toolkit/unohlp.hxx>
#endif

#include <tools/solar.h>
#include <vcl/svapp.hxx>
#include <rtl/logfile.hxx>

using namespace com::sun::star::uno;
using namespace com::sun::star::beans;
using namespace com::sun::star::frame;
using namespace com::sun::star::lang;
using namespace com::sun::star::container;
using namespace com::sun::star::awt;
using namespace ::com::sun::star::ui;

namespace framework
{

StatusBarWrapper::StatusBarWrapper(
    const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& xServiceManager
    )
 :  UIConfigElementWrapperBase( UIElementType::STATUSBAR ),
    m_xServiceFactory( xServiceManager )
{
}

StatusBarWrapper::~StatusBarWrapper()
{
}

const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& StatusBarWrapper::getServiceFactory()
{
    ResetableGuard aLock( m_aLock );
    if ( m_bDisposed )
        throw DisposedException();

    return m_xServiceFactory;
}

void SAL_CALL StatusBarWrapper::dispose() throw (::com::sun::star::uno::RuntimeException)
{
    Reference< XComponent > xThis( static_cast< OWeakObject* >(this), UNO_QUERY );

    com::sun::star::lang::EventObject aEvent( xThis );
    m_aListenerContainer.disposeAndClear( aEvent );

    ResetableGuard aLock( m_aLock );
    if ( !m_bDisposed )
    {
        if ( m_xStatusBarManager.is() )
            m_xStatusBarManager->dispose();
        m_xStatusBarManager.clear();
        m_xConfigSource.clear();
        m_xConfigData.clear();
        m_xServiceFactory.clear();

        m_bDisposed = sal_True;
    }
    else
        throw DisposedException();
}

// XInitialization
void SAL_CALL StatusBarWrapper::initialize( const Sequence< Any >& aArguments ) throw ( Exception, RuntimeException )
{
    ResetableGuard aLock( m_aLock );

    if ( m_bDisposed )
        throw DisposedException();

    if ( !m_bInitialized )
    {
        UIConfigElementWrapperBase::initialize( aArguments );

        Reference< XFrame > xFrame( m_xWeakFrame );
        if ( xFrame.is() && m_xConfigSource.is() )
        {
            // Create VCL based toolbar which will be filled with settings data
            StatusBar*        pStatusBar( 0 );
            StatusBarManager* pStatusBarManager( 0 );
            {
                vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
                Window* pWindow = VCLUnoHelper::GetWindow( xFrame->getContainerWindow() );
                if ( pWindow )
                {
                    ULONG nStyles = WinBits( WB_LEFT | WB_3DLOOK );

                    pStatusBar = new FrameworkStatusBar( pWindow, nStyles );
                    pStatusBarManager = new StatusBarManager( m_xServiceFactory, xFrame, m_aResourceURL, pStatusBar );
                    ((FrameworkStatusBar*)pStatusBar)->SetStatusBarManager( pStatusBarManager );
                    m_xStatusBarManager = Reference< XComponent >( static_cast< OWeakObject *>( pStatusBarManager ), UNO_QUERY );
                    pStatusBar->SetUniqueId( HID_STATUSBAR );
                }
            }

            try
            {
                m_xConfigData = m_xConfigSource->getSettings( m_aResourceURL, sal_False );
                if ( m_xConfigData.is() && pStatusBar && pStatusBarManager )
                {
                    // Fill statusbar with container contents
                    pStatusBarManager->FillStatusBar( m_xConfigData );
                }
            }
            catch ( NoSuchElementException& )
            {
            }
        }
    }
}

// XUIElementSettings
void SAL_CALL StatusBarWrapper::updateSettings() throw ( RuntimeException )
{
    ResetableGuard aLock( m_aLock );

    if ( m_bDisposed )
        throw DisposedException();

    if ( m_bPersistent &&
         m_xConfigSource.is() &&
         m_xStatusBarManager.is() )
    {
        try
        {
            StatusBarManager* pStatusBarManager = static_cast< StatusBarManager *>( m_xStatusBarManager.get() );

            m_xConfigData = m_xConfigSource->getSettings( m_aResourceURL, sal_False );
            if ( m_xConfigData.is() )
                pStatusBarManager->FillStatusBar( m_xConfigData );
        }
        catch ( NoSuchElementException& )
        {
        }
    }
}

void SAL_CALL StatusBarWrapper::setSettings( const Reference< XIndexAccess >& xSettings ) throw ( RuntimeException )
{
    ResetableGuard aLock( m_aLock );

    if ( m_bDisposed )
        throw DisposedException();

    if ( xSettings.is() )
    {
        // Create a copy of the data if the container is not const
        Reference< XIndexReplace > xReplace( xSettings, UNO_QUERY );
        if ( xReplace.is() )
            m_xConfigData = Reference< XIndexAccess >( static_cast< OWeakObject * >( new ConstItemContainer( xSettings ) ), UNO_QUERY );
        else
            m_xConfigData = xSettings;

        if ( m_xConfigSource.is() && m_bPersistent )
        {
            ::rtl::OUString aResourceURL( m_aResourceURL );
            Reference< XUIConfigurationManager > xUICfgMgr( m_xConfigSource );

            aLock.unlock();

            try
            {
                xUICfgMgr->replaceSettings( aResourceURL, m_xConfigData );
            }
            catch( NoSuchElementException& )
            {
            }
        }
    }
}

Reference< XIndexAccess > SAL_CALL StatusBarWrapper::getSettings( sal_Bool bWriteable ) throw ( RuntimeException )
{
    ResetableGuard aLock( m_aLock );

    if ( m_bDisposed )
        throw DisposedException();

    if ( bWriteable )
        return Reference< XIndexAccess >( static_cast< OWeakObject * >( new RootItemContainer( m_xConfigData ) ), UNO_QUERY );
    else
        return m_xConfigData;
}

Reference< XInterface > SAL_CALL StatusBarWrapper::getRealInterface() throw ( RuntimeException )
{
    ResetableGuard aLock( m_aLock );

    if ( m_xStatusBarManager.is() )
    {
        StatusBarManager* pStatusBarManager = static_cast< StatusBarManager *>( m_xStatusBarManager.get() );
        if ( pStatusBarManager )
        {
            Window* pWindow = (Window *)pStatusBarManager->GetStatusBar();
            if ( pWindow )
                return Reference< XInterface >( VCLUnoHelper::GetInterface( pWindow ), UNO_QUERY );
        }
    }

    return Reference< XInterface >();
}

} // namespace framework

<|endoftext|>


<commit_before><commit_msg>Fix typo.<commit_after><|endoftext|>


<commit_before><commit_msg>Detect that window isn't minimized more often<commit_after><|endoftext|>


<commit_before><commit_msg>snapshot: swap properly internally<commit_after><|endoftext|>


<commit_before>#include "osm_pbf_reader.hpp"

#include <iostream>

#include <fstream>
#ifndef _WIN32
#include <arpa/inet.h>
#endif
#include <zlib.h>

using namespace std ;

#define MAX_BLOCK_HEADER_SIZE 64*1024
#define MAX_BLOB_SIZE 32*1024*1024
#define NANO_DEGREE .000000001

namespace OSM {

using PBF::BlockHeader ;
using PBF::Blob ;
using PBF::PrimitiveGroup ;
using PBF::StringTable ;
using PBF::HeaderBlock;
using PBF::PrimitiveBlock ;
using PBF::DenseNodes ;

static uint32_t get_length(istream &input)
{
    char buf[4];

    if ( !input.read(buf, sizeof(buf) ) ) return 0;

    return ntohl(*((size_t *)buf));
}

static bool read_header(BlockHeader &header_msg, istream &input)
{
    size_t length = get_length(input);

    if ( length == 0 ) return false ;

    std::unique_ptr<char []> buf(new char [length]) ;

    if ( !buf || !input.read(buf.get(), length) ) return false ;

    return header_msg.ParseFromArray(buf.get(), length) ;
}

static bool read_blob(Blob &blob_msg, istream &input, int32_t length)
{
    std::unique_ptr<char []> buf(new char [length]) ;

    if ( !buf || !input.read(buf.get(), length) ) return false ;

    return blob_msg.ParseFromArray(buf.get(), length) ;
}

static bool uncompress_blob(PBF::Blob &bmsg, char *ubuf)
{
    if ( bmsg.has_raw() ) {
        memcpy(ubuf, bmsg.raw().data(), bmsg.raw().size());
    }
    else if ( bmsg.has_zlib_data() ) {

        int ret;
        z_stream strm;
        strm.zalloc = Z_NULL;
        strm.zfree = Z_NULL;
        strm.opaque = Z_NULL;
        strm.avail_in = bmsg.zlib_data().size();
        strm.next_in = (unsigned char *)bmsg.zlib_data().data();
        strm.avail_out = bmsg.raw_size();
        strm.next_out = (unsigned char *)ubuf;

        ret = inflateInit(&strm);

        if (ret != Z_OK) {
            delete [] ubuf ;
            return false ;
        }

        ret = inflate(&strm, Z_NO_FLUSH);

        (void)inflateEnd(&strm);

        if (ret != Z_STREAM_END) return false ;

    }
    else return false ;

    return true ;
}

bool PBFReader::process_osm_data_nodes(Storage &doc, const PrimitiveGroup &group, const StringTable &string_table, double lat_offset, double lon_offset, double granularity)
{
    for ( unsigned node_id = 0; node_id < group.nodes_size() ; node_id++ )
    {
        const PBF::Node &node = group.nodes(node_id) ;

        Node n ;
        n.id_ = node.id() ;

        n.lat_ = lat_offset + (node.lat() * granularity);
        n.lon_ = lon_offset + (node.lon() * granularity);

        for ( unsigned key_id = 0; key_id < node.keys_size() ; key_id++ )
        {
            uint32_t key_idx = node.keys(key_id) ;
            uint32_t val_idx = node.vals(key_id) ;

            string key = string_table.s(key_idx) ;
            string val = string_table.s(val_idx) ;

            n.tags_.add(key, val) ;
        }

        doc.writeNode(n) ;
    }

    return true ;

}

bool PBFReader::process_osm_data_dense_nodes(Storage &doc, const PrimitiveGroup &group, const StringTable &string_table, double lat_offset, double lon_offset, double granularity)
{
    if ( !group.has_dense() ) return true ;

    unsigned l = 0;
    int64_t deltaid = 0;
    long int deltalat = 0;
    long int deltalon = 0;

    const DenseNodes &dense = group.dense() ;

    for ( unsigned node_id = 0; node_id < dense.id_size() ; node_id++ )
    {
        Node n ;

        deltaid += dense.id(node_id) ;
        deltalat += dense.lat(node_id);
        deltalon += dense.lon(node_id) ;

        n.id_ = deltaid ;

        if ( n.id_ < 0 ) std::cout << n.id_ << std::endl ;

        if ( l < dense.keys_vals_size() )
        {
            while (dense.keys_vals(l) != 0 && l < dense.keys_vals_size() )
            {
                uint32_t key_idx = dense.keys_vals(l) ;
                uint32_t val_idx = dense.keys_vals(l+1) ;

                string key = string_table.s(key_idx) ;
                string val = string_table.s(val_idx) ;

                n.tags_.add(key, val) ;

                l += 2;
            }
            l++ ;
        }

        n.lat_ = lat_offset + (deltalat * granularity);
        n.lon_ = lon_offset + (deltalon * granularity);

        doc.writeNode(n);

    }

    return true ;

}

bool PBFReader::process_osm_data_ways(Storage &doc, const PrimitiveGroup &group, const StringTable &string_table)
{
    for ( unsigned way_id = 0; way_id < group.ways_size() ; way_id++ )
    {
        int64_t deltaref = 0 ;

        const PBF::Way &way = group.ways(way_id) ;

        Way w ;

        w.id_ = way.id() ;

        for ( unsigned key_id = 0; key_id < way.keys_size() ; key_id++ )
        {
            uint32_t key_idx = way.keys(key_id) ;
            uint32_t val_idx = way.vals(key_id) ;

            string key = string_table.s(key_idx) ;
            string val = string_table.s(val_idx) ;

            w.tags_.add(key, val) ;
        }

        for ( unsigned ref_id = 0; ref_id < way.refs_size() ; ref_id++ )
        {
            int64_t delta = way.refs(ref_id) ;
            deltaref += delta ;
            w.nodes_.push_back(deltaref) ;
        }

        doc.writeWay(w) ;
    }

    return true ;

}

bool PBFReader::process_osm_data_relations(Storage &doc, const PrimitiveGroup &group, const StringTable &string_table)
{
    for ( unsigned rel_id = 0; rel_id < group.relations_size() ; rel_id++ )
    {
        const PBF::Relation &relation = group.relations(rel_id) ;

        Relation r ;

        r.id_ = relation.id() ;

        for ( unsigned key_id = 0; key_id < relation.keys_size() ; key_id++ )
        {
            uint32_t key_idx = relation.keys(key_id) ;
            uint32_t val_idx = relation.vals(key_id) ;

            string key = string_table.s(key_idx) ;
            string val = string_table.s(val_idx) ;

            r.tags_.add(key, val) ;
        }

        int64_t deltaref = 0 ;

        for( unsigned member_id = 0 ; member_id < relation.memids_size() ; member_id++ )
        {
            deltaref += relation.memids(member_id) ;

            int64_t role_id = relation.roles_sid(member_id) ;
            string role = string_table.s(role_id) ;

            switch (relation.types(member_id) ) {
            case PBF::Relation::NODE:
                r.nodes_.push_back(deltaref) ;
                r.nodes_role_.push_back(role) ;
                break ;
            case PBF::Relation::WAY:
                r.ways_.push_back(deltaref) ;
                r.ways_role_.push_back(role) ;
                break ;
            case PBF::Relation::RELATION:
                r.children_.push_back(deltaref) ;
                r.children_role_.push_back(role) ;
                break ;
            }
        }

        doc.writeRelation(r);

    }

    return true ;

}

bool PBFReader::read(istream &input, Storage &doc)
{
    BlockHeader header_msg;
    Blob blob_msg ;

    if ( !input ) return false ;

    doc.writeBegin() ;

    while ( input.good() )
    {
        // reader header and blob data

        if ( !read_header(header_msg, input) ) break ;

        if ( !read_blob(blob_msg, input, header_msg.datasize()) )
            return false ;

        // uncompress data

        size_t bsize = blob_msg.raw_size() ;

        std::unique_ptr<char []> bbuf(new char [bsize]) ;

        if ( !bbuf || !uncompress_blob(blob_msg, bbuf.get()) ) return false ;

        // process data

        if ( header_msg.type() == "OSMHeader" )
        {
            // Ignore header contents for now

            HeaderBlock hb_msg ;

            if ( !hb_msg.ParseFromArray(bbuf.get(), bsize) ) return false ;

        }
        else if ( header_msg.type() == "OSMData" )
        {
            PrimitiveBlock pb_msg ;

            if ( !pb_msg.ParseFromArray(bbuf.get(), bsize) ) return false ;

            double lat_offset = NANO_DEGREE * pb_msg.lat_offset();
            double lon_offset = NANO_DEGREE * pb_msg.lon_offset();
            double granularity = NANO_DEGREE * pb_msg.granularity();

            for ( int j = 0; j < pb_msg.primitivegroup_size(); j++ )
            {
                const PrimitiveGroup &group = pb_msg.primitivegroup(j) ;
                const StringTable &string_table = pb_msg.stringtable() ;

                if ( !process_osm_data_nodes(doc, group, string_table, lat_offset, lon_offset, granularity) ) return false ;
                if ( !process_osm_data_dense_nodes(doc, group, string_table, lat_offset, lon_offset, granularity) ) return false ;
                if ( !process_osm_data_ways(doc, group, string_table) ) return false ;
                if ( !process_osm_data_relations(doc, group, string_table) ) return false ;
            }
        }

    }

    doc.writeEnd() ;

    return true ;

}

}
<commit_msg>minor fix<commit_after>#include "osm_pbf_reader.hpp"

#include <iostream>

#include <fstream>
#ifndef _WIN32
#include <arpa/inet.h>
#endif
#include <zlib.h>

using namespace std ;

#define MAX_BLOCK_HEADER_SIZE 64*1024
#define MAX_BLOB_SIZE 32*1024*1024
#define NANO_DEGREE .000000001

namespace OSM {

using PBF::BlockHeader ;
using PBF::Blob ;
using PBF::PrimitiveGroup ;
using PBF::StringTable ;
using PBF::HeaderBlock;
using PBF::PrimitiveBlock ;
using PBF::DenseNodes ;

static uint32_t get_length(istream &input)
{
    char buf[4];

    if ( !input.read(buf, sizeof(buf) ) ) return 0;

    return ntohl(*((size_t *)buf));
}

static bool read_header(BlockHeader &header_msg, istream &input)
{
    size_t length = get_length(input);

    if ( length == 0 ) return false ;

    std::unique_ptr<char []> buf(new char [length]) ;

    if ( !buf || !input.read(buf.get(), length) ) return false ;

    return header_msg.ParseFromArray(buf.get(), length) ;
}

static bool read_blob(Blob &blob_msg, istream &input, int32_t length)
{
    std::unique_ptr<char []> buf(new char [length]) ;

    if ( !buf || !input.read(buf.get(), length) ) return false ;

    return blob_msg.ParseFromArray(buf.get(), length) ;
}

static bool uncompress_blob(PBF::Blob &bmsg, char *ubuf)
{
    if ( bmsg.has_raw() ) {
        memcpy(ubuf, bmsg.raw().data(), bmsg.raw().size());
    }
    else if ( bmsg.has_zlib_data() ) {

        int ret;
        z_stream strm;
        strm.zalloc = Z_NULL;
        strm.zfree = Z_NULL;
        strm.opaque = Z_NULL;
        strm.avail_in = bmsg.zlib_data().size();
        strm.next_in = (unsigned char *)bmsg.zlib_data().data();
        strm.avail_out = bmsg.raw_size();
        strm.next_out = (unsigned char *)ubuf;

        ret = inflateInit(&strm);

        if (ret != Z_OK) {
            delete [] ubuf ;
            return false ;
        }

        ret = inflate(&strm, Z_NO_FLUSH);

        (void)inflateEnd(&strm);

        if (ret != Z_STREAM_END) return false ;

    }
    else return false ;

    return true ;
}

bool PBFReader::process_osm_data_nodes(Storage &doc, const PrimitiveGroup &group, const StringTable &string_table, double lat_offset, double lon_offset, double granularity)
{
    for ( unsigned node_id = 0; node_id < group.nodes_size() ; node_id++ )
    {
        const PBF::Node &node = group.nodes(node_id) ;

        Node n ;
        n.id_ = node.id() ;

        n.lat_ = lat_offset + (node.lat() * granularity);
        n.lon_ = lon_offset + (node.lon() * granularity);

        for ( unsigned key_id = 0; key_id < node.keys_size() ; key_id++ )
        {
            uint32_t key_idx = node.keys(key_id) ;
            uint32_t val_idx = node.vals(key_id) ;

            string key = string_table.s(key_idx) ;
            string val = string_table.s(val_idx) ;

            n.tags_.add(key, val) ;
        }

        doc.writeNode(n) ;
    }

    return true ;

}

bool PBFReader::process_osm_data_dense_nodes(Storage &doc, const PrimitiveGroup &group, const StringTable &string_table, double lat_offset, double lon_offset, double granularity)
{
    if ( !group.has_dense() ) return true ;

    unsigned l = 0;
    int64_t deltaid = 0;
    long int deltalat = 0;
    long int deltalon = 0;

    const DenseNodes &dense = group.dense() ;

    for ( unsigned node_id = 0; node_id < dense.id_size() ; node_id++ )
    {
        Node n ;

        deltaid += dense.id(node_id) ;
        deltalat += dense.lat(node_id);
        deltalon += dense.lon(node_id) ;

        n.id_ = deltaid ;

      //  if ( n.id_ < 0 ) std::cout << n.id_ << std::endl ;

        if ( l < dense.keys_vals_size() )
        {
            while (dense.keys_vals(l) != 0 && l < dense.keys_vals_size() )
            {
                uint32_t key_idx = dense.keys_vals(l) ;
                uint32_t val_idx = dense.keys_vals(l+1) ;

                string key = string_table.s(key_idx) ;
                string val = string_table.s(val_idx) ;

                n.tags_.add(key, val) ;

                l += 2;
            }
            l++ ;
        }

        n.lat_ = lat_offset + (deltalat * granularity);
        n.lon_ = lon_offset + (deltalon * granularity);

        doc.writeNode(n);

    }

    return true ;

}

bool PBFReader::process_osm_data_ways(Storage &doc, const PrimitiveGroup &group, const StringTable &string_table)
{
    for ( unsigned way_id = 0; way_id < group.ways_size() ; way_id++ )
    {
        int64_t deltaref = 0 ;

        const PBF::Way &way = group.ways(way_id) ;

        Way w ;

        w.id_ = way.id() ;

        for ( unsigned key_id = 0; key_id < way.keys_size() ; key_id++ )
        {
            uint32_t key_idx = way.keys(key_id) ;
            uint32_t val_idx = way.vals(key_id) ;

            string key = string_table.s(key_idx) ;
            string val = string_table.s(val_idx) ;

            w.tags_.add(key, val) ;
        }

        for ( unsigned ref_id = 0; ref_id < way.refs_size() ; ref_id++ )
        {
            int64_t delta = way.refs(ref_id) ;
            deltaref += delta ;
            w.nodes_.push_back(deltaref) ;
        }

        doc.writeWay(w) ;
    }

    return true ;

}

bool PBFReader::process_osm_data_relations(Storage &doc, const PrimitiveGroup &group, const StringTable &string_table)
{
    for ( unsigned rel_id = 0; rel_id < group.relations_size() ; rel_id++ )
    {
        const PBF::Relation &relation = group.relations(rel_id) ;

        Relation r ;

        r.id_ = relation.id() ;

        for ( unsigned key_id = 0; key_id < relation.keys_size() ; key_id++ )
        {
            uint32_t key_idx = relation.keys(key_id) ;
            uint32_t val_idx = relation.vals(key_id) ;

            string key = string_table.s(key_idx) ;
            string val = string_table.s(val_idx) ;

            r.tags_.add(key, val) ;
        }

        int64_t deltaref = 0 ;

        for( unsigned member_id = 0 ; member_id < relation.memids_size() ; member_id++ )
        {
            deltaref += relation.memids(member_id) ;

            int64_t role_id = relation.roles_sid(member_id) ;
            string role = string_table.s(role_id) ;

            switch (relation.types(member_id) ) {
            case PBF::Relation::NODE:
                r.nodes_.push_back(deltaref) ;
                r.nodes_role_.push_back(role) ;
                break ;
            case PBF::Relation::WAY:
                r.ways_.push_back(deltaref) ;
                r.ways_role_.push_back(role) ;
                break ;
            case PBF::Relation::RELATION:
                r.children_.push_back(deltaref) ;
                r.children_role_.push_back(role) ;
                break ;
            }
        }

        doc.writeRelation(r);

    }

    return true ;

}

bool PBFReader::read(istream &input, Storage &doc)
{
    BlockHeader header_msg;
    Blob blob_msg ;

    if ( !input ) return false ;

    doc.writeBegin() ;

    while ( input.good() )
    {
        // reader header and blob data

        if ( !read_header(header_msg, input) ) break ;

        if ( !read_blob(blob_msg, input, header_msg.datasize()) )
            return false ;

        // uncompress data

        size_t bsize = blob_msg.raw_size() ;

        std::unique_ptr<char []> bbuf(new char [bsize]) ;

        if ( !bbuf || !uncompress_blob(blob_msg, bbuf.get()) ) return false ;

        // process data

        if ( header_msg.type() == "OSMHeader" )
        {
            // Ignore header contents for now

            HeaderBlock hb_msg ;

            if ( !hb_msg.ParseFromArray(bbuf.get(), bsize) ) return false ;

        }
        else if ( header_msg.type() == "OSMData" )
        {
            PrimitiveBlock pb_msg ;

            if ( !pb_msg.ParseFromArray(bbuf.get(), bsize) ) return false ;

            double lat_offset = NANO_DEGREE * pb_msg.lat_offset();
            double lon_offset = NANO_DEGREE * pb_msg.lon_offset();
            double granularity = NANO_DEGREE * pb_msg.granularity();

            for ( int j = 0; j < pb_msg.primitivegroup_size(); j++ )
            {
                const PrimitiveGroup &group = pb_msg.primitivegroup(j) ;
                const StringTable &string_table = pb_msg.stringtable() ;

                if ( !process_osm_data_nodes(doc, group, string_table, lat_offset, lon_offset, granularity) ) return false ;
                if ( !process_osm_data_dense_nodes(doc, group, string_table, lat_offset, lon_offset, granularity) ) return false ;
                if ( !process_osm_data_ways(doc, group, string_table) ) return false ;
                if ( !process_osm_data_relations(doc, group, string_table) ) return false ;
            }
        }

    }

    doc.writeEnd() ;

    return true ;

}

}
<|endoftext|>


<commit_before>//=============================================================================================================
/**
 * @file     test_sensorSet.cpp
 * @author   Ruben Dörfel <doerfelruben@aol.com>
 * @since    0.1.0
 * @date     November, 2021
 *
 * @section  LICENSE
 *
 * Copyright (C) 2021, Ruben Dörfel. 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 MNE-CPP authors 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.
 *
 *
 * @brief     Test for the sensor set class.
 *
 */

//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include <utils/generics/applicationlogger.h>
#include <inverse/hpiFit/sensorset.h>
#include <fiff/fiff_raw_data.h>

//=============================================================================================================
// QT INCLUDES
//=============================================================================================================

#include <QtCore/QCoreApplication>
#include <QtTest>

//=============================================================================================================
// Eigen
//=============================================================================================================

#include <Eigen/Dense>

//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace FIFFLIB;
using namespace UTILSLIB;
using namespace INVERSELIB;
using namespace Eigen;

//=============================================================================================================
/**
 * DECLARE CLASS TestSensorSet
 *
 * @brief The TestSensorSet class provides tests for SensorSet
 *
 */
class TestSensorSet: public QObject
{
    Q_OBJECT

public:
    TestSensorSet();

private slots:
    void initTestCase();
    void testConstructor();
    void testChannelList_acc1();
    void testChannelList_acc2();
    void cleanupTestCase();

private:
    // declare your thresholds, variables and error values here
    QList<FIFFLIB::FiffChInfo> lChannels;

};

//=============================================================================================================

TestSensorSet::TestSensorSet()
{
}

//=============================================================================================================

void TestSensorSet::initTestCase()
{
    qInstallMessageHandler(ApplicationLogger::customLogWriter);

    QFile t_fileIn(QCoreApplication::applicationDirPath() + "/mne-cpp-test-data/MEG/sample/test_hpiFit_raw.fif");

    // Setup for reading the raw data
    FiffRawData raw = FiffRawData(t_fileIn);
    FiffInfo::SPtr pFiffInfo =  FiffInfo::SPtr(new FiffInfo(raw.info));

    // create meg channel list
    int iNumCh = pFiffInfo->nchan;
    for (int i = 0; i < iNumCh; ++i) {
        if(pFiffInfo->chs[i].chpos.coil_type == FIFFV_COIL_BABY_MAG ||
            pFiffInfo->chs[i].chpos.coil_type == FIFFV_COIL_VV_PLANAR_T1 ||
            pFiffInfo->chs[i].chpos.coil_type == FIFFV_COIL_VV_PLANAR_T2 ||
            pFiffInfo->chs[i].chpos.coil_type == FIFFV_COIL_VV_PLANAR_T3) {
            // Check if the sensor is bad, if not append to innerind
            if(!(pFiffInfo->bads.contains(pFiffInfo->ch_names.at(i)))) {
                lChannels.append(pFiffInfo->chs[i]);
            }
        }
    }
}

//=============================================================================================================

void TestSensorSet::testConstructor()
{
    int iNChan = 0;
    int iNp = 0;
    int iNRmag = 0;
    int iNCosmag = 0;
    int iNTra = 0;
    int iNW = 0;

    /// act
    SensorSet sensorsActual = SensorSet();

    /// assert
    QVERIFY2(iNp == sensorsActual.np,"Number of integration points does not match.");
    QVERIFY2(iNChan == sensorsActual.ncoils,"Number of channels does not match.");
    QVERIFY2(iNRmag == sensorsActual.rmag.rows(),"Number of points for computation does not match.");
    QVERIFY2(iNCosmag == sensorsActual.cosmag.rows(),"Number of points for computation does not match.");
    QVERIFY2(iNTra == sensorsActual.tra.size(),"Size of square matrix does not match.");
    QVERIFY2(iNW == sensorsActual.w.size(),"Number of iweights does not match");
}

//=============================================================================================================

void TestSensorSet::testChannelList_acc1()
{
    // create vector with expected sizes of sensor struct data
    int iNChan = 204;               // number of channels (204 gradiometers)
    int iNp = 8;                    // 8 integration points for acc 2
    int iNRmag = iNp * iNChan;      // expected number of points for computation, 8 for each sensor -> 8*204
    int iNCosmag = iNp * iNChan;    // same as rmag
    int iNTra = iNChan*iNChan;      // size square matrix 204*204
    int iNW = iNp * iNChan;         // one weight for each point

    /// act
    int iAccuracy = 1;
    SensorSet sensorsActual = SensorSet();
    sensorsActual.updateSensorSet(lChannels,iAccuracy);

    /// assert
    QVERIFY2(iNp == sensorsActual.np,"Number of integration points does not match.");
    QVERIFY2(iNChan == sensorsActual.ncoils,"Number of channels does not match.");
    QVERIFY2(iNRmag == sensorsActual.rmag.rows(),"Number of points for computation does not match.");
    QVERIFY2(iNCosmag == sensorsActual.cosmag.rows(),"Number of points for computation does not match.");
    QVERIFY2(iNTra == sensorsActual.tra.size(),"Size of square matrix does not match.");
    QVERIFY2(iNW == sensorsActual.w.size(),"Number of iweights does not match");
}

//=============================================================================================================

void TestSensorSet::testChannelList_acc2()
{
    // create vector with expected sizes of sensor struct data
    int iNChan = 204;               // number of channels (204 gradiometers)
    int iNp = 8;                    // 8 integration points for acc 2
    int iNRmag = iNp * iNChan;      // expected number of points for computation, 8 for each sensor -> 8*204
    int iNCosmag = iNp * iNChan;    // same as rmag
    int iNTra = iNChan*iNChan;      // size square matrix 204*204
    int iNW = iNp * iNChan;         // one weight for each point

    /// act
    int iAccuracy = 2;
    SensorSet sensorsActual = SensorSet();
    sensorsActual.updateSensorSet(lChannels,iAccuracy);

    /// assert
    QVERIFY2(iNp == sensorsActual.np,"Number of integration points does not match.");
    QVERIFY2(iNChan == sensorsActual.ncoils,"Number of channels does not match.");
    QVERIFY2(iNRmag == sensorsActual.rmag.rows(),"Number of points for computation does not match.");
    QVERIFY2(iNCosmag == sensorsActual.cosmag.rows(),"Number of points for computation does not match.");
    QVERIFY2(iNTra == sensorsActual.tra.size(),"Size of square matrix does not match.");
    QVERIFY2(iNW == sensorsActual.w.size(),"Number of iweights does not match");
}

//=============================================================================================================

void TestSensorSet::cleanupTestCase()
{
}

//=============================================================================================================
// MAIN
//=============================================================================================================

QTEST_GUILESS_MAIN(TestSensorSet)
#include "test_sensorSet.moc"

<commit_msg>Maint: workin test<commit_after>//=============================================================================================================
/**
 * @file     test_sensorSet.cpp
 * @author   Ruben Dörfel <doerfelruben@aol.com>
 * @since    0.1.0
 * @date     November, 2021
 *
 * @section  LICENSE
 *
 * Copyright (C) 2021, Ruben Dörfel. 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 MNE-CPP authors 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.
 *
 *
 * @brief     Test for the sensor set class.
 *
 */

//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include <utils/generics/applicationlogger.h>
#include <inverse/hpiFit/sensorset.h>
#include <fiff/fiff_raw_data.h>

//=============================================================================================================
// QT INCLUDES
//=============================================================================================================

#include <QtCore/QCoreApplication>
#include <QtTest>

//=============================================================================================================
// Eigen
//=============================================================================================================

#include <Eigen/Dense>

//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace FIFFLIB;
using namespace UTILSLIB;
using namespace INVERSELIB;
using namespace Eigen;

//=============================================================================================================
/**
 * DECLARE CLASS TestSensorSet
 *
 * @brief The TestSensorSet class provides tests for SensorSet
 *
 */
class TestSensorSet: public QObject
{
    Q_OBJECT

public:
    TestSensorSet();

private slots:
    void initTestCase();
    void testConstructor();
    void testChannelList_acc1();
    void testChannelList_acc2();
    void cleanupTestCase();

private:
    // declare your thresholds, variables and error values here
    QList<FIFFLIB::FiffChInfo> lChannels;

};

//=============================================================================================================

TestSensorSet::TestSensorSet()
{
}

//=============================================================================================================

void TestSensorSet::initTestCase()
{
    qInstallMessageHandler(ApplicationLogger::customLogWriter);

    QFile t_fileIn(QCoreApplication::applicationDirPath() + "/mne-cpp-test-data/MEG/sample/test_hpiFit_raw.fif");

    // Setup for reading the raw data
    FiffRawData raw = FiffRawData(t_fileIn);
    FiffInfo::SPtr pFiffInfo =  FiffInfo::SPtr(new FiffInfo(raw.info));

    // create meg channel list
    int iNumCh = pFiffInfo->nchan;
    for (int i = 0; i < iNumCh; ++i) {
        if(pFiffInfo->chs[i].chpos.coil_type == FIFFV_COIL_BABY_MAG ||
            pFiffInfo->chs[i].chpos.coil_type == FIFFV_COIL_VV_PLANAR_T1 ||
            pFiffInfo->chs[i].chpos.coil_type == FIFFV_COIL_VV_PLANAR_T2 ||
            pFiffInfo->chs[i].chpos.coil_type == FIFFV_COIL_VV_PLANAR_T3) {
            // Check if the sensor is bad, if not append to innerind
            if(!(pFiffInfo->bads.contains(pFiffInfo->ch_names.at(i)))) {
                lChannels.append(pFiffInfo->chs[i]);
            }
        }
    }
}

//=============================================================================================================

void TestSensorSet::testConstructor()
{
    int iNChan = 0;
    int iNp = 0;
    int iNRmag = 0;
    int iNCosmag = 0;
    int iNTra = 0;
    int iNW = 0;

    /// act
    SensorSet sensorsActual = SensorSet();

    /// assert
    QVERIFY2(iNp == sensorsActual.np,"Number of integration points does not match.");
    QVERIFY2(iNChan == sensorsActual.ncoils,"Number of channels does not match.");
    QVERIFY2(iNRmag == sensorsActual.rmag.rows(),"Number of points for computation does not match.");
    QVERIFY2(iNCosmag == sensorsActual.cosmag.rows(),"Number of points for computation does not match.");
    QVERIFY2(iNTra == sensorsActual.tra.size(),"Size of square matrix does not match.");
    QVERIFY2(iNW == sensorsActual.w.size(),"Number of iweights does not match");
}

//=============================================================================================================

void TestSensorSet::testChannelList_acc1()
{
    // create vector with expected sizes of sensor struct data
    int iNChan = 204;               // number of channels (204 gradiometers)
    int iNp = 4;                    // 8 integration points for acc 2
    int iNRmag = iNp * iNChan;      // expected number of points for computation, 8 for each sensor -> 8*204
    int iNCosmag = iNp * iNChan;    // same as rmag
    int iNTra = iNChan*iNChan;      // size square matrix 204*204
    int iNW = iNp * iNChan;         // one weight for each point

    /// act
    int iAccuracy = 1;
    SensorSet sensorsActual = SensorSet();
    sensorsActual.updateSensorSet(lChannels,iAccuracy);

    /// assert
    QVERIFY2(iNp == sensorsActual.np,"Number of integration points does not match.");
    QVERIFY2(iNChan == sensorsActual.ncoils,"Number of channels does not match.");
    QVERIFY2(iNRmag == sensorsActual.rmag.rows(),"Number of points for computation does not match.");
    QVERIFY2(iNCosmag == sensorsActual.cosmag.rows(),"Number of points for computation does not match.");
    QVERIFY2(iNTra == sensorsActual.tra.size(),"Size of square matrix does not match.");
    QVERIFY2(iNW == sensorsActual.w.size(),"Number of iweights does not match");
}

//=============================================================================================================

void TestSensorSet::testChannelList_acc2()
{
    // create vector with expected sizes of sensor struct data
    int iNChan = 204;               // number of channels (204 gradiometers)
    int iNp = 8;                    // 8 integration points for acc 2
    int iNRmag = iNp * iNChan;      // expected number of points for computation, 8 for each sensor -> 8*204
    int iNCosmag = iNp * iNChan;    // same as rmag
    int iNTra = iNChan*iNChan;      // size square matrix 204*204
    int iNW = iNp * iNChan;         // one weight for each point

    /// act
    int iAccuracy = 2;
    SensorSet sensorsActual = SensorSet();
    sensorsActual.updateSensorSet(lChannels,iAccuracy);

    /// assert
    QVERIFY2(iNp == sensorsActual.np,"Number of integration points does not match.");
    QVERIFY2(iNChan == sensorsActual.ncoils,"Number of channels does not match.");
    QVERIFY2(iNRmag == sensorsActual.rmag.rows(),"Number of points for computation does not match.");
    QVERIFY2(iNCosmag == sensorsActual.cosmag.rows(),"Number of points for computation does not match.");
    QVERIFY2(iNTra == sensorsActual.tra.size(),"Size of square matrix does not match.");
    QVERIFY2(iNW == sensorsActual.w.size(),"Number of iweights does not match");
}

//=============================================================================================================

void TestSensorSet::cleanupTestCase()
{
}

//=============================================================================================================
// MAIN
//=============================================================================================================

QTEST_GUILESS_MAIN(TestSensorSet)
#include "test_sensorSet.moc"

<|endoftext|>


<commit_before>/*
 *
 * Copyright 2015 gRPC authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include <grpc/support/port_platform.h>

#include "src/core/lib/iomgr/exec_ctx.h"

#include <grpc/support/log.h>
#include <grpc/support/sync.h>

#include "src/core/lib/gprpp/thd.h"
#include "src/core/lib/iomgr/combiner.h"
#include "src/core/lib/profiling/timers.h"

static void exec_ctx_run(grpc_closure* closure, grpc_error* error) {
#ifndef NDEBUG
  closure->scheduled = false;
  if (grpc_trace_closure.enabled()) {
    gpr_log(GPR_DEBUG, "running closure %p: created [%s:%d]: %s [%s:%d]",
            closure, closure->file_created, closure->line_created,
            closure->run ? "run" : "scheduled", closure->file_initiated,
            closure->line_initiated);
  }
#endif
  closure->cb(closure->cb_arg, error);
#ifndef NDEBUG
  if (grpc_trace_closure.enabled()) {
    gpr_log(GPR_DEBUG, "closure %p finished", closure);
  }
#endif
  GRPC_ERROR_UNREF(error);
}

static void exec_ctx_sched(grpc_closure* closure, grpc_error* error) {
  grpc_closure_list_append(grpc_core::ExecCtx::Get()->closure_list(), closure,
                           error);
}

static gpr_timespec g_start_time;
static gpr_cycle_counter g_start_cycle;

static grpc_millis timespec_to_millis_round_down(gpr_timespec ts) {
  ts = gpr_time_sub(ts, g_start_time);
  double x = GPR_MS_PER_SEC * static_cast<double>(ts.tv_sec) +
             static_cast<double>(ts.tv_nsec) / GPR_NS_PER_MS;
  if (x < 0) return 0;
  if (x > GRPC_MILLIS_INF_FUTURE) return GRPC_MILLIS_INF_FUTURE;
  return static_cast<grpc_millis>(x);
}

static grpc_millis timespec_to_millis_round_up(gpr_timespec ts) {
  ts = gpr_time_sub(ts, g_start_time);
  double x = GPR_MS_PER_SEC * static_cast<double>(ts.tv_sec) +
             static_cast<double>(ts.tv_nsec) / GPR_NS_PER_MS +
             static_cast<double>(GPR_NS_PER_SEC - 1) /
                 static_cast<double>(GPR_NS_PER_SEC);
  if (x < 0) return 0;
  if (x > GRPC_MILLIS_INF_FUTURE) return GRPC_MILLIS_INF_FUTURE;
  return static_cast<grpc_millis>(x);
}

gpr_timespec grpc_millis_to_timespec(grpc_millis millis,
                                     gpr_clock_type clock_type) {
  // special-case infinities as grpc_millis can be 32bit on some platforms
  // while gpr_time_from_millis always takes an int64_t.
  if (millis == GRPC_MILLIS_INF_FUTURE) {
    return gpr_inf_future(clock_type);
  }
  if (millis == GRPC_MILLIS_INF_PAST) {
    return gpr_inf_past(clock_type);
  }

  if (clock_type == GPR_TIMESPAN) {
    return gpr_time_from_millis(millis, GPR_TIMESPAN);
  }
  return gpr_time_add(gpr_convert_clock_type(g_start_time, clock_type),
                      gpr_time_from_millis(millis, GPR_TIMESPAN));
}

grpc_millis grpc_timespec_to_millis_round_down(gpr_timespec ts) {
  return timespec_to_millis_round_down(
      gpr_convert_clock_type(ts, g_start_time.clock_type));
}

grpc_millis grpc_timespec_to_millis_round_up(gpr_timespec ts) {
  return timespec_to_millis_round_up(
      gpr_convert_clock_type(ts, g_start_time.clock_type));
}

grpc_millis grpc_cycle_counter_to_millis_round_down(gpr_cycle_counter cycles) {
  return timespec_to_millis_round_down(
      gpr_time_add(g_start_time, gpr_cycle_counter_sub(cycles, g_start_cycle)));
}

grpc_millis grpc_cycle_counter_to_millis_round_up(gpr_cycle_counter cycles) {
  return timespec_to_millis_round_up(
      gpr_time_add(g_start_time, gpr_cycle_counter_sub(cycles, g_start_cycle)));
}

static const grpc_closure_scheduler_vtable exec_ctx_scheduler_vtable = {
    exec_ctx_run, exec_ctx_sched, "exec_ctx"};
static grpc_closure_scheduler exec_ctx_scheduler = {&exec_ctx_scheduler_vtable};
grpc_closure_scheduler* grpc_schedule_on_exec_ctx = &exec_ctx_scheduler;

namespace grpc_core {
GPR_TLS_CLASS_DEF(ExecCtx::exec_ctx_);
GPR_TLS_CLASS_DEF(ApplicationCallbackExecCtx::callback_exec_ctx_);

// WARNING: for testing purposes only!
void ExecCtx::TestOnlyGlobalInit(gpr_timespec new_val) {
  g_start_time = new_val;
  gpr_tls_init(&exec_ctx_);
}

void ExecCtx::GlobalInit(void) {
  // gpr_now(GPR_CLOCK_MONOTONIC) incurs a syscall. We don't actually know the
  // exact cycle the time was captured, so we use the average of cycles before
  // and after the syscall as the starting cycle.
  const gpr_cycle_counter cycle_before = gpr_get_cycle_counter();
  g_start_time = gpr_now(GPR_CLOCK_MONOTONIC);
  const gpr_cycle_counter cycle_after = gpr_get_cycle_counter();
  g_start_cycle = (cycle_before + cycle_after) / 2;
  gpr_tls_init(&exec_ctx_);
}

bool ExecCtx::Flush() {
  bool did_something = 0;
  GPR_TIMER_SCOPE("grpc_exec_ctx_flush", 0);
  for (;;) {
    if (!grpc_closure_list_empty(closure_list_)) {
      grpc_closure* c = closure_list_.head;
      closure_list_.head = closure_list_.tail = nullptr;
      while (c != nullptr) {
        grpc_closure* next = c->next_data.next;
        grpc_error* error = c->error_data.error;
        did_something = true;
        exec_ctx_run(c, error);
        c = next;
      }
    } else if (!grpc_combiner_continue_exec_ctx()) {
      break;
    }
  }
  GPR_ASSERT(combiner_data_.active_combiner == nullptr);
  return did_something;
}

grpc_millis ExecCtx::Now() {
  if (!now_is_valid_) {
    now_ = timespec_to_millis_round_down(gpr_now(GPR_CLOCK_MONOTONIC));
    now_is_valid_ = true;
  }
  return now_;
}

}  // namespace grpc_core
<commit_msg>Optimize cycle to millis conversion by bypassing sub+add.<commit_after>/*
 *
 * Copyright 2015 gRPC authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include <grpc/support/port_platform.h>

#include "src/core/lib/iomgr/exec_ctx.h"

#include <grpc/support/log.h>
#include <grpc/support/sync.h>

#include "src/core/lib/gprpp/thd.h"
#include "src/core/lib/iomgr/combiner.h"
#include "src/core/lib/profiling/timers.h"

static void exec_ctx_run(grpc_closure* closure, grpc_error* error) {
#ifndef NDEBUG
  closure->scheduled = false;
  if (grpc_trace_closure.enabled()) {
    gpr_log(GPR_DEBUG, "running closure %p: created [%s:%d]: %s [%s:%d]",
            closure, closure->file_created, closure->line_created,
            closure->run ? "run" : "scheduled", closure->file_initiated,
            closure->line_initiated);
  }
#endif
  closure->cb(closure->cb_arg, error);
#ifndef NDEBUG
  if (grpc_trace_closure.enabled()) {
    gpr_log(GPR_DEBUG, "closure %p finished", closure);
  }
#endif
  GRPC_ERROR_UNREF(error);
}

static void exec_ctx_sched(grpc_closure* closure, grpc_error* error) {
  grpc_closure_list_append(grpc_core::ExecCtx::Get()->closure_list(), closure,
                           error);
}

static gpr_timespec g_start_time;
static gpr_cycle_counter g_start_cycle;

static grpc_millis timespan_to_millis_round_down(gpr_timespec ts) {
  double x = GPR_MS_PER_SEC * static_cast<double>(ts.tv_sec) +
             static_cast<double>(ts.tv_nsec) / GPR_NS_PER_MS;
  if (x < 0) return 0;
  if (x > GRPC_MILLIS_INF_FUTURE) return GRPC_MILLIS_INF_FUTURE;
  return static_cast<grpc_millis>(x);
}

static grpc_millis timespec_to_millis_round_down(gpr_timespec ts) {
  return timespan_to_millis_round_down(gpr_time_sub(ts, g_start_time));
}

static grpc_millis timespan_to_millis_round_up(gpr_timespec ts) {
  double x = GPR_MS_PER_SEC * static_cast<double>(ts.tv_sec) +
             static_cast<double>(ts.tv_nsec) / GPR_NS_PER_MS +
             static_cast<double>(GPR_NS_PER_SEC - 1) /
                 static_cast<double>(GPR_NS_PER_SEC);
  if (x < 0) return 0;
  if (x > GRPC_MILLIS_INF_FUTURE) return GRPC_MILLIS_INF_FUTURE;
  return static_cast<grpc_millis>(x);
}

static grpc_millis timespec_to_millis_round_up(gpr_timespec ts) {
  return timespan_to_millis_round_up(gpr_time_sub(ts, g_start_time));
}

gpr_timespec grpc_millis_to_timespec(grpc_millis millis,
                                     gpr_clock_type clock_type) {
  // special-case infinities as grpc_millis can be 32bit on some platforms
  // while gpr_time_from_millis always takes an int64_t.
  if (millis == GRPC_MILLIS_INF_FUTURE) {
    return gpr_inf_future(clock_type);
  }
  if (millis == GRPC_MILLIS_INF_PAST) {
    return gpr_inf_past(clock_type);
  }

  if (clock_type == GPR_TIMESPAN) {
    return gpr_time_from_millis(millis, GPR_TIMESPAN);
  }
  return gpr_time_add(gpr_convert_clock_type(g_start_time, clock_type),
                      gpr_time_from_millis(millis, GPR_TIMESPAN));
}

grpc_millis grpc_timespec_to_millis_round_down(gpr_timespec ts) {
  return timespec_to_millis_round_down(
      gpr_convert_clock_type(ts, g_start_time.clock_type));
}

grpc_millis grpc_timespec_to_millis_round_up(gpr_timespec ts) {
  return timespec_to_millis_round_up(
      gpr_convert_clock_type(ts, g_start_time.clock_type));
}

grpc_millis grpc_cycle_counter_to_millis_round_down(gpr_cycle_counter cycles) {
  return timespan_to_millis_round_down(
      gpr_cycle_counter_sub(cycles, g_start_cycle));
}

grpc_millis grpc_cycle_counter_to_millis_round_up(gpr_cycle_counter cycles) {
  return timespan_to_millis_round_up(
      gpr_cycle_counter_sub(cycles, g_start_cycle));
}

static const grpc_closure_scheduler_vtable exec_ctx_scheduler_vtable = {
    exec_ctx_run, exec_ctx_sched, "exec_ctx"};
static grpc_closure_scheduler exec_ctx_scheduler = {&exec_ctx_scheduler_vtable};
grpc_closure_scheduler* grpc_schedule_on_exec_ctx = &exec_ctx_scheduler;

namespace grpc_core {
GPR_TLS_CLASS_DEF(ExecCtx::exec_ctx_);
GPR_TLS_CLASS_DEF(ApplicationCallbackExecCtx::callback_exec_ctx_);

// WARNING: for testing purposes only!
void ExecCtx::TestOnlyGlobalInit(gpr_timespec new_val) {
  g_start_time = new_val;
  gpr_tls_init(&exec_ctx_);
}

void ExecCtx::GlobalInit(void) {
  // gpr_now(GPR_CLOCK_MONOTONIC) incurs a syscall. We don't actually know the
  // exact cycle the time was captured, so we use the average of cycles before
  // and after the syscall as the starting cycle.
  const gpr_cycle_counter cycle_before = gpr_get_cycle_counter();
  g_start_time = gpr_now(GPR_CLOCK_MONOTONIC);
  const gpr_cycle_counter cycle_after = gpr_get_cycle_counter();
  g_start_cycle = (cycle_before + cycle_after) / 2;
  gpr_tls_init(&exec_ctx_);
}

bool ExecCtx::Flush() {
  bool did_something = 0;
  GPR_TIMER_SCOPE("grpc_exec_ctx_flush", 0);
  for (;;) {
    if (!grpc_closure_list_empty(closure_list_)) {
      grpc_closure* c = closure_list_.head;
      closure_list_.head = closure_list_.tail = nullptr;
      while (c != nullptr) {
        grpc_closure* next = c->next_data.next;
        grpc_error* error = c->error_data.error;
        did_something = true;
        exec_ctx_run(c, error);
        c = next;
      }
    } else if (!grpc_combiner_continue_exec_ctx()) {
      break;
    }
  }
  GPR_ASSERT(combiner_data_.active_combiner == nullptr);
  return did_something;
}

grpc_millis ExecCtx::Now() {
  if (!now_is_valid_) {
    now_ = timespec_to_millis_round_down(gpr_now(GPR_CLOCK_MONOTONIC));
    now_is_valid_ = true;
  }
  return now_;
}

}  // namespace grpc_core
<|endoftext|>


<commit_before><commit_msg>Fix build with OSL 1.9.x, automatically aligns to 16 bytes now.<commit_after><|endoftext|>


<commit_before><commit_msg>dont needlessly convert to proto after gfa export<commit_after><|endoftext|>