<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2004-2007 Torsten Rahn <tackat@kde.org>
// Copyright 2007      Inge Wallin  <ingwa@kde.org>
// Copyright 2008-2009      Patrick Spendrin <ps_ml@gmx.de>
//

// Own
#include "GeoDataPlacemark.h"

// Private
#include "GeoDataPlacemark_p.h"

#include "GeoDataMultiGeometry.h"
#include "GeoDataCoordinates.h"

// Qt
#include <QDataStream>
#include "MarbleDebug.h"
#include "GeoDataTrack.h"

namespace Marble
{
GeoDataPlacemark::GeoDataPlacemark()
    : GeoDataFeature( new GeoDataPlacemarkPrivate )
{
    p()->m_geometry->setParent( this );
}

GeoDataPlacemark::GeoDataPlacemark( const GeoDataPlacemark& other )
: GeoDataFeature( other )
{
    p()->m_geometry->setParent( this );
}

GeoDataPlacemark::GeoDataPlacemark( const QString& name )
    : GeoDataFeature( new GeoDataPlacemarkPrivate )
{
    d->m_name = name;
    p()->m_geometry->setParent( this );
}

GeoDataPlacemark::~GeoDataPlacemark()
{
}

bool GeoDataPlacemark::operator==( const GeoDataPlacemark& other ) const
{
    return p() == other.p();
}

GeoDataPlacemarkPrivate* GeoDataPlacemark::p() const
{
    return static_cast<GeoDataPlacemarkPrivate*>(d);
}

GeoDataGeometry* GeoDataPlacemark::geometry() const
{
    return p()->m_geometry;
}

const GeoDataLookAt *GeoDataPlacemark::lookAt() const
{
    return dynamic_cast<const GeoDataLookAt*>( abstractView() );
}

GeoDataLookAt *GeoDataPlacemark::lookAt()
{
    return dynamic_cast<GeoDataLookAt*>( abstractView() );
}

GeoDataCoordinates GeoDataPlacemark::coordinate( const QDateTime &dateTime, bool *iconAtCoordinates ) const
{
    bool hasIcon = false;
    GeoDataCoordinates coord;

    if( p()->m_geometry ) {
        // Beware: comparison between pointers, not strings.
        if ( p()->m_geometry->nodeType() == GeoDataTypes::GeoDataPointType ) {
            hasIcon = true;
            coord = static_cast<const GeoDataPoint *>( p()->m_geometry )->coordinates();
        } else if ( p()->m_geometry->nodeType() == GeoDataTypes::GeoDataMultiGeometryType ) {
            const GeoDataMultiGeometry *multiGeometry = static_cast<const GeoDataMultiGeometry *>( p()->m_geometry );

            QVector<GeoDataGeometry*>::ConstIterator it = multiGeometry->constBegin();
            QVector<GeoDataGeometry*>::ConstIterator end = multiGeometry->constEnd();
            for ( ; it != end; ++it ) {
                if ( (*it)->nodeType() == GeoDataTypes::GeoDataPointType ) {
                    hasIcon = true;
                    break;
                }
            }

            coord = p()->m_geometry->latLonAltBox().center();
        } else if ( p()->m_geometry->nodeType() == GeoDataTypes::GeoDataTrackType ) {
            const GeoDataTrack *track = static_cast<const GeoDataTrack *>( p()->m_geometry );
            hasIcon = track->size() != 0 && track->firstWhen() <= dateTime;
            coord = track->coordinatesAt( dateTime );
        } else {
            coord = p()->m_geometry->latLonAltBox().center();
        }
    }

    if ( iconAtCoordinates != 0 ) {
        *iconAtCoordinates = hasIcon;
    }
    return coord;
}

void GeoDataPlacemark::coordinate( qreal& lon, qreal& lat, qreal& alt ) const
{
    coordinate().geoCoordinates( lon, lat, alt );
}

void GeoDataPlacemark::setCoordinate( qreal lon, qreal lat, qreal alt, GeoDataPoint::Unit _unit)
{
    setGeometry( new GeoDataPoint(lon, lat, alt, _unit ) );
}

void GeoDataPlacemark::setCoordinate( const GeoDataCoordinates &point )
{
    setGeometry ( new GeoDataPoint( point ) );
}

void GeoDataPlacemark::setCoordinate( const GeoDataPoint &point )
{
    setGeometry ( new GeoDataPoint( point ) );
}

void GeoDataPlacemark::setGeometry( GeoDataGeometry *entry )
{
    detach();
    delete p()->m_geometry;
    p()->m_geometry = entry;
    p()->m_geometry->setParent( this );
}

qreal GeoDataPlacemark::area() const
{
    return p()->m_area;
}

void GeoDataPlacemark::setArea( qreal area )
{
    detach();
    p()->m_area = area;
}

qint64 GeoDataPlacemark::population() const
{
    return p()->m_population;
}

void GeoDataPlacemark::setPopulation( qint64 population )
{
    detach();
    p()->m_population = population;
}

const QString GeoDataPlacemark::state() const
{
    return p()->m_state;
}

void GeoDataPlacemark::setState( const QString &state )
{
    detach();
    p()->m_state = state;
}

const QString GeoDataPlacemark::countryCode() const
{
    return p()->m_countrycode;
}

void GeoDataPlacemark::setCountryCode( const QString &countrycode )
{
    detach();
    p()->m_countrycode = countrycode;
}

void GeoDataPlacemark::pack( QDataStream& stream ) const
{
    GeoDataFeature::pack( stream );

    stream << p()->m_countrycode;
    stream << p()->m_area;
    stream << p()->m_population;
    if ( p()->m_geometry )
    {
        stream << p()->m_geometry->geometryId();
        p()->m_geometry->pack( stream );
    }
    else
    {
        stream << InvalidGeometryId;
    }
}

QXmlStreamWriter& GeoDataPlacemark::pack( QXmlStreamWriter& stream ) const
{
    stream.writeStartElement( "placemark" );

    stream.writeEndElement();
    return stream;
}

QXmlStreamWriter& GeoDataPlacemark::operator <<( QXmlStreamWriter& stream ) const
{
    pack( stream );
    return stream;
}

void GeoDataPlacemark::unpack( QDataStream& stream )
{
    detach();
    GeoDataFeature::unpack( stream );

    stream >> p()->m_countrycode;
    stream >> p()->m_area;
    stream >> p()->m_population;
    int geometryId;
    stream >> geometryId;
    switch( geometryId ) {
        case InvalidGeometryId:
            break;
        case GeoDataPointId:
            {
            GeoDataPoint* point = new GeoDataPoint;
            point->unpack( stream );
            delete p()->m_geometry;
            p()->m_geometry = point;
            }
            break;
        case GeoDataLineStringId:
            {
            GeoDataLineString* lineString = new GeoDataLineString;
            lineString->unpack( stream );
            delete p()->m_geometry;
            p()->m_geometry = lineString;
            }
            break;
        case GeoDataLinearRingId:
            {
            GeoDataLinearRing* linearRing = new GeoDataLinearRing;
            linearRing->unpack( stream );
            delete p()->m_geometry;
            p()->m_geometry = linearRing;
            }
            break;
        case GeoDataPolygonId:
            {
            GeoDataPolygon* polygon = new GeoDataPolygon;
            polygon->unpack( stream );
            delete p()->m_geometry;
            p()->m_geometry = polygon;
            }
            break;
        case GeoDataMultiGeometryId:
            {
            GeoDataMultiGeometry* multiGeometry = new GeoDataMultiGeometry;
            multiGeometry->unpack( stream );
            delete p()->m_geometry;
            p()->m_geometry = multiGeometry;
            }
            break;
        case GeoDataModelId:
            break;
        default: break;
    };
}

}
<commit_msg>add fixme for potential craash<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2004-2007 Torsten Rahn <tackat@kde.org>
// Copyright 2007      Inge Wallin  <ingwa@kde.org>
// Copyright 2008-2009      Patrick Spendrin <ps_ml@gmx.de>
//

// Own
#include "GeoDataPlacemark.h"

// Private
#include "GeoDataPlacemark_p.h"

#include "GeoDataMultiGeometry.h"
#include "GeoDataCoordinates.h"

// Qt
#include <QDataStream>
#include "MarbleDebug.h"
#include "GeoDataTrack.h"

namespace Marble
{
GeoDataPlacemark::GeoDataPlacemark()
    : GeoDataFeature( new GeoDataPlacemarkPrivate )
{
    p()->m_geometry->setParent( this );
}

GeoDataPlacemark::GeoDataPlacemark( const GeoDataPlacemark& other )
: GeoDataFeature( other )
{
    // FIXME: violates invariant of this == p()->m_geometry->parent() for other (which could lead to crashes)
    p()->m_geometry->setParent( this );
}

GeoDataPlacemark::GeoDataPlacemark( const QString& name )
    : GeoDataFeature( new GeoDataPlacemarkPrivate )
{
    d->m_name = name;
    p()->m_geometry->setParent( this );
}

GeoDataPlacemark::~GeoDataPlacemark()
{
}

bool GeoDataPlacemark::operator==( const GeoDataPlacemark& other ) const
{
    return p() == other.p();
}

GeoDataPlacemarkPrivate* GeoDataPlacemark::p() const
{
    return static_cast<GeoDataPlacemarkPrivate*>(d);
}

GeoDataGeometry* GeoDataPlacemark::geometry() const
{
    return p()->m_geometry;
}

const GeoDataLookAt *GeoDataPlacemark::lookAt() const
{
    return dynamic_cast<const GeoDataLookAt*>( abstractView() );
}

GeoDataLookAt *GeoDataPlacemark::lookAt()
{
    return dynamic_cast<GeoDataLookAt*>( abstractView() );
}

GeoDataCoordinates GeoDataPlacemark::coordinate( const QDateTime &dateTime, bool *iconAtCoordinates ) const
{
    bool hasIcon = false;
    GeoDataCoordinates coord;

    if( p()->m_geometry ) {
        // Beware: comparison between pointers, not strings.
        if ( p()->m_geometry->nodeType() == GeoDataTypes::GeoDataPointType ) {
            hasIcon = true;
            coord = static_cast<const GeoDataPoint *>( p()->m_geometry )->coordinates();
        } else if ( p()->m_geometry->nodeType() == GeoDataTypes::GeoDataMultiGeometryType ) {
            const GeoDataMultiGeometry *multiGeometry = static_cast<const GeoDataMultiGeometry *>( p()->m_geometry );

            QVector<GeoDataGeometry*>::ConstIterator it = multiGeometry->constBegin();
            QVector<GeoDataGeometry*>::ConstIterator end = multiGeometry->constEnd();
            for ( ; it != end; ++it ) {
                if ( (*it)->nodeType() == GeoDataTypes::GeoDataPointType ) {
                    hasIcon = true;
                    break;
                }
            }

            coord = p()->m_geometry->latLonAltBox().center();
        } else if ( p()->m_geometry->nodeType() == GeoDataTypes::GeoDataTrackType ) {
            const GeoDataTrack *track = static_cast<const GeoDataTrack *>( p()->m_geometry );
            hasIcon = track->size() != 0 && track->firstWhen() <= dateTime;
            coord = track->coordinatesAt( dateTime );
        } else {
            coord = p()->m_geometry->latLonAltBox().center();
        }
    }

    if ( iconAtCoordinates != 0 ) {
        *iconAtCoordinates = hasIcon;
    }
    return coord;
}

void GeoDataPlacemark::coordinate( qreal& lon, qreal& lat, qreal& alt ) const
{
    coordinate().geoCoordinates( lon, lat, alt );
}

void GeoDataPlacemark::setCoordinate( qreal lon, qreal lat, qreal alt, GeoDataPoint::Unit _unit)
{
    setGeometry( new GeoDataPoint(lon, lat, alt, _unit ) );
}

void GeoDataPlacemark::setCoordinate( const GeoDataCoordinates &point )
{
    setGeometry ( new GeoDataPoint( point ) );
}

void GeoDataPlacemark::setCoordinate( const GeoDataPoint &point )
{
    setGeometry ( new GeoDataPoint( point ) );
}

void GeoDataPlacemark::setGeometry( GeoDataGeometry *entry )
{
    detach();
    delete p()->m_geometry;
    p()->m_geometry = entry;
    p()->m_geometry->setParent( this );
}

qreal GeoDataPlacemark::area() const
{
    return p()->m_area;
}

void GeoDataPlacemark::setArea( qreal area )
{
    detach();
    p()->m_area = area;
}

qint64 GeoDataPlacemark::population() const
{
    return p()->m_population;
}

void GeoDataPlacemark::setPopulation( qint64 population )
{
    detach();
    p()->m_population = population;
}

const QString GeoDataPlacemark::state() const
{
    return p()->m_state;
}

void GeoDataPlacemark::setState( const QString &state )
{
    detach();
    p()->m_state = state;
}

const QString GeoDataPlacemark::countryCode() const
{
    return p()->m_countrycode;
}

void GeoDataPlacemark::setCountryCode( const QString &countrycode )
{
    detach();
    p()->m_countrycode = countrycode;
}

void GeoDataPlacemark::pack( QDataStream& stream ) const
{
    GeoDataFeature::pack( stream );

    stream << p()->m_countrycode;
    stream << p()->m_area;
    stream << p()->m_population;
    if ( p()->m_geometry )
    {
        stream << p()->m_geometry->geometryId();
        p()->m_geometry->pack( stream );
    }
    else
    {
        stream << InvalidGeometryId;
    }
}

QXmlStreamWriter& GeoDataPlacemark::pack( QXmlStreamWriter& stream ) const
{
    stream.writeStartElement( "placemark" );

    stream.writeEndElement();
    return stream;
}

QXmlStreamWriter& GeoDataPlacemark::operator <<( QXmlStreamWriter& stream ) const
{
    pack( stream );
    return stream;
}

void GeoDataPlacemark::unpack( QDataStream& stream )
{
    detach();
    GeoDataFeature::unpack( stream );

    stream >> p()->m_countrycode;
    stream >> p()->m_area;
    stream >> p()->m_population;
    int geometryId;
    stream >> geometryId;
    switch( geometryId ) {
        case InvalidGeometryId:
            break;
        case GeoDataPointId:
            {
            GeoDataPoint* point = new GeoDataPoint;
            point->unpack( stream );
            delete p()->m_geometry;
            p()->m_geometry = point;
            }
            break;
        case GeoDataLineStringId:
            {
            GeoDataLineString* lineString = new GeoDataLineString;
            lineString->unpack( stream );
            delete p()->m_geometry;
            p()->m_geometry = lineString;
            }
            break;
        case GeoDataLinearRingId:
            {
            GeoDataLinearRing* linearRing = new GeoDataLinearRing;
            linearRing->unpack( stream );
            delete p()->m_geometry;
            p()->m_geometry = linearRing;
            }
            break;
        case GeoDataPolygonId:
            {
            GeoDataPolygon* polygon = new GeoDataPolygon;
            polygon->unpack( stream );
            delete p()->m_geometry;
            p()->m_geometry = polygon;
            }
            break;
        case GeoDataMultiGeometryId:
            {
            GeoDataMultiGeometry* multiGeometry = new GeoDataMultiGeometry;
            multiGeometry->unpack( stream );
            delete p()->m_geometry;
            p()->m_geometry = multiGeometry;
            }
            break;
        case GeoDataModelId:
            break;
        default: break;
    };
}

}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#ifndef INCLUDED_VCL_OPENGL_OPENGLCONTEXT_HXX
#define INCLUDED_VCL_OPENGL_OPENGLCONTEXT_HXX

#include <string.h>

#include <GL/glew.h>

#if defined( MACOSX )
#elif defined( IOS )
#elif defined( ANDROID )
#elif defined( UNX )
#  include <prex.h>
#  include "GL/glxew.h"
#  include <postx.h>
#elif defined( _WIN32 )
#ifndef INCLUDED_PRE_POST_WIN_H
#define INCLUDED_PRE_POST_WIN_H
#  include "prewin.h"
#  include "postwin.h"
#endif
#endif

#if defined( _WIN32 )
#include <GL/glext.h>
#include <GL/wglext.h>
#elif defined( MACOSX )
#include <OpenGL/OpenGL.h>
#ifdef __OBJC__
@class NSOpenGLView;
#else
class NSOpenGLView;
#endif
#elif defined( IOS )
#elif defined( ANDROID )
#elif defined( UNX )
#include <GL/glext.h>
#define GLX_GLXEXT_PROTOTYPES 1
#include <GL/glx.h>
#include <GL/glxext.h>
#endif

#include <vcl/vclopengl_dllapi.hxx>
#include <boost/scoped_ptr.hpp>
#include <vcl/window.hxx>
#include <tools/gen.hxx>
#include <vcl/syschild.hxx>

/// Holds the information of our new child window
struct GLWindow
{
    // Copy of gluCheckExtension(), from the Apache-licensed
    // https://code.google.com/p/glues/source/browse/trunk/glues/source/glues_registry.c
    static GLboolean checkExtension(const GLubyte* extName, const GLubyte* extString)
    {
      GLboolean flag=GL_FALSE;
      char* word;
      char* lookHere;
      char* deleteThis;

      if (extString==NULL)
      {
         return GL_FALSE;
      }

      deleteThis=lookHere=(char*)malloc(strlen((const char*)extString)+1);
      if (lookHere==NULL)
      {
         return GL_FALSE;
      }

      /* strtok() will modify string, so copy it somewhere */
      strcpy(lookHere,(const char*)extString);

      while ((word=strtok(lookHere, " "))!=NULL)
      {
         if (strcmp(word,(const char*)extName)==0)
         {
            flag=GL_TRUE;
            break;
         }
         lookHere=NULL; /* get next token */
      }
      free((void*)deleteThis);

      return flag;
    }

#if defined( _WIN32 )
    HWND                    hWnd;
    HDC                     hDC;
    HGLRC                   hRC;
#elif defined( MACOSX )
#elif defined( IOS )
#elif defined( ANDROID )
#elif defined( UNX )
    Display*            dpy;
    int                 screen;
    Window              win;
    Pixmap              pix;
#if defined( GLX_EXT_texture_from_pixmap )
    GLXFBConfig        fbc;
#endif
    XVisualInfo*       vi;
    GLXContext         ctx;
    GLXPixmap           glPix;

    bool HasGLXExtension( const char* name ) { return checkExtension( (const GLubyte*) name, (const GLubyte*) GLXExtensions ); }
    const char*             GLXExtensions;
#endif
    unsigned int            bpp;
    unsigned int            Width;
    unsigned int            Height;
    const GLubyte*          GLExtensions;
    bool bMultiSampleSupported;

    GLWindow()
        :
#if defined( _WIN32 )
#elif defined( MACOSX )
#elif defined( IOS )
#elif defined( ANDROID )
#elif defined( UNX )
        dpy(NULL),
        screen(0),
        win(0),
#if defined( GLX_EXT_texture_from_pixmap )
        fbc(0),
#endif
        vi(NULL),
        ctx(0),
        glPix(0),
        GLXExtensions(NULL),
#endif
        bpp(0),
        Width(0),
        Height(0),
        GLExtensions(NULL),
        bMultiSampleSupported(false)
    {
    }

    ~GLWindow();
};

class VCLOPENGL_DLLPUBLIC OpenGLContext
{
public:
    OpenGLContext();
    ~OpenGLContext();

    void requestLegacyContext();
    void requestSingleBufferedRendering();
    void requestVirtualDevice();

    bool init(vcl::Window* pParent = 0);
    bool init(SystemChildWindow* pChildWindow);

// these methods are for the deep platform layer, don't use them in normal code
// only in vcl's platform code
#if defined( UNX ) && !defined MACOSX && !defined IOS && !defined ANDROID
    bool init(Display* dpy, Window win, int screen);
    bool init(Display* dpy, Pixmap pix, unsigned int width, unsigned int height, int nScreen);
#elif defined( _WIN32 )
    bool init( HDC hDC, HWND hWnd );
#endif

    void makeCurrent();
    void resetCurrent();
    void swapBuffers();
    void sync();
    void show();

    void setWinPosAndSize(const Point &rPos, const Size& rSize);
    void setWinSize(const Size& rSize);
    const GLWindow& getOpenGLWindow() const { return m_aGLWin;}

    SystemChildWindow* getChildWindow();
    const SystemChildWindow* getChildWindow() const;

    void renderToFile();

    bool isInitialized()
    {
        return mbInitialized;
    }

    bool supportMultiSampling() const;

    static SystemWindowData generateWinData(vcl::Window* pParent, bool bRequestLegacyContext);

private:
    SAL_DLLPRIVATE bool InitGLEW();
    SAL_DLLPRIVATE bool initWindow();
    SAL_DLLPRIVATE bool ImplInit();
#if defined( UNX ) && !defined MACOSX && !defined IOS && !defined ANDROID
    SAL_DLLPRIVATE void initGLWindow(Visual* pVisual);
#endif

#if defined(MACOSX)
    NSOpenGLView* getOpenGLView();
#endif

    GLWindow m_aGLWin;
    boost::scoped_ptr<vcl::Window> m_pWindow;
    vcl::Window* mpWindow; //points to m_pWindow or the parent window, don't delete it
    SystemChildWindow* m_pChildWindow;
    boost::scoped_ptr<SystemChildWindow> m_pChildWindowGC;
    bool mbInitialized;
    bool mbRequestLegacyContext;
    bool mbUseDoubleBufferedRendering;
    bool mbRequestVirtualDevice;
#if defined( UNX ) && !defined MACOSX && !defined IOS && !defined ANDROID
    bool mbPixmap; // is a pixmap instead of a window
#endif
};

#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>coverity#1187864 Uninitialized scalar field<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#ifndef INCLUDED_VCL_OPENGL_OPENGLCONTEXT_HXX
#define INCLUDED_VCL_OPENGL_OPENGLCONTEXT_HXX

#include <string.h>

#include <GL/glew.h>

#if defined( MACOSX )
#elif defined( IOS )
#elif defined( ANDROID )
#elif defined( UNX )
#  include <prex.h>
#  include "GL/glxew.h"
#  include <postx.h>
#elif defined( _WIN32 )
#ifndef INCLUDED_PRE_POST_WIN_H
#define INCLUDED_PRE_POST_WIN_H
#  include "prewin.h"
#  include "postwin.h"
#endif
#endif

#if defined( _WIN32 )
#include <GL/glext.h>
#include <GL/wglext.h>
#elif defined( MACOSX )
#include <OpenGL/OpenGL.h>
#ifdef __OBJC__
@class NSOpenGLView;
#else
class NSOpenGLView;
#endif
#elif defined( IOS )
#elif defined( ANDROID )
#elif defined( UNX )
#include <GL/glext.h>
#define GLX_GLXEXT_PROTOTYPES 1
#include <GL/glx.h>
#include <GL/glxext.h>
#endif

#include <vcl/vclopengl_dllapi.hxx>
#include <boost/scoped_ptr.hpp>
#include <vcl/window.hxx>
#include <tools/gen.hxx>
#include <vcl/syschild.hxx>

/// Holds the information of our new child window
struct GLWindow
{
    // Copy of gluCheckExtension(), from the Apache-licensed
    // https://code.google.com/p/glues/source/browse/trunk/glues/source/glues_registry.c
    static GLboolean checkExtension(const GLubyte* extName, const GLubyte* extString)
    {
      GLboolean flag=GL_FALSE;
      char* word;
      char* lookHere;
      char* deleteThis;

      if (extString==NULL)
      {
         return GL_FALSE;
      }

      deleteThis=lookHere=(char*)malloc(strlen((const char*)extString)+1);
      if (lookHere==NULL)
      {
         return GL_FALSE;
      }

      /* strtok() will modify string, so copy it somewhere */
      strcpy(lookHere,(const char*)extString);

      while ((word=strtok(lookHere, " "))!=NULL)
      {
         if (strcmp(word,(const char*)extName)==0)
         {
            flag=GL_TRUE;
            break;
         }
         lookHere=NULL; /* get next token */
      }
      free((void*)deleteThis);

      return flag;
    }

#if defined( _WIN32 )
    HWND                    hWnd;
    HDC                     hDC;
    HGLRC                   hRC;
#elif defined( MACOSX )
#elif defined( IOS )
#elif defined( ANDROID )
#elif defined( UNX )
    Display*            dpy;
    int                 screen;
    Window              win;
    Pixmap              pix;
#if defined( GLX_EXT_texture_from_pixmap )
    GLXFBConfig        fbc;
#endif
    XVisualInfo*       vi;
    GLXContext         ctx;
    GLXPixmap           glPix;

    bool HasGLXExtension( const char* name ) { return checkExtension( (const GLubyte*) name, (const GLubyte*) GLXExtensions ); }
    const char*             GLXExtensions;
#endif
    unsigned int            bpp;
    unsigned int            Width;
    unsigned int            Height;
    const GLubyte*          GLExtensions;
    bool bMultiSampleSupported;

    GLWindow()
        :
#if defined( _WIN32 )
#elif defined( MACOSX )
#elif defined( IOS )
#elif defined( ANDROID )
#elif defined( UNX )
        dpy(NULL),
        screen(0),
        win(0),
        pix(0),
#if defined( GLX_EXT_texture_from_pixmap )
        fbc(0),
#endif
        vi(NULL),
        ctx(0),
        glPix(0),
        GLXExtensions(NULL),
#endif
        bpp(0),
        Width(0),
        Height(0),
        GLExtensions(NULL),
        bMultiSampleSupported(false)
    {
    }

    ~GLWindow();
};

class VCLOPENGL_DLLPUBLIC OpenGLContext
{
public:
    OpenGLContext();
    ~OpenGLContext();

    void requestLegacyContext();
    void requestSingleBufferedRendering();
    void requestVirtualDevice();

    bool init(vcl::Window* pParent = 0);
    bool init(SystemChildWindow* pChildWindow);

// these methods are for the deep platform layer, don't use them in normal code
// only in vcl's platform code
#if defined( UNX ) && !defined MACOSX && !defined IOS && !defined ANDROID
    bool init(Display* dpy, Window win, int screen);
    bool init(Display* dpy, Pixmap pix, unsigned int width, unsigned int height, int nScreen);
#elif defined( _WIN32 )
    bool init( HDC hDC, HWND hWnd );
#endif

    void makeCurrent();
    void resetCurrent();
    void swapBuffers();
    void sync();
    void show();

    void setWinPosAndSize(const Point &rPos, const Size& rSize);
    void setWinSize(const Size& rSize);
    const GLWindow& getOpenGLWindow() const { return m_aGLWin;}

    SystemChildWindow* getChildWindow();
    const SystemChildWindow* getChildWindow() const;

    void renderToFile();

    bool isInitialized()
    {
        return mbInitialized;
    }

    bool supportMultiSampling() const;

    static SystemWindowData generateWinData(vcl::Window* pParent, bool bRequestLegacyContext);

private:
    SAL_DLLPRIVATE bool InitGLEW();
    SAL_DLLPRIVATE bool initWindow();
    SAL_DLLPRIVATE bool ImplInit();
#if defined( UNX ) && !defined MACOSX && !defined IOS && !defined ANDROID
    SAL_DLLPRIVATE void initGLWindow(Visual* pVisual);
#endif

#if defined(MACOSX)
    NSOpenGLView* getOpenGLView();
#endif

    GLWindow m_aGLWin;
    boost::scoped_ptr<vcl::Window> m_pWindow;
    vcl::Window* mpWindow; //points to m_pWindow or the parent window, don't delete it
    SystemChildWindow* m_pChildWindow;
    boost::scoped_ptr<SystemChildWindow> m_pChildWindowGC;
    bool mbInitialized;
    bool mbRequestLegacyContext;
    bool mbUseDoubleBufferedRendering;
    bool mbRequestVirtualDevice;
#if defined( UNX ) && !defined MACOSX && !defined IOS && !defined ANDROID
    bool mbPixmap; // is a pixmap instead of a window
#endif
};

#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright UMC Utrecht and contributors
 *
 *  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.txt
 *
 *  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 "itkTestHelper.h"
#include "itkGenericMultiResolutionPyramidImageFilter.h"

// GPU includes
#include "itkGPUImageFactory.h"
#include "itkGPURecursiveGaussianImageFilterFactory.h"
#include "itkGPUCastImageFilterFactory.h"
#include "itkGPUShrinkImageFilterFactory.h"
#include "itkGPUResampleImageFilterFactory.h"
#include "itkGPUIdentityTransformFactory.h"
#include "itkGPULinearInterpolateImageFunctionFactory.h"

#include "itkOpenCLContextScopeGuard.h"

// ITK include files
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkImageRegionConstIterator.h"
#include "itkMersenneTwisterRandomVariateGenerator.h"
#include "itkTimeProbe.h"

#include <iomanip> // setprecision, etc.
#include <random>  // For mt19937.

//------------------------------------------------------------------------------
// This test compares the CPU with the GPU version of the
// GenericMultiResolutionPyramidImageFilter.
// The filter takes an input image and produces an output image.
// We compare the CPU and GPU output image write RMSE and speed.

int
main(int argc, char * argv[])
{
  // Check arguments for help
  if (argc < 4)
  {
    std::cerr << "ERROR: insufficient command line arguments.\n"
              << "  inputFileName outputNameCPU outputNameGPU" << std::endl;
    return EXIT_FAILURE;
  }

  // Setup for debugging
  itk::SetupForDebugging();

  // Create and check OpenCL context
  if (!itk::CreateContext())
  {
    return EXIT_FAILURE;
  }
  const itk::OpenCLContextScopeGuard openCLContextScopeGuard{};

  /** Get the command line arguments. */
  const std::string  inputFileName = argv[1];
  const std::string  outputFileNameCPU = argv[2];
  const std::string  outputFileNameGPU = argv[3];
  const unsigned int numberOfLevels = 4;
  const bool         useMultiResolutionRescaleSchedule = true;
  const bool         useMultiResolutionSmoothingSchedule = true;
  const bool         useShrinkImageFilter = false;
  const bool         computeOnlyForCurrentLevel = true;
  const double       epsilon = 1e-3;
  const unsigned int runTimes = 5;

  std::cout << std::showpoint << std::setprecision(4);

  // Typedefs.
  const unsigned int Dimension = 3;
  using InputPixelType = float;
  using OutputPixelType = float;
  using InputImageType = itk::Image<InputPixelType, Dimension>;
  using OutputImageType = itk::Image<OutputPixelType, Dimension>;
  using GPUInputImageType = itk::GPUImage<InputPixelType, Dimension>;
  using GPUOutputImageType = itk::GPUImage<OutputPixelType, Dimension>;

  // CPU Typedefs
  using PrecisionType = float;
  using FilterType = itk::GenericMultiResolutionPyramidImageFilter<InputImageType, OutputImageType, PrecisionType>;
  using GPUFilterType =
    itk::GenericMultiResolutionPyramidImageFilter<GPUInputImageType, GPUOutputImageType, PrecisionType>;
  using ReaderType = itk::ImageFileReader<InputImageType>;

  // Reader
  auto reader = ReaderType::New();
  reader->SetFileName(inputFileName);
  reader->Update();

  // Construct the filter
  auto cpuFilter = FilterType::New();

  using RescaleScheduleType = FilterType::RescaleScheduleType;
  using SmoothingScheduleType = FilterType::SmoothingScheduleType;

  using RandomNumberGeneratorType = itk::Statistics::MersenneTwisterRandomVariateGenerator;
  RandomNumberGeneratorType::Pointer randomNum = RandomNumberGeneratorType::GetInstance();
  randomNum->SetSeed(std::mt19937::default_seed);

  RescaleScheduleType   rescaleSchedule(numberOfLevels, Dimension);
  SmoothingScheduleType smoothingSchedule(numberOfLevels, Dimension);
  double                tmp = 0.0;
  for (unsigned int i = 0; i < numberOfLevels; ++i)
  {
    for (unsigned int j = 0; j < Dimension; ++j)
    {
      tmp = randomNum->GetUniformVariate(0, 8);
      rescaleSchedule[i][j] = static_cast<unsigned int>(tmp);

      tmp = randomNum->GetUniformVariate(0, 4);
      smoothingSchedule[i][j] = tmp;
    }
  }

  cpuFilter->SetNumberOfLevels(numberOfLevels);
  cpuFilter->SetRescaleSchedule(rescaleSchedule);
  cpuFilter->SetSmoothingSchedule(smoothingSchedule);
  if (!useMultiResolutionSmoothingSchedule)
  {
    cpuFilter->SetRescaleScheduleToUnity();
  }
  if (!useMultiResolutionRescaleSchedule)
  {
    cpuFilter->SetSmoothingScheduleToZero();
  }
  cpuFilter->SetUseShrinkImageFilter(useShrinkImageFilter);
  cpuFilter->SetComputeOnlyForCurrentLevel(computeOnlyForCurrentLevel);

  std::cout << "RescaleSchedule:\n" << rescaleSchedule << "\n";
  std::cout << "SmoothingSchedule:\n" << smoothingSchedule << "\n";
  std::cout << "Testing the GenericMultiResolutionPyramidImageFilter, CPU vs GPU:\n";
  std::cout << "CPU/GPU #threads time speedup RMSE\n";
  // std::cout << "CPU/GPU factors sigmas #threads time speedup RMSE\n";

  // Time the filter, run on the CPU
  itk::TimeProbe cputimer;
  cputimer.Start();
  for (unsigned int i = 0; i < runTimes; ++i)
  {
    cpuFilter->SetInput(reader->GetOutput());

    if (!computeOnlyForCurrentLevel)
    {
      try
      {
        cpuFilter->Update();
      }
      catch (itk::ExceptionObject & e)
      {
        std::cerr << "ERROR: " << e << std::endl;
        return EXIT_FAILURE;
      }
      cpuFilter->Modified();
    }
    else
    {
      for (unsigned int j = 0; j < cpuFilter->GetNumberOfLevels(); ++j)
      {
        cpuFilter->SetCurrentLevel(j);
        try
        {
          cpuFilter->Update();
        }
        catch (itk::ExceptionObject & e)
        {
          std::cerr << "ERROR: " << e << std::endl;
          return EXIT_FAILURE;
        }
        // Modify the filter, only not the last iteration
        if (i != runTimes - 1)
        {
          cpuFilter->Modified();
        }
      }
    }
  }
  cputimer.Stop();

  std::cout << "CPU " << cpuFilter->GetNumberOfWorkUnits() << " " << cputimer.GetMean() / runTimes << std::endl;

  /** Write the CPU result. */
  try
  {
    itk::WriteImage(cpuFilter->GetOutput(numberOfLevels - 1), outputFileNameCPU);
  }
  catch (itk::ExceptionObject & e)
  {
    std::cerr << "ERROR: " << e << std::endl;
    return EXIT_FAILURE;
  }

  // Register object factory for GPU image and filter
  // All these filters that are constructed after this point are
  // turned into a GPU filter.
  // Note that we are not registering a
  // GPUGenericMultiResolutionPyramidImageFilter,
  // but the recursive one. We are simply using the original ITK implementation,
  // that internally uses the recursive filter. By registering the recursive
  // filter, we now automatically use it, even if it's usage is hidden by a
  // wrapper.
  using OCLImageTypes = typelist::MakeTypeList<float>::Type;
  itk::GPUImageFactory2<OCLImageTypes, OCLImageDims>::RegisterOneFactory();
  itk::GPURecursiveGaussianImageFilterFactory2<OCLImageTypes, OCLImageTypes, OCLImageDims>::RegisterOneFactory();
  itk::GPUCastImageFilterFactory2<OCLImageTypes, OCLImageTypes, OCLImageDims>::RegisterOneFactory();
  itk::GPUShrinkImageFilterFactory2<OCLImageTypes, OCLImageTypes, OCLImageDims>::RegisterOneFactory();
  itk::GPUResampleImageFilterFactory2<OCLImageTypes, OCLImageTypes, OCLImageDims>::RegisterOneFactory();
  itk::GPUIdentityTransformFactory2<OCLImageDims>::RegisterOneFactory();
  itk::GPULinearInterpolateImageFunctionFactory2<OCLImageTypes, OCLImageDims>::RegisterOneFactory();

  // Construct the filter
  // Use a try/catch, because construction of this filter will trigger
  // OpenCL compilation, which may fail.
  GPUFilterType::Pointer gpuFilter;
  try
  {
    gpuFilter = GPUFilterType::New();
    itk::ITKObjectEnableWarnings(gpuFilter.GetPointer());
  }
  catch (itk::ExceptionObject & e)
  {
    std::cerr << "ERROR: " << e << std::endl;
    return EXIT_FAILURE;
  }
  gpuFilter->SetNumberOfLevels(numberOfLevels);
  gpuFilter->SetRescaleSchedule(rescaleSchedule);
  gpuFilter->SetSmoothingSchedule(smoothingSchedule);
  if (!useMultiResolutionSmoothingSchedule)
  {
    gpuFilter->SetRescaleScheduleToUnity();
  }
  if (!useMultiResolutionRescaleSchedule)
  {
    gpuFilter->SetSmoothingScheduleToZero();
  }
  gpuFilter->SetUseShrinkImageFilter(useShrinkImageFilter);
  gpuFilter->SetComputeOnlyForCurrentLevel(computeOnlyForCurrentLevel);

  // Also need to re-construct the image reader, so that it now
  // reads a GPUImage instead of a normal image.
  // Otherwise, you will get an exception when running the GPU filter:
  // "ERROR: The GPU InputImage is NULL. Filter unable to perform."
  auto gpuReader = ReaderType::New();
  gpuReader->SetFileName(inputFileName);

  // \todo: If the following line is uncommented something goes wrong with
  // the ITK pipeline synchronization.
  // Something is still read in, but I guess it is not properly copied to
  // the GPU. The output of the shrink filter is then bogus.
  // The following line is however not needed in a pure CPU implementation.
  gpuReader->Update();

  // GPU input image
  GPUInputImageType::Pointer gpuInputImage = GPUInputImageType::New();
  gpuInputImage->GraftITKImage(gpuReader->GetOutput());
  gpuInputImage->AllocateGPU();
  gpuInputImage->GetGPUDataManager()->SetCPUBufferLock(true);
  gpuInputImage->GetGPUDataManager()->SetGPUDirtyFlag(true);
  gpuInputImage->GetGPUDataManager()->UpdateGPUBuffer();

  // Time the filter, run on the GPU
  itk::TimeProbe gputimer;
  gputimer.Start();
  for (unsigned int i = 0; i < runTimes; ++i)
  {
    gpuFilter->SetInput(gpuInputImage);

    if (!computeOnlyForCurrentLevel)
    {
      try
      {
        gpuFilter->Update();
      }
      catch (itk::ExceptionObject & e)
      {
        std::cerr << "ERROR: " << e << std::endl;
        return EXIT_FAILURE;
      }
      // Modify the filter, only not the last iteration
      if (i != runTimes - 1)
      {
        gpuFilter->Modified();
      }
    }
    else
    {
      for (unsigned int j = 0; j < gpuFilter->GetNumberOfLevels(); ++j)
      {
        gpuFilter->SetCurrentLevel(j);
        try
        {
          gpuFilter->Update();
        }
        catch (itk::ExceptionObject & e)
        {
          std::cerr << "ERROR: " << e << std::endl;
          return EXIT_FAILURE;
        }
        // Modify the filter, only not the last iteration
        if (i != runTimes - 1)
        {
          gpuFilter->Modified();
        }
      }
    }
  }
  gputimer.Stop();

  std::cout << "GPU x " << gputimer.GetMean() / runTimes << " " << cputimer.GetMean() / gputimer.GetMean();

  /** Write the GPU result. */
  try
  {
    itk::WriteImage(gpuFilter->GetOutput(numberOfLevels - 1), outputFileNameGPU);
  }
  catch (itk::ExceptionObject & e)
  {
    std::cerr << "ERROR: " << e << std::endl;
    return EXIT_FAILURE;
  }

  // Compute RMSE
  double       RMSrelative = 0.0;
  const double RMSerror = itk::ComputeRMSE<double, OutputImageType, OutputImageType>(
    cpuFilter->GetOutput(numberOfLevels - 1), gpuFilter->GetOutput(numberOfLevels - 1), RMSrelative);
  std::cout << " " << RMSerror << std::endl;

  // Check
  if (RMSerror > epsilon)
  {
    std::cerr << "ERROR: RMSE between CPU and GPU result larger than expected" << std::endl;
    return EXIT_FAILURE;
  }

  // End program.
  return EXIT_SUCCESS;
} // end main()
<commit_msg>STYLE: Use ReadImage in GPUGenericMultiResolutionPyramidImageFilterTest<commit_after>/*=========================================================================
 *
 *  Copyright UMC Utrecht and contributors
 *
 *  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.txt
 *
 *  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 "itkTestHelper.h"
#include "itkGenericMultiResolutionPyramidImageFilter.h"

// GPU includes
#include "itkGPUImageFactory.h"
#include "itkGPURecursiveGaussianImageFilterFactory.h"
#include "itkGPUCastImageFilterFactory.h"
#include "itkGPUShrinkImageFilterFactory.h"
#include "itkGPUResampleImageFilterFactory.h"
#include "itkGPUIdentityTransformFactory.h"
#include "itkGPULinearInterpolateImageFunctionFactory.h"

#include "itkOpenCLContextScopeGuard.h"

// ITK include files
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkImageRegionConstIterator.h"
#include "itkMersenneTwisterRandomVariateGenerator.h"
#include "itkTimeProbe.h"

#include <iomanip> // setprecision, etc.
#include <random>  // For mt19937.

//------------------------------------------------------------------------------
// This test compares the CPU with the GPU version of the
// GenericMultiResolutionPyramidImageFilter.
// The filter takes an input image and produces an output image.
// We compare the CPU and GPU output image write RMSE and speed.

int
main(int argc, char * argv[])
{
  // Check arguments for help
  if (argc < 4)
  {
    std::cerr << "ERROR: insufficient command line arguments.\n"
              << "  inputFileName outputNameCPU outputNameGPU" << std::endl;
    return EXIT_FAILURE;
  }

  // Setup for debugging
  itk::SetupForDebugging();

  // Create and check OpenCL context
  if (!itk::CreateContext())
  {
    return EXIT_FAILURE;
  }
  const itk::OpenCLContextScopeGuard openCLContextScopeGuard{};

  /** Get the command line arguments. */
  const std::string  inputFileName = argv[1];
  const std::string  outputFileNameCPU = argv[2];
  const std::string  outputFileNameGPU = argv[3];
  const unsigned int numberOfLevels = 4;
  const bool         useMultiResolutionRescaleSchedule = true;
  const bool         useMultiResolutionSmoothingSchedule = true;
  const bool         useShrinkImageFilter = false;
  const bool         computeOnlyForCurrentLevel = true;
  const double       epsilon = 1e-3;
  const unsigned int runTimes = 5;

  std::cout << std::showpoint << std::setprecision(4);

  // Typedefs.
  const unsigned int Dimension = 3;
  using InputPixelType = float;
  using OutputPixelType = float;
  using InputImageType = itk::Image<InputPixelType, Dimension>;
  using OutputImageType = itk::Image<OutputPixelType, Dimension>;
  using GPUInputImageType = itk::GPUImage<InputPixelType, Dimension>;
  using GPUOutputImageType = itk::GPUImage<OutputPixelType, Dimension>;

  // CPU Typedefs
  using PrecisionType = float;
  using FilterType = itk::GenericMultiResolutionPyramidImageFilter<InputImageType, OutputImageType, PrecisionType>;
  using GPUFilterType =
    itk::GenericMultiResolutionPyramidImageFilter<GPUInputImageType, GPUOutputImageType, PrecisionType>;

  // Read image
  InputImageType::Pointer inputImage = itk::ReadImage<InputImageType>(inputFileName);

  // Construct the filter
  auto cpuFilter = FilterType::New();

  using RescaleScheduleType = FilterType::RescaleScheduleType;
  using SmoothingScheduleType = FilterType::SmoothingScheduleType;

  using RandomNumberGeneratorType = itk::Statistics::MersenneTwisterRandomVariateGenerator;
  RandomNumberGeneratorType::Pointer randomNum = RandomNumberGeneratorType::GetInstance();
  randomNum->SetSeed(std::mt19937::default_seed);

  RescaleScheduleType   rescaleSchedule(numberOfLevels, Dimension);
  SmoothingScheduleType smoothingSchedule(numberOfLevels, Dimension);
  double                tmp = 0.0;
  for (unsigned int i = 0; i < numberOfLevels; ++i)
  {
    for (unsigned int j = 0; j < Dimension; ++j)
    {
      tmp = randomNum->GetUniformVariate(0, 8);
      rescaleSchedule[i][j] = static_cast<unsigned int>(tmp);

      tmp = randomNum->GetUniformVariate(0, 4);
      smoothingSchedule[i][j] = tmp;
    }
  }

  cpuFilter->SetNumberOfLevels(numberOfLevels);
  cpuFilter->SetRescaleSchedule(rescaleSchedule);
  cpuFilter->SetSmoothingSchedule(smoothingSchedule);
  if (!useMultiResolutionSmoothingSchedule)
  {
    cpuFilter->SetRescaleScheduleToUnity();
  }
  if (!useMultiResolutionRescaleSchedule)
  {
    cpuFilter->SetSmoothingScheduleToZero();
  }
  cpuFilter->SetUseShrinkImageFilter(useShrinkImageFilter);
  cpuFilter->SetComputeOnlyForCurrentLevel(computeOnlyForCurrentLevel);

  std::cout << "RescaleSchedule:\n" << rescaleSchedule << "\n";
  std::cout << "SmoothingSchedule:\n" << smoothingSchedule << "\n";
  std::cout << "Testing the GenericMultiResolutionPyramidImageFilter, CPU vs GPU:\n";
  std::cout << "CPU/GPU #threads time speedup RMSE\n";
  // std::cout << "CPU/GPU factors sigmas #threads time speedup RMSE\n";

  // Time the filter, run on the CPU
  itk::TimeProbe cputimer;
  cputimer.Start();
  for (unsigned int i = 0; i < runTimes; ++i)
  {
    cpuFilter->SetInput(inputImage);

    if (!computeOnlyForCurrentLevel)
    {
      try
      {
        cpuFilter->Update();
      }
      catch (itk::ExceptionObject & e)
      {
        std::cerr << "ERROR: " << e << std::endl;
        return EXIT_FAILURE;
      }
      cpuFilter->Modified();
    }
    else
    {
      for (unsigned int j = 0; j < cpuFilter->GetNumberOfLevels(); ++j)
      {
        cpuFilter->SetCurrentLevel(j);
        try
        {
          cpuFilter->Update();
        }
        catch (itk::ExceptionObject & e)
        {
          std::cerr << "ERROR: " << e << std::endl;
          return EXIT_FAILURE;
        }
        // Modify the filter, only not the last iteration
        if (i != runTimes - 1)
        {
          cpuFilter->Modified();
        }
      }
    }
  }
  cputimer.Stop();

  std::cout << "CPU " << cpuFilter->GetNumberOfWorkUnits() << " " << cputimer.GetMean() / runTimes << std::endl;

  /** Write the CPU result. */
  try
  {
    itk::WriteImage(cpuFilter->GetOutput(numberOfLevels - 1), outputFileNameCPU);
  }
  catch (itk::ExceptionObject & e)
  {
    std::cerr << "ERROR: " << e << std::endl;
    return EXIT_FAILURE;
  }

  // Register object factory for GPU image and filter
  // All these filters that are constructed after this point are
  // turned into a GPU filter.
  // Note that we are not registering a
  // GPUGenericMultiResolutionPyramidImageFilter,
  // but the recursive one. We are simply using the original ITK implementation,
  // that internally uses the recursive filter. By registering the recursive
  // filter, we now automatically use it, even if it's usage is hidden by a
  // wrapper.
  using OCLImageTypes = typelist::MakeTypeList<float>::Type;
  itk::GPUImageFactory2<OCLImageTypes, OCLImageDims>::RegisterOneFactory();
  itk::GPURecursiveGaussianImageFilterFactory2<OCLImageTypes, OCLImageTypes, OCLImageDims>::RegisterOneFactory();
  itk::GPUCastImageFilterFactory2<OCLImageTypes, OCLImageTypes, OCLImageDims>::RegisterOneFactory();
  itk::GPUShrinkImageFilterFactory2<OCLImageTypes, OCLImageTypes, OCLImageDims>::RegisterOneFactory();
  itk::GPUResampleImageFilterFactory2<OCLImageTypes, OCLImageTypes, OCLImageDims>::RegisterOneFactory();
  itk::GPUIdentityTransformFactory2<OCLImageDims>::RegisterOneFactory();
  itk::GPULinearInterpolateImageFunctionFactory2<OCLImageTypes, OCLImageDims>::RegisterOneFactory();

  // Construct the filter
  // Use a try/catch, because construction of this filter will trigger
  // OpenCL compilation, which may fail.
  GPUFilterType::Pointer gpuFilter;
  try
  {
    gpuFilter = GPUFilterType::New();
    itk::ITKObjectEnableWarnings(gpuFilter.GetPointer());
  }
  catch (itk::ExceptionObject & e)
  {
    std::cerr << "ERROR: " << e << std::endl;
    return EXIT_FAILURE;
  }
  gpuFilter->SetNumberOfLevels(numberOfLevels);
  gpuFilter->SetRescaleSchedule(rescaleSchedule);
  gpuFilter->SetSmoothingSchedule(smoothingSchedule);
  if (!useMultiResolutionSmoothingSchedule)
  {
    gpuFilter->SetRescaleScheduleToUnity();
  }
  if (!useMultiResolutionRescaleSchedule)
  {
    gpuFilter->SetSmoothingScheduleToZero();
  }
  gpuFilter->SetUseShrinkImageFilter(useShrinkImageFilter);
  gpuFilter->SetComputeOnlyForCurrentLevel(computeOnlyForCurrentLevel);

  // GPU input image
  GPUInputImageType::Pointer gpuInputImage = GPUInputImageType::New();
  gpuInputImage->GraftITKImage(inputImage);
  gpuInputImage->AllocateGPU();
  gpuInputImage->GetGPUDataManager()->SetCPUBufferLock(true);
  gpuInputImage->GetGPUDataManager()->SetGPUDirtyFlag(true);
  gpuInputImage->GetGPUDataManager()->UpdateGPUBuffer();

  // Time the filter, run on the GPU
  itk::TimeProbe gputimer;
  gputimer.Start();
  for (unsigned int i = 0; i < runTimes; ++i)
  {
    gpuFilter->SetInput(gpuInputImage);

    if (!computeOnlyForCurrentLevel)
    {
      try
      {
        gpuFilter->Update();
      }
      catch (itk::ExceptionObject & e)
      {
        std::cerr << "ERROR: " << e << std::endl;
        return EXIT_FAILURE;
      }
      // Modify the filter, only not the last iteration
      if (i != runTimes - 1)
      {
        gpuFilter->Modified();
      }
    }
    else
    {
      for (unsigned int j = 0; j < gpuFilter->GetNumberOfLevels(); ++j)
      {
        gpuFilter->SetCurrentLevel(j);
        try
        {
          gpuFilter->Update();
        }
        catch (itk::ExceptionObject & e)
        {
          std::cerr << "ERROR: " << e << std::endl;
          return EXIT_FAILURE;
        }
        // Modify the filter, only not the last iteration
        if (i != runTimes - 1)
        {
          gpuFilter->Modified();
        }
      }
    }
  }
  gputimer.Stop();

  std::cout << "GPU x " << gputimer.GetMean() / runTimes << " " << cputimer.GetMean() / gputimer.GetMean();

  /** Write the GPU result. */
  try
  {
    itk::WriteImage(gpuFilter->GetOutput(numberOfLevels - 1), outputFileNameGPU);
  }
  catch (itk::ExceptionObject & e)
  {
    std::cerr << "ERROR: " << e << std::endl;
    return EXIT_FAILURE;
  }

  // Compute RMSE
  double       RMSrelative = 0.0;
  const double RMSerror = itk::ComputeRMSE<double, OutputImageType, OutputImageType>(
    cpuFilter->GetOutput(numberOfLevels - 1), gpuFilter->GetOutput(numberOfLevels - 1), RMSrelative);
  std::cout << " " << RMSerror << std::endl;

  // Check
  if (RMSerror > epsilon)
  {
    std::cerr << "ERROR: RMSE between CPU and GPU result larger than expected" << std::endl;
    return EXIT_FAILURE;
  }

  // End program.
  return EXIT_SUCCESS;
} // end main()
<|endoftext|>


<commit_before>#ifndef MANIFOLDS_FUNCTIONS_POLY_COMPOS_SIMPLIFICATIONS_HH
#define MANIFOLDS_FUNCTIONS_POLY_COMPOS_SIMPLIFICATIONS_HH

namespace manifolds {

  template <class A>
  struct Simplification<
    Addition<A,A>, 0,
    typename std::enable_if<
      is_stateless<A>::value>::type>
  {
    typedef Composition<
      Polynomial<double,int_<2>>,
      A> type;
    static type Combine(Addition<A,A> a)
    {
#ifdef PRINT_SIMPLIFIES
      std::cout << "Simplifying addition of function by itself\n";
#endif
      type b = {GetPolynomial(0.0,2.0), A()};
      return b;
    }
  };

  template <class A>
  struct Simplification<
    Multiplication<A,A>, 2,
    typename std::enable_if<is_stateless<A>::value>::type>
  {
    typedef Composition<
      Polynomial<double,int_<3>>,A> type;

    static type Combine(Multiplication<A,A>)
    {
#ifdef PRINT_SIMPLIFIES
      std::cout << "Simplifying multiplication of function "
	"by itself\n";
#endif
      return {GetPolynomial(0,0,1), A()};
    }
  };

  template <class Arg1, class Arg2, class ... Args>
  struct Simplification<
    Multiplication<Composition<Arg1, Args...>,
		   Composition<Arg2, Args...>>, 0,
    typename std::enable_if<
      and_<is_stateless<Args>...>::value &&
      (!std::is_same<Arg1,Arg2>::value ||
       !is_stateless<Arg1>::value ||
       !is_stateless<Arg2>::value) &&
      !std::is_same<
	typename Simplification<Multiplication<Arg1,Arg2>>::type,
	Multiplication<Arg1,Arg2>
	>::value>::type>
  {
    typedef Composition<
      typename Simplification<
	Multiplication<Arg1, Arg2>>::type,
      Args...> type;

    static type Combine(Multiplication<Composition<Arg1, Args...>,
			Composition<Arg2, Args...>> a)
    {
#ifdef PRINT_SIMPLIFIES
      std::cout << "Simplifying multipication of composition of "
	"simplifiable functions\n";
#endif
      auto first = get<0>(get<0>(a.GetFunctions()).
			       GetFunctions());
      auto second = get<0>(get<1>(a.GetFunctions()).
				GetFunctions());
      Multiplication<decltype(first),decltype(second)>
	m(first,second);
      auto s = Simplify(m);
      return {s, Args()...};
    }
  };

  template <class CType, int order, class T>
  struct Simplification<
    Addition<Composition<
	       Polynomial<CType, int_<order>>, T>, T>, 0,
    typename std::enable_if<is_stateless<T>::value>::type>
  {
    static const int new_order = 2 > order ? 2 : order;
    typedef Composition<Polynomial<CType, int_<new_order>>, T> type;
    template <class A, class B>
      static auto Add(A a, B b)
    {
      return Addition<A,B>(a,b);
    }
    static type Combine(Addition<Composition<
			Polynomial<CType, int_<order>>, T>, T> a)
    {
#ifdef PRINT_SIMPLIFIES
      std::cout << "Simplifying addition of composed polynomial "
	"by inner function\n";
#endif
      auto p = get<0>(get<0>(a.GetFunctions()).
			   GetFunctions());
      return Simplify(Add(GetPolynomial(0,1), p))(T());
    }
  };

  template <class CType, int order, class T>
  struct Simplification<
    Multiplication<Composition<
		     Polynomial<CType, int_<order>>, T>, T>, 0,
    typename std::enable_if<is_stateless<T>::value>::type>
  {
    static const int new_order = 1 + order;
    typedef Composition<Polynomial<CType, int_<new_order>>, T> type;

    template <class A, class B>
      static auto Mult(A a, B b)
    {
      return Simplify(Multiplication<A,B>(a,b));
    }

    static type Combine(Multiplication<Composition<
			Polynomial<CType, int_<order>>, T>, T> a)
    {
#ifdef PRINT_SIMPLIFIES
      std::cout << "Simplifying multiplication of composed "
	"polynomial by inner function\n";
#endif
      auto m =
	Mult(GetPolynomial(0,1),
	     get<0>(get<0>
			 (a.GetFunctions()).
			 GetFunctions()));
      T t;
      return m(t);
    }
  };

  template <template <class...>class Variadic,
	    class CType, int order, class T>
  struct Simplification<
    Variadic<T, Composition<
      Polynomial<CType, int_<order>>, T>>, 1,
      typename std::enable_if<is_stateless<T>::value>::type>
  {
    typedef Simplification<
      Variadic<Composition<
		 Polynomial<CType, int_<order>>,
		 T>, T>> ref_type;
    typedef typename ref_type::type type;

    static type Combine(Variadic<T, Composition<
			Polynomial<CType, int_<order>>, T>> a)
    {
#ifdef PRINT_SIMPLIFIES
      std::cout << "Simplifying inverted composed "
	"polynomial operation\n";
#endif
      auto t = a.GetFunctions();
      typedef typename std::remove_reference<
	decltype(get<1>(t))>::type T1;
      typedef typename std::remove_reference<
	decltype(get<0>(t))>::type T2;
      Variadic<T1, T2> v(get<1>(t), get<0>(t));
      return ref_type::Combine(v);
    }
  };

  template <class CoeffType,
	    class ... Functions>
  struct Simplification<
    Composition<Polynomial<CoeffType,int_<1>>,Functions...>,0>
  {
    typedef Polynomial<CoeffType,int_<1>> type;

    static type Combine(Composition<Polynomial<
			CoeffType,int_<1>>,Functions...> p)
    {
#ifdef PRINT_SIMPLIFIES
      std::cout << "Simplifying composition of "
	"constant polynomial\n";
#endif
      return get<0>(p.GetFunctions());
    }
  };

  template <class T, class C>
  struct Simplification<Addition<T, Polynomial<C, int_<1>>>>
  {
    typedef Addition<T, Polynomial<C, int_<1>>> in_type;
    static auto Combine(in_type a)
    {
      auto t = a.GetFunctions();
      return GetPolynomial(get<1>(t).GetCoeffs()[0], (C)1)
	(get<0>(t));
    }
    typedef decltype(Combine(std::declval<in_type>())) type;
  };

  template <template<class...>class Variadic,
	    class C1, class O1,
	    class C2, class O2,
	    class ... F1s>
  struct Simplification<
    Variadic<Composition<Polynomial<C1,O1>,F1s...>,
	     Composition<Polynomial<C2,O2>,F1s...>>, 1,
    typename std::enable_if<
      is_stateless<Composition<F1s...>>::value>::type>
  {
    typedef Variadic<Polynomial<C1,O2>,
		     Polynomial<C2,O2>> inter_type;
    typedef Composition<
      SimplifiedType<inter_type>,
      F1s...> type;
    static type Combine(Variadic<Composition<
			Polynomial<C1,O1>,F1s...>,
			Composition<
			Polynomial<C2,O2>,F1s...>> v)
    {
      auto t = v.GetFunctions();
      inter_type i(get<0>(get<0>(t).GetFunctions()),
		   get<0>(get<1>(t).GetFunctions()));
      return make_my_tuple(Simplify(i), F1s()...);
    }
  };

    template <class C, class O, class ... Fs>
    struct Simplification<
        Composition<
            Polynomial<C,O>, Addition<Fs...> >, 3>
    {
        typedef Composition<
            Polynomial<C,O>, Addition<Fs...> > in_type;

        static auto P(C c){return GetPolynomial(c);}

        template <class T, std::size_t>
        struct Dummy
        {
            typedef T type;
        };

        template <std::size_t ... count>
        static auto Mult(C c, Addition<Fs...> a,
                         std::integer_sequence<std::size_t, count...>)
        {
            auto p = P(c);
            Multiplication<
                decltype(p),
                typename Dummy<Addition<Fs...>, count>::type...> r(P(c), ((void)count, a)...);
            return r;
        }

        template <std::size_t ... orders>
        static auto Addem(in_type c, std::integer_sequence<std::size_t, orders...>)
        {
            auto a = get<1>(c.GetFunctions());
            auto coeffs = get<0>(c.GetFunctions()).GetCoeffs();
            return Add(Mult(coeffs[orders], a, std::make_index_sequence<orders>())...);
        }

        static auto Combine(in_type c)
        {
            return Addem(c, std::make_index_sequence<O::value>());
        }
    };
}

#endif
<commit_msg>Fixing up some simplifications and commenting out one for later work<commit_after>#ifndef MANIFOLDS_FUNCTIONS_POLY_COMPOS_SIMPLIFICATIONS_HH
#define MANIFOLDS_FUNCTIONS_POLY_COMPOS_SIMPLIFICATIONS_HH

namespace manifolds {

  template <class A>
  struct Simplification<
    Addition<A,A>, 0,
    typename std::enable_if<
      is_stateless<A>::value>::type>
  {
    typedef Composition<
      Polynomial<double,int_<2>>,
      A> type;
    static type Combine(Addition<A,A> a)
    {
#ifdef PRINT_SIMPLIFIES
      std::cout << "Simplifying addition of function by itself\n";
#endif
      type b = {GetPolynomial(0.0,2.0), A()};
      return b;
    }
  };

  template <class A>
  struct Simplification<
    Multiplication<A,A>, 2,
    typename std::enable_if<is_stateless<A>::value>::type>
  {
    typedef Composition<
      Polynomial<double,int_<3>>,A> type;

    static type Combine(Multiplication<A,A>)
    {
#ifdef PRINT_SIMPLIFIES
      std::cout << "Simplifying multiplication of function "
	"by itself\n";
#endif
      return {GetPolynomial(0,0,1), A()};
    }
  };

  template <class Arg1, class Arg2, class ... Args>
  struct Simplification<
    Multiplication<Composition<Arg1, Args...>,
		   Composition<Arg2, Args...>>, 0,
    typename std::enable_if<
      and_<is_stateless<Args>...>::value &&
      (!std::is_same<Arg1,Arg2>::value ||
       !is_stateless<Arg1>::value ||
       !is_stateless<Arg2>::value) &&
      !std::is_same<
	typename Simplification<Multiplication<Arg1,Arg2>>::type,
	Multiplication<Arg1,Arg2>
	>::value>::type>
  {
    typedef Composition<
      typename Simplification<
	Multiplication<Arg1, Arg2>>::type,
      Args...> type;

    static type Combine(Multiplication<Composition<Arg1, Args...>,
			Composition<Arg2, Args...>> a)
    {
#ifdef PRINT_SIMPLIFIES
      std::cout << "Simplifying multipication of composition of "
	"simplifiable functions\n";
#endif
      auto first = get<0>(get<0>(a.GetFunctions()).
			       GetFunctions());
      auto second = get<0>(get<1>(a.GetFunctions()).
				GetFunctions());
      Multiplication<decltype(first),decltype(second)>
	m(first,second);
      auto s = Simplify(m);
      return {s, Args()...};
    }
  };

  template <class CType, int order, class T>
  struct Simplification<
    Addition<Composition<
	       Polynomial<CType, int_<order>>, T>, T>, 0,
    typename std::enable_if<is_stateless<T>::value>::type>
  {
    static const int new_order = 2 > order ? 2 : order;
    typedef Composition<Polynomial<CType, int_<new_order>>, T> type;
    template <class A, class B>
      static auto Add(A a, B b)
    {
      return Addition<A,B>(a,b);
    }
    static type Combine(Addition<Composition<
			Polynomial<CType, int_<order>>, T>, T> a)
    {
#ifdef PRINT_SIMPLIFIES
      std::cout << "Simplifying addition of composed polynomial "
	"by inner function\n";
#endif
      auto p = get<0>(get<0>(a.GetFunctions()).
			   GetFunctions());
      return Simplify(Add(GetPolynomial(0,1), p))(T());
    }
  };

  template <class CType, int order, class T>
  struct Simplification<
    Multiplication<Composition<
		     Polynomial<CType, int_<order>>, T>, T>, 0,
    typename std::enable_if<is_stateless<T>::value>::type>
  {
    static const int new_order = 1 + order;
    typedef Composition<Polynomial<CType, int_<new_order>>, T> type;

    template <class A, class B>
      static auto Mult(A a, B b)
    {
      return Simplify(Multiplication<A,B>(a,b));
    }

    static type Combine(Multiplication<Composition<
			Polynomial<CType, int_<order>>, T>, T> a)
    {
#ifdef PRINT_SIMPLIFIES
      std::cout << "Simplifying multiplication of composed "
	"polynomial by inner function\n";
#endif
      auto m =
	Mult(GetPolynomial(0,1),
	     get<0>(get<0>
			 (a.GetFunctions()).
			 GetFunctions()));
      T t;
      return m(t);
    }
  };

  template <template <class...>class Variadic,
	    class CType, int order, class T>
  struct Simplification<
    Variadic<T, Composition<
      Polynomial<CType, int_<order>>, T>>, 1,
      typename std::enable_if<is_stateless<T>::value>::type>
  {
    typedef Simplification<
      Variadic<Composition<
		 Polynomial<CType, int_<order>>,
		 T>, T>> ref_type;
    typedef typename ref_type::type type;

    static type Combine(Variadic<T, Composition<
			Polynomial<CType, int_<order>>, T>> a)
    {
#ifdef PRINT_SIMPLIFIES
      std::cout << "Simplifying inverted composed "
	"polynomial operation\n";
#endif
      auto t = a.GetFunctions();
      typedef typename std::remove_reference<
	decltype(get<1>(t))>::type T1;
      typedef typename std::remove_reference<
	decltype(get<0>(t))>::type T2;
      Variadic<T1, T2> v(get<1>(t), get<0>(t));
      return ref_type::Combine(v);
    }
  };

  template <class CoeffType,
	    class ... Functions>
  struct Simplification<
    Composition<Polynomial<CoeffType,int_<1>>,Functions...>,0>
  {
    typedef Polynomial<CoeffType,int_<1>> type;

    static type Combine(Composition<Polynomial<
			CoeffType,int_<1>>,Functions...> p)
    {
#ifdef PRINT_SIMPLIFIES
      std::cout << "Simplifying composition of "
	"constant polynomial\n";
#endif
      return get<0>(p.GetFunctions());
    }
  };

  template <class T, class C>
  struct Simplification<Addition<T, Polynomial<C, int_<1>>>>
  {
    typedef Addition<T, Polynomial<C, int_<1>>> in_type;
    static auto Combine(in_type a)
    {
#ifdef PRINT_SIMPLIFIES
      std::cout << "Simplifying adddition of constant "
	"and another function\n";
#endif
      auto t = a.GetFunctions();
      return GetPolynomial(get<1>(t).GetCoeffs()[0], (C)1)
	(get<0>(t));
    }
    typedef decltype(Combine(std::declval<in_type>())) type;
  };

  /*  template <template<class...>class Variadic,
	    class C1, class O1,
	    class C2, class O2,
	    class ... F1s>
  struct Simplification<
    Variadic<Composition<Polynomial<C1,O1>,F1s...>,
	     Composition<Polynomial<C2,O2>,F1s...>>, 1,
    typename std::enable_if<
      is_stateless<Composition<F1s...>>::value>::type>
  {
    typedef Variadic<Polynomial<C1,O1>,
		     Polynomial<C2,O2>> inter_type;
    typedef Composition<
      inter_type,
      F1s...> type;
    static type Combine(Variadic<Composition<
			Polynomial<C1,O1>,F1s...>,
			Composition<
			Polynomial<C2,O2>,F1s...>> v)
    {
#ifdef PRINT_SIMPLIFIES
      std::cout << "Simplifying operation on "
	"polynomials composed by same functions\n";
#endif
      auto t = v.GetFunctions();
      inter_type i(get<0>(get<0>(t).GetFunctions()),
		   get<0>(get<1>(t).GetFunctions()));
      return make_my_tuple(i, F1s()...);
    }
    };*/

  template <class C, class O, class ... Fs>
  struct Simplification<
    Composition<
      Polynomial<C,O>, Addition<Fs...> >, 3>
  {
    typedef Composition<
      Polynomial<C,O>, Addition<Fs...> > in_type;

    static auto P(C c){return GetPolynomial(c);}

    template <class T, std::size_t>
    struct Dummy
    {
      typedef T type;
    };

    template <std::size_t ... count>
    static auto Mult(C c, Addition<Fs...> a,
		     std::integer_sequence<std::size_t, count...>)
    {
      auto p = P(c);
      Multiplication<
	decltype(p),
	typename Dummy<Addition<Fs...>,
		       count>::type...>
	r(P(c), ((void)count, a)...);
      return r;
    }

    template <std::size_t ... orders>
    static auto Addem(in_type c, std::integer_sequence<
		      std::size_t, orders...>)
    {
      auto a = get<1>(c.GetFunctions());
      auto coeffs = get<0>(c.GetFunctions()).GetCoeffs();
      return Add(Mult(coeffs[orders], a,
		      std::make_index_sequence<orders>())...);
    }

    static auto Combine(in_type c)
    {
#ifndef PRINT_SIMPLIFIES
      std::cout << "Simplifying polynomial of addition of "
	"functions\n";
#endif
      return Addem(c, std::make_index_sequence<O::value>());
    }
  };
}

#endif
<|endoftext|>


<commit_before>#include "Server.h"
#include "Var_for_threads.h"
#include "Interrupt.h"

/*******************************************************************************/
vector<string> my_gList;
mutex glist_mutex;
condition_variable gdata_cond;

/*******************************************************************************/
void send_data(SOCKET& client_socket)
{
	int index = 0;

	while(true)
	{
		unique_lock<mutex> u_mutex(glist_mutex);

			/*gdata_cond.wait(u_mutex, [&index]{return (index < my_gList.size());});*/
			interruptible_wait(gdata_cond, u_mutex, [&index]{return (index < my_gList.size());});
			my_send(client_socket, my_gList[index]);
			++index;

		u_mutex.unlock();
	}

}

/*******************************************************************************/
int recv_data(string& data)
{
	int result = websocket_get_content(data, data.size()); //

	if(result == 1)
	{
		return 1;
	}

	websocket_set_content(data, data.size(), result); //

	lock_guard<mutex> guard(glist_mutex);

	my_gList.push_back(data); //
	gdata_cond.notify_all(); //

	return 0;
}<commit_msg>Delete Functions_inside_thread.cpp<commit_after><|endoftext|>


<commit_before>#define DEBUG 1
/**
 * File    : D.cpp
 * Author  : Kazune Takahashi
 * Created : 2020/1/11 20:56:20
 * Powered by Visual Studio Code
 */
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using boost::rational;
using boost::multiprecision::cpp_int;
using namespace std;
using ll = long long;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1000000007LL};
// constexpr ll MOD{998244353LL}; // be careful
constexpr ll MAX_SIZE{3000010LL};
// constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
  if (left < right)
  {
    left = right;
  }
}
template <typename T>
void ch_min(T &left, T right)
{
  if (left > right)
  {
    left = right;
  }
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
  ll x;
  Mint() : x{0LL} {}
  Mint(ll x) : x{x % MOD} {}
  Mint operator-() const { return x ? MOD - x : 0; }
  Mint &operator+=(const Mint &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  Mint &operator-=(const Mint &a) { return *this += -a; }
  Mint &operator*=(const Mint &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  Mint &operator/=(const Mint &a)
  {
    Mint b{a};
    return *this *= b.power(MOD - 2);
  }
  Mint operator+(const Mint &a) const { return Mint(*this) += a; }
  Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
  Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
  Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
  bool operator<(const Mint &a) const { return x < a.x; }
  bool operator<=(const Mint &a) const { return x <= a.x; }
  bool operator>(const Mint &a) const { return x > a.x; }
  bool operator>=(const Mint &a) const { return x >= a.x; }
  bool operator==(const Mint &a) const { return x == a.x; }
  bool operator!=(const Mint &a) const { return !(*this == a); }
  const Mint power(ll N)
  {
    if (N == 0)
    {
      return 1;
    }
    else if (N % 2 == 1)
    {
      return *this * power(N - 1);
    }
    else
    {
      Mint half = power(N / 2);
      return half * half;
    }
  }
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
  return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
  return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
  return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
  return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
  return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
  return stream << a.x;
}
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
  vector<Mint<MOD>> inv, fact, factinv;
  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
  {
    inv[1] = 1;
    for (auto i = 2LL; i < MAX_SIZE; i++)
    {
      inv[i] = (-inv[MOD % i]) * (MOD / i);
    }
    fact[0] = factinv[0] = 1;
    for (auto i = 1LL; i < MAX_SIZE; i++)
    {
      fact[i] = Mint<MOD>(i) * fact[i - 1];
      factinv[i] = inv[i] * factinv[i - 1];
    }
  }
  Mint<MOD> operator()(int n, int k)
  {
    if (n >= 0 && k >= 0 && n - k >= 0)
    {
      return fact[n] * factinv[k] * factinv[n - k];
    }
    return 0;
  }
  Mint<MOD> catalan(int x, int y)
  {
    return (*this)(x + y, y) - (*this)(x + y, y - 1);
  }
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
ll lcm(ll x, ll y) { return x / gcd(x, y) * y; }
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
  cout << "Yes" << endl;
  exit(0);
}
void No()
{
  cout << "-1" << endl;
  exit(0);
}
// ----- main() -----
int main()
{
  int N;
  cin >> N;
  vector<int> A(N);
  if (N == 2)
  {
    No();
  }
  for (auto i = 0; i < N; i++)
  {
    cin >> A[i];
    A[i]--;
  }
  set<int> S;
  for (auto i = 0; i < N; i++)
  {
    S.insert(i);
  }
  vector<int> B;
  while (S.size() > 3)
  {
    auto it{S.begin()};
    if (!B.empty() && A[B.back()] == *it)
    {
      ++it;
    }
    B.push_back(*it);
    S.erase(it);
  }
  vector<int> V;
  copy(S.begin(), S.end(), back_inserter(V));
  // assert(static_cast<int>(V.size()) == 3);
  do
  {
    if (A[B.back()] != V[0] && A[V[0]] != V[1] && A[V[1]] != V[2])
    {
      copy(V.begin(), V.end(), back_inserter(B));
      break;
    }
  } while (next_permutation(V.begin(), V.end()));
  for (auto i = 0; i < N; i++)
  {
    cout << B[i] + 1;
    if (i < N - 1)
    {
      cout << " ";
    }
    else
    {
      cout << endl;
    }
  }
}
<commit_msg>submit D.cpp to 'D - Arrangement' (dwacon6th-prelims) [C++14 (GCC 5.4.1)]<commit_after>#define DEBUG 1
/**
 * File    : D.cpp
 * Author  : Kazune Takahashi
 * Created : 2020/1/11 20:56:20
 * Powered by Visual Studio Code
 */
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using boost::rational;
using boost::multiprecision::cpp_int;
using namespace std;
using ll = long long;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1000000007LL};
// constexpr ll MOD{998244353LL}; // be careful
constexpr ll MAX_SIZE{3000010LL};
// constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
  if (left < right)
  {
    left = right;
  }
}
template <typename T>
void ch_min(T &left, T right)
{
  if (left > right)
  {
    left = right;
  }
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
  ll x;
  Mint() : x{0LL} {}
  Mint(ll x) : x{x % MOD} {}
  Mint operator-() const { return x ? MOD - x : 0; }
  Mint &operator+=(const Mint &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  Mint &operator-=(const Mint &a) { return *this += -a; }
  Mint &operator*=(const Mint &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  Mint &operator/=(const Mint &a)
  {
    Mint b{a};
    return *this *= b.power(MOD - 2);
  }
  Mint operator+(const Mint &a) const { return Mint(*this) += a; }
  Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
  Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
  Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
  bool operator<(const Mint &a) const { return x < a.x; }
  bool operator<=(const Mint &a) const { return x <= a.x; }
  bool operator>(const Mint &a) const { return x > a.x; }
  bool operator>=(const Mint &a) const { return x >= a.x; }
  bool operator==(const Mint &a) const { return x == a.x; }
  bool operator!=(const Mint &a) const { return !(*this == a); }
  const Mint power(ll N)
  {
    if (N == 0)
    {
      return 1;
    }
    else if (N % 2 == 1)
    {
      return *this * power(N - 1);
    }
    else
    {
      Mint half = power(N / 2);
      return half * half;
    }
  }
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
  return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
  return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
  return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
  return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
  return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
  return stream << a.x;
}
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
  vector<Mint<MOD>> inv, fact, factinv;
  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
  {
    inv[1] = 1;
    for (auto i = 2LL; i < MAX_SIZE; i++)
    {
      inv[i] = (-inv[MOD % i]) * (MOD / i);
    }
    fact[0] = factinv[0] = 1;
    for (auto i = 1LL; i < MAX_SIZE; i++)
    {
      fact[i] = Mint<MOD>(i) * fact[i - 1];
      factinv[i] = inv[i] * factinv[i - 1];
    }
  }
  Mint<MOD> operator()(int n, int k)
  {
    if (n >= 0 && k >= 0 && n - k >= 0)
    {
      return fact[n] * factinv[k] * factinv[n - k];
    }
    return 0;
  }
  Mint<MOD> catalan(int x, int y)
  {
    return (*this)(x + y, y) - (*this)(x + y, y - 1);
  }
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
ll lcm(ll x, ll y) { return x / gcd(x, y) * y; }
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
  cout << "Yes" << endl;
  exit(0);
}
void No()
{
  cout << "-1" << endl;
  exit(0);
}
// ----- main() -----
int main()
{
  int N;
  cin >> N;
  vector<int> A(N);
  if (N == 2)
  {
    No();
  }
  for (auto i = 0; i < N; i++)
  {
    cin >> A[i];
    A[i]--;
  }
  set<int> S;
  for (auto i = 0; i < N; i++)
  {
    S.insert(i);
  }
  vector<int> B;
  while (S.size() > 3)
  {
    auto it{S.begin()};
    if (!B.empty() && A[B.back()] == *it)
    {
      ++it;
    }
    B.push_back(*it);
    S.erase(it);
  }
  vector<int> V;
  copy(S.begin(), S.end(), back_inserter(V));
  assert(static_cast<int>(V.size()) == 3);
  do
  {
    if (A[B.back()] != V[0] && A[V[0]] != V[1] && A[V[1]] != V[2])
    {
      copy(V.begin(), V.end(), back_inserter(B));
      break;
    }
  } while (next_permutation(V.begin(), V.end()));
  if (static_cast<int>(B.size()) != N)
  {
    sleep(100);
  }
  for (auto i = 0; i < N; i++)
  {
    cout << B[i] + 1;
    if (i < N - 1)
    {
      cout << " ";
    }
    else
    {
      cout << endl;
    }
  }
}
<|endoftext|>


<commit_before>#include <ros/ros.h>
#include <sensor_msgs/Image.h>
#include <camera_info_manager/camera_info_manager.h>
#include <ros/publisher.h>
#include <opencv2/video/video.hpp>
#include <opencv2/opencv.hpp>
#include <image_transport/image_transport.h>
#include <cv_bridge/cv_bridge.h>

// ros::Publisher info_pub;
// camera_info_manager::CameraInfoManager* cameraManager;

using namespace cv;
cv_bridge::CvImagePtr cv_ptr;
image_transport::Publisher _new_img;

void callback(const sensor_msgs::ImageConstPtr& msg) {

    // sensor_msgs::CameraInfo cl = cameraManager->getCameraInfo();
    // cl.header.frame_id = "/usb_cam";
    // cl.header.stamp = msg->header.stamp;
    // cameraManager->setCameraInfo(cl);

    // info_pub.publish(cameraManager->getCameraInfo());

    cv_ptr = cv_bridge::toCvCopy(msg, "");
    Mat image = (cv_ptr->image).clone();

    // To access an element in the image (aka a pixel)
    // image.at<double>(x, y);

    // All of my code goes here
    Mat dst;

    vector<Mat> bgr_planes;
    split(image, bgr_planes);

    int histSize = 256;
    float range[] = {0, 256};
    const float* histRange = {range};
    bool uniform = true;
    bool accumulate = false;

    Mat b_hist, g_hist, r_hist;

    calcHist( &bgr_planes[0], 1, 0, Mat(), b_hist, 1, &histSize, &histRange, uniform, accumulate );
    calcHist( &bgr_planes[1], 1, 0, Mat(), g_hist, 1, &histSize, &histRange, uniform, accumulate );
    calcHist( &bgr_planes[2], 1, 0, Mat(), r_hist, 1, &histSize, &histRange, uniform, accumulate );

    int hist_w = 512; int hist_h = 400;
    int bin_w = cvRound( (double) hist_w/histSize );

    Mat histImage( hist_h, hist_w, CV_8UC3, Scalar( 0,0,0) );

    normalize(b_hist, b_hist, 0, histImage.rows, NORM_MINMAX, -1, Mat() );
    normalize(g_hist, g_hist, 0, histImage.rows, NORM_MINMAX, -1, Mat() );
    normalize(r_hist, r_hist, 0, histImage.rows, NORM_MINMAX, -1, Mat() );

    for( int i = 1; i < histSize; i++ ) {
        line( histImage, Point( bin_w*(i-1), hist_h - cvRound(b_hist.at<float>(i-1)) ) ,
                         Point( bin_w*(i), hist_h - cvRound(b_hist.at<float>(i)) ),
                         Scalar( 255, 0, 0), 2, 8, 0  );
        line( histImage, Point( bin_w*(i-1), hist_h - cvRound(g_hist.at<float>(i-1)) ) ,
                         Point( bin_w*(i), hist_h - cvRound(g_hist.at<float>(i)) ),
                         Scalar( 0, 255, 0), 2, 8, 0  );
        line( histImage, Point( bin_w*(i-1), hist_h - cvRound(r_hist.at<float>(i-1)) ) ,
                         Point( bin_w*(i), hist_h - cvRound(r_hist.at<float>(i)) ),
                         Scalar( 0, 0, 255), 2, 8, 0  );
    }

    namedWindow("calcHist Demo", CV_WINDOW_AUTOSIZE );
    imshow("calcHist Demo", histImage );

    cv_ptr->image = histImage;
    _new_img.publish(cv_ptr->toImageMsg());
}

int main(int argc, char** argv) {
    ros::init(argc, argv, "webcam");
    ros::NodeHandle nh;

    // cameraManager = new camera_info_manager::CameraInfoManager(ros::NodeHandle("/usb_cam"), "/usb_cam", "file:///home/nareddyt/Desktop/cal.yml");
    // info_pub = nh.advertise<sensor_msgs::CameraInfo>("/usb_cam/camera_info", 1);

    ros::Subscriber sub = nh.subscribe("/usb_cam/image_raw", 1, callback);

    image_transport::ImageTransport _it(nh);
    _new_img = _it.advertise("/new_img", 1);

    ros::spin();
}<commit_msg>Modified webcam to start working on overhead image rectification<commit_after>#include <ros/ros.h>
#include <sensor_msgs/Image.h>
#include <camera_info_manager/camera_info_manager.h>
#include <ros/publisher.h>
#include <opencv2/video/video.hpp>
#include <opencv2/opencv.hpp>
#include <image_transport/image_transport.h>
#include <cv_bridge/cv_bridge.h>
#include <stdio.h>
#include <iostream>
#include "opencv2/core/core.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/calib3d/calib3d.hpp"

// ros::Publisher info_pub;
// camera_info_manager::CameraInfoManager* cameraManager;

using namespace cv;
cv_bridge::CvImagePtr cv_ptr;
image_transport::Publisher _new_img;

void callback(const sensor_msgs::ImageConstPtr& msg) {
    cv_ptr = cv_bridge::toCvCopy(msg, "");
    Mat image = (cv_ptr->image).clone();

    // All of my code goes here
    Mat img_overhead = imread("overhead.jpg", CV_LOAD_IMAGE_GRAYSCALE );
    Mat img_normal = imread("normal.jpg", CV_LOAD_IMAGE_GRAYSCALE );

    // namedWindow("calcHist Demo", CV_WINDOW_AUTOSIZE );
    // imshow("calcHist Demo", histImage );

    cv_ptr->image = img_normal;
    _new_img.publish(cv_ptr->toImageMsg());
}

int main(int argc, char** argv) {
    ros::init(argc, argv, "webcam");
    ros::NodeHandle nh;

    // cameraManager = new camera_info_manager::CameraInfoManager(ros::NodeHandle("/usb_cam"), "/usb_cam", "file:///home/nareddyt/Desktop/cal.yml");
    // info_pub = nh.advertise<sensor_msgs::CameraInfo>("/usb_cam/camera_info", 1);

    ros::Subscriber sub = nh.subscribe("/usb_cam/image_raw", 1, callback);

    image_transport::ImageTransport _it(nh);
    _new_img = _it.advertise("/new_img", 1);

    ros::spin();
}<|endoftext|>


<commit_before>// This file is distributed under the MIT license.
// See the LICENSE file for details.

#pragma once

#ifndef VSNRAY_DETAIL_SIMPLE_INL
#define VSNRAY_DETAIL_SIMPLE_INL 1

#include <visionaray/get_surface.h>
#include <visionaray/result_record.h>
#include <visionaray/traverse.h>

namespace visionaray
{
namespace simple
{

template <typename Params>
struct kernel
{

    Params params;

    template <typename Intersector, typename R>
    VSNRAY_FUNC result_record<typename R::scalar_type> operator()(Intersector& isect, R ray) const
    {
        using S = typename R::scalar_type;
        using V = typename result_record<S>::vec_type;
        using C = spectrum<S>;

        result_record<S> result;

        auto hit_rec = closest_hit(ray, params.prims.begin, params.prims.end, isect);

        if (any(hit_rec.hit))
        {
            hit_rec.isect_pos = ray.ori + ray.dir * hit_rec.t;

            auto surf = get_surface(hit_rec, params);
            auto ambient = surf.material.ambient() * C(from_rgba(params.ambient_color));
            auto shaded_clr = select( hit_rec.hit, ambient, C(from_rgba(params.bg_color)) );
            auto view_dir = -ray.dir;

            for (auto it = params.lights.begin; it != params.lights.end; ++it)
            {
                auto sr             = make_shade_record<Params, S>();
                sr.isect_pos        = hit_rec.isect_pos;
                sr.normal           = surf.shading_normal;
                sr.geometric_normal = surf.geometric_normal;
                sr.view_dir         = -ray.dir;
                sr.light_dir        = normalize( V(it->position()) - hit_rec.isect_pos );
                sr.light            = *it;
                auto clr            = surf.shade(sr);

                shaded_clr     += select( hit_rec.hit, clr, C(0.0) );
            }

            result.color        = select( hit_rec.hit, to_rgba(shaded_clr), params.bg_color );
            result.isect_pos    = hit_rec.isect_pos;
        }
        else
        {
            result.color = params.bg_color;
        }

        result.hit = hit_rec.hit;
        return result;
    }

    template <typename R>
    VSNRAY_FUNC result_record<typename R::scalar_type> operator()(R ray) const
    {
        default_intersector ignore;
        return (*this)(ignore, ray);
    }
};

} // simple
} // visionaray

#endif // VSNRAY_DETAIL_SIMPLE_INL
<commit_msg>Unused variable<commit_after>// This file is distributed under the MIT license.
// See the LICENSE file for details.

#pragma once

#ifndef VSNRAY_DETAIL_SIMPLE_INL
#define VSNRAY_DETAIL_SIMPLE_INL 1

#include <visionaray/get_surface.h>
#include <visionaray/result_record.h>
#include <visionaray/traverse.h>

namespace visionaray
{
namespace simple
{

template <typename Params>
struct kernel
{

    Params params;

    template <typename Intersector, typename R>
    VSNRAY_FUNC result_record<typename R::scalar_type> operator()(Intersector& isect, R ray) const
    {
        using S = typename R::scalar_type;
        using V = typename result_record<S>::vec_type;
        using C = spectrum<S>;

        result_record<S> result;

        auto hit_rec = closest_hit(ray, params.prims.begin, params.prims.end, isect);

        if (any(hit_rec.hit))
        {
            hit_rec.isect_pos = ray.ori + ray.dir * hit_rec.t;

            auto surf = get_surface(hit_rec, params);
            auto ambient = surf.material.ambient() * C(from_rgba(params.ambient_color));
            auto shaded_clr = select( hit_rec.hit, ambient, C(from_rgba(params.bg_color)) );

            for (auto it = params.lights.begin; it != params.lights.end; ++it)
            {
                auto sr             = make_shade_record<Params, S>();
                sr.isect_pos        = hit_rec.isect_pos;
                sr.normal           = surf.shading_normal;
                sr.geometric_normal = surf.geometric_normal;
                sr.view_dir         = -ray.dir;
                sr.light_dir        = normalize( V(it->position()) - hit_rec.isect_pos );
                sr.light            = *it;
                auto clr            = surf.shade(sr);

                shaded_clr     += select( hit_rec.hit, clr, C(0.0) );
            }

            result.color        = select( hit_rec.hit, to_rgba(shaded_clr), params.bg_color );
            result.isect_pos    = hit_rec.isect_pos;
        }
        else
        {
            result.color = params.bg_color;
        }

        result.hit = hit_rec.hit;
        return result;
    }

    template <typename R>
    VSNRAY_FUNC result_record<typename R::scalar_type> operator()(R ray) const
    {
        default_intersector ignore;
        return (*this)(ignore, ray);
    }
};

} // simple
} // visionaray

#endif // VSNRAY_DETAIL_SIMPLE_INL
<|endoftext|>