<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/.
 */

#include "oglplayer.hxx"
#include "oglframegrabber.hxx"
#include "oglwindow.hxx"

#include <cppuhelper/supportsservice.hxx>
#include <tools/stream.hxx>
#include <vcl/graph.hxx>
#include <vcl/graphicfilter.hxx>
#include <tools/urlobj.hxx>
#include <vcl/opengl/OpenGLHelper.hxx>

using namespace com::sun::star;

namespace avmedia { namespace ogl {

OGLPlayer::OGLPlayer()
    : Player_BASE(m_aMutex)
    , m_pHandle(NULL)
    , m_pOGLWindow(NULL)
{
}

OGLPlayer::~OGLPlayer()
{
    osl::MutexGuard aGuard(m_aMutex);
    if( m_pHandle )
    {
        for (size_t i = 0; i < m_pHandle->size; ++i)
        {
            if (m_pHandle->files[i].type != GLTF_JSON)
            {
                delete [] m_pHandle->files[i].buffer;
            }
        }
        gltf_renderer_release(m_pHandle);
    }
}

static bool lcl_LoadFile( glTFFile* io_pFile, const OUString& rURL)
{
    SvFileStream aStream( rURL, STREAM_READ );
    if( !aStream.IsOpen() )
        return false;

    const sal_Int64 nBytes = aStream.remainingSize();
    char* pBuffer = new char[nBytes];
    aStream.Read( pBuffer, nBytes );
    aStream.Close();

    io_pFile->buffer = pBuffer;
    io_pFile->size = nBytes;

    return true;
}

bool OGLPlayer::create( const OUString& rURL )
{
    osl::MutexGuard aGuard(m_aMutex);

    m_sURL = rURL;

    // Load *.json file and init renderer
    glTFFile aJsonFile;
    aJsonFile.type = GLTF_JSON;
    OString sFileName = OUStringToOString(INetURLObject(m_sURL).GetLastName(),RTL_TEXTENCODING_UTF8);
    aJsonFile.filename = (char*)sFileName.getStr();
    if( !lcl_LoadFile(&aJsonFile, m_sURL) )
    {
        SAL_WARN("avmedia.opengl", "Can't load *.json file: " + sFileName);
        return false;
    }

    m_pHandle = gltf_renderer_init(&aJsonFile);

    delete [] aJsonFile.buffer;

    if( !m_pHandle || !m_pHandle->files )
    {
        SAL_WARN("avmedia.opengl", "gltf_renderer_init returned an invalid glTFHandle");
        return false;
    }

    // Load external resources
    for( size_t i = 0; i < m_pHandle->size; ++i )
    {
        glTFFile& rFile = m_pHandle->files[i];
        if( rFile.filename )
        {
            const OUString sFilesURL =
                INetURLObject::GetAbsURL(m_sURL,OStringToOUString(OString(rFile.filename),RTL_TEXTENCODING_UTF8));
            if( rFile.type == GLTF_IMAGE )
            {
                // Load images as bitmaps
                GraphicFilter aFilter;
                Graphic aGraphic;
                if( aFilter.ImportGraphic(aGraphic, INetURLObject(sFilesURL)) != GRFILTER_OK )
                {
                    rFile.buffer = 0;
                    rFile.imagewidth = 0;
                    rFile.imageheight = 0;
                    SAL_WARN("avmedia.opengl", "Can't load texture file: " + sFilesURL);
                    return false;
                }
                BitmapEx aBitmapEx = aGraphic.GetBitmapEx();
                aBitmapEx.Mirror(BMP_MIRROR_VERT);
                rFile.buffer = (char*)OpenGLHelper::ConvertBitmapExToRGBABuffer(aBitmapEx);
                rFile.imagewidth = aBitmapEx.GetSizePixel().Width();
                rFile.imageheight = aBitmapEx.GetSizePixel().Height();
            }
            else if( rFile.type == GLTF_BINARY || rFile.type == GLTF_GLSL )
            {
                if( !lcl_LoadFile(&rFile, sFilesURL) )
                {
                    rFile.buffer = 0;
                    rFile.size = 0;
                    SAL_WARN("avmedia.opengl", "Can't load glTF file: " + sFilesURL);
                    return false;
                }
            }
        }
    }

    // Set timer
    m_aTimer.SetTimeout(10);
    m_aTimer.SetTimeoutHdl(LINK(this,OGLPlayer,TimerHandler));
    return true;
}

void SAL_CALL OGLPlayer::start() throw ( uno::RuntimeException, std::exception )
{
    osl::MutexGuard aGuard(m_aMutex);
    gltf_animation_start(m_pHandle);
    m_aTimer.Start();
}

void SAL_CALL OGLPlayer::stop() throw ( uno::RuntimeException, std::exception )
{
    osl::MutexGuard aGuard(m_aMutex);
    m_aTimer.Stop();
    gltf_animation_stop(m_pHandle);
}

sal_Bool SAL_CALL OGLPlayer::isPlaying() throw ( uno::RuntimeException, std::exception )
{
    osl::MutexGuard aGuard(m_aMutex);
    return (sal_Bool)gltf_animation_is_playing(m_pHandle);
}

double SAL_CALL OGLPlayer::getDuration() throw ( uno::RuntimeException, std::exception )
{
    osl::MutexGuard aGuard(m_aMutex);
    return gltf_animation_get_duration(m_pHandle);
}

void SAL_CALL OGLPlayer::setMediaTime( double fTime ) throw ( uno::RuntimeException, std::exception )
{
    // TODO: doesn't work, but cause problem in playing
    osl::MutexGuard aGuard(m_aMutex);
    (void) fTime;
    //gltf_animation_set_time(m_pHandle, fTime);
}

double SAL_CALL OGLPlayer::getMediaTime() throw ( ::com::sun::star::uno::RuntimeException, std::exception )
{
    osl::MutexGuard aGuard(m_aMutex);
    return 0.0; //gltf_animation_get_time(m_pHandle);
}

void SAL_CALL OGLPlayer::setPlaybackLoop( sal_Bool bSet ) throw ( uno::RuntimeException, std::exception )
{
    osl::MutexGuard aGuard(m_aMutex);
    gltf_animation_set_looping(m_pHandle, (int)bSet);
}

sal_Bool SAL_CALL OGLPlayer::isPlaybackLoop() throw ( uno::RuntimeException, std::exception )
{
    osl::MutexGuard aGuard(m_aMutex);
    return (sal_Bool)gltf_animation_get_looping(m_pHandle);
}

void SAL_CALL OGLPlayer::setVolumeDB( sal_Int16 /*nVolumDB*/ ) throw ( uno::RuntimeException, std::exception )
{
    // OpenGL models have no sound.
}

sal_Int16 SAL_CALL OGLPlayer::getVolumeDB() throw ( uno::RuntimeException, std::exception )
{
    // OpenGL models have no sound.
    return 0;
}

void SAL_CALL OGLPlayer::setMute( sal_Bool /*bSet*/ ) throw ( uno::RuntimeException, std::exception )
{
    // OpenGL models have no sound.
}

sal_Bool SAL_CALL OGLPlayer::isMute() throw ( uno::RuntimeException, std::exception )
{
    // OpenGL models have no sound.
    return false;
}

awt::Size SAL_CALL OGLPlayer::getPreferredPlayerWindowSize() throw ( uno::RuntimeException, std::exception )
{
    return awt::Size( 480, 360 );
}

uno::Reference< media::XPlayerWindow > SAL_CALL OGLPlayer::createPlayerWindow( const uno::Sequence< uno::Any >& rArguments )
     throw ( uno::RuntimeException, std::exception )
{
    osl::MutexGuard aGuard( m_aMutex );

    assert( rArguments.getLength() >= 3 );

    sal_IntPtr pIntPtr = 0;
    rArguments[ 2 ] >>= pIntPtr;
    SystemChildWindow *pChildWindow = reinterpret_cast< SystemChildWindow* >( pIntPtr );

    if( !m_aContext.init(pChildWindow) )
    {
        SAL_WARN("avmedia.opengl", "Context initialization failed");
        return uno::Reference< media::XPlayerWindow >();
    }

    Size aSize = pChildWindow->GetSizePixel();
    m_aContext.setWinSize(aSize);
    m_pHandle->viewport.x = 0;
    m_pHandle->viewport.y = 0;
    m_pHandle->viewport.width = aSize.Width();
    m_pHandle->viewport.height = aSize.Height();

    // TODO: In libgltf different return values are defined (for different errors)
    // but these error codes are not part of the library interface
    int nRet = gltf_renderer_set_content(m_pHandle);
    if( nRet != 0 )
    {
        SAL_WARN("avmedia.opengl", "Error occured while parsing *.json file! Error code: " << nRet);
        return uno::Reference< media::XPlayerWindow >();
    }
    m_pOGLWindow = new OGLWindow(m_pHandle, &m_aContext, pChildWindow);
    return uno::Reference< media::XPlayerWindow >( m_pOGLWindow );
}

uno::Reference< media::XFrameGrabber > SAL_CALL OGLPlayer::createFrameGrabber()
     throw ( uno::RuntimeException, std::exception )
{
    osl::MutexGuard aGuard(m_aMutex);

    if( !m_aContext.init() )
    {
        SAL_WARN("avmedia.opengl", "Offscreen context initialization failed");
        return uno::Reference< media::XFrameGrabber >();
    }

    m_pHandle->viewport.x = 0;
    m_pHandle->viewport.y = 0;
    m_pHandle->viewport.width = getPreferredPlayerWindowSize().Width;
    m_pHandle->viewport.height = getPreferredPlayerWindowSize().Height;

    int nRet = gltf_renderer_set_content(m_pHandle);
    if( nRet != 0 )
    {
        SAL_WARN("avmedia.opengl", "Error occured while parsing *.json file! Error code: " << nRet);
        return uno::Reference< media::XFrameGrabber >();
    }
    OGLFrameGrabber *pFrameGrabber = new OGLFrameGrabber( m_pHandle );
    return uno::Reference< media::XFrameGrabber >( pFrameGrabber );
}

OUString SAL_CALL OGLPlayer::getImplementationName()
     throw ( ::com::sun::star::uno::RuntimeException, std::exception )
{
    return OUString("com.sun.star.comp.avmedia.Player_OpenGL");
}

sal_Bool SAL_CALL OGLPlayer::supportsService( const OUString& rServiceName )
     throw ( uno::RuntimeException, std::exception )
{
    return cppu::supportsService(this, rServiceName);
}

uno::Sequence< OUString > SAL_CALL OGLPlayer::getSupportedServiceNames()
     throw ( uno::RuntimeException, std::exception )
{
    uno::Sequence< OUString > aRet(1);
    aRet[0] = OUString("com.sun.star.media.Player_OpenGL");
    return aRet;
}

IMPL_LINK(OGLPlayer,TimerHandler,Timer*,pTimer)
{
    if (pTimer == &m_aTimer)
    {
        osl::MutexGuard aGuard(m_aMutex);
        m_pOGLWindow->update();
    }

    return 0;
}

} // namespace ogl
} // namespace avmedia

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>OGLPlayer: use more assertions<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/.
 */

#include "oglplayer.hxx"
#include "oglframegrabber.hxx"
#include "oglwindow.hxx"

#include <cppuhelper/supportsservice.hxx>
#include <tools/stream.hxx>
#include <vcl/graph.hxx>
#include <vcl/graphicfilter.hxx>
#include <tools/urlobj.hxx>
#include <vcl/opengl/OpenGLHelper.hxx>

#include <cassert>

using namespace com::sun::star;

namespace avmedia { namespace ogl {

OGLPlayer::OGLPlayer()
    : Player_BASE(m_aMutex)
    , m_pHandle(NULL)
    , m_pOGLWindow(NULL)
{
}

OGLPlayer::~OGLPlayer()
{
    osl::MutexGuard aGuard(m_aMutex);
    if( m_pHandle )
    {
        for (size_t i = 0; i < m_pHandle->size; ++i)
        {
            if (m_pHandle->files[i].type != GLTF_JSON)
            {
                delete [] m_pHandle->files[i].buffer;
            }
        }
        gltf_renderer_release(m_pHandle);
    }
}

static bool lcl_LoadFile( glTFFile* io_pFile, const OUString& rURL)
{
    SvFileStream aStream( rURL, STREAM_READ );
    if( !aStream.IsOpen() )
        return false;

    const sal_Int64 nBytes = aStream.remainingSize();
    char* pBuffer = new char[nBytes];
    aStream.Read( pBuffer, nBytes );
    aStream.Close();

    io_pFile->buffer = pBuffer;
    io_pFile->size = nBytes;

    return true;
}

bool OGLPlayer::create( const OUString& rURL )
{
    osl::MutexGuard aGuard(m_aMutex);

    m_sURL = rURL;

    // Load *.json file and init renderer
    glTFFile aJsonFile;
    aJsonFile.type = GLTF_JSON;
    OString sFileName = OUStringToOString(INetURLObject(m_sURL).GetLastName(),RTL_TEXTENCODING_UTF8);
    aJsonFile.filename = (char*)sFileName.getStr();
    if( !lcl_LoadFile(&aJsonFile, m_sURL) )
    {
        SAL_WARN("avmedia.opengl", "Can't load *.json file: " + sFileName);
        return false;
    }

    m_pHandle = gltf_renderer_init(&aJsonFile);

    delete [] aJsonFile.buffer;

    if( !m_pHandle || !m_pHandle->files )
    {
        SAL_WARN("avmedia.opengl", "gltf_renderer_init returned an invalid glTFHandle");
        return false;
    }

    // Load external resources
    for( size_t i = 0; i < m_pHandle->size; ++i )
    {
        glTFFile& rFile = m_pHandle->files[i];
        if( rFile.filename )
        {
            const OUString sFilesURL =
                INetURLObject::GetAbsURL(m_sURL,OStringToOUString(OString(rFile.filename),RTL_TEXTENCODING_UTF8));
            if( rFile.type == GLTF_IMAGE )
            {
                // Load images as bitmaps
                GraphicFilter aFilter;
                Graphic aGraphic;
                if( aFilter.ImportGraphic(aGraphic, INetURLObject(sFilesURL)) != GRFILTER_OK )
                {
                    rFile.buffer = 0;
                    rFile.imagewidth = 0;
                    rFile.imageheight = 0;
                    SAL_WARN("avmedia.opengl", "Can't load texture file: " + sFilesURL);
                    return false;
                }
                BitmapEx aBitmapEx = aGraphic.GetBitmapEx();
                aBitmapEx.Mirror(BMP_MIRROR_VERT);
                rFile.buffer = (char*)OpenGLHelper::ConvertBitmapExToRGBABuffer(aBitmapEx);
                rFile.imagewidth = aBitmapEx.GetSizePixel().Width();
                rFile.imageheight = aBitmapEx.GetSizePixel().Height();
            }
            else if( rFile.type == GLTF_BINARY || rFile.type == GLTF_GLSL )
            {
                if( !lcl_LoadFile(&rFile, sFilesURL) )
                {
                    rFile.buffer = 0;
                    rFile.size = 0;
                    SAL_WARN("avmedia.opengl", "Can't load glTF file: " + sFilesURL);
                    return false;
                }
            }
        }
    }

    // Set timer
    m_aTimer.SetTimeout(10);
    m_aTimer.SetTimeoutHdl(LINK(this,OGLPlayer,TimerHandler));
    return true;
}

void SAL_CALL OGLPlayer::start() throw ( uno::RuntimeException, std::exception )
{
    osl::MutexGuard aGuard(m_aMutex);
    assert(m_pHandle);
    gltf_animation_start(m_pHandle);
    m_aTimer.Start();
}

void SAL_CALL OGLPlayer::stop() throw ( uno::RuntimeException, std::exception )
{
    osl::MutexGuard aGuard(m_aMutex);
    assert(m_pHandle);
    gltf_animation_stop(m_pHandle);
    m_aTimer.Stop();
    gltf_animation_stop(m_pHandle);
}

sal_Bool SAL_CALL OGLPlayer::isPlaying() throw ( uno::RuntimeException, std::exception )
{
    osl::MutexGuard aGuard(m_aMutex);
    assert(m_pHandle);
    return (sal_Bool)gltf_animation_is_playing(m_pHandle);
}

double SAL_CALL OGLPlayer::getDuration() throw ( uno::RuntimeException, std::exception )
{
    osl::MutexGuard aGuard(m_aMutex);
    assert(m_pHandle);
    return gltf_animation_get_duration(m_pHandle);
}

void SAL_CALL OGLPlayer::setMediaTime( double fTime ) throw ( uno::RuntimeException, std::exception )
{
    // TODO: doesn't work, but cause problem in playing
    osl::MutexGuard aGuard(m_aMutex);
    assert(m_pHandle);
    (void) fTime;
    //gltf_animation_set_time(m_pHandle, fTime);
}

double SAL_CALL OGLPlayer::getMediaTime() throw ( ::com::sun::star::uno::RuntimeException, std::exception )
{
    osl::MutexGuard aGuard(m_aMutex);
    assert(m_pHandle);
    return 0.0; //gltf_animation_get_time(m_pHandle);
}

void SAL_CALL OGLPlayer::setPlaybackLoop( sal_Bool bSet ) throw ( uno::RuntimeException, std::exception )
{
    osl::MutexGuard aGuard(m_aMutex);
    assert(m_pHandle);
    gltf_animation_set_looping(m_pHandle, (int)bSet);
}

sal_Bool SAL_CALL OGLPlayer::isPlaybackLoop() throw ( uno::RuntimeException, std::exception )
{
    osl::MutexGuard aGuard(m_aMutex);
    assert(m_pHandle);
    return (sal_Bool)gltf_animation_get_looping(m_pHandle);
}

void SAL_CALL OGLPlayer::setVolumeDB( sal_Int16 /*nVolumDB*/ ) throw ( uno::RuntimeException, std::exception )
{
    // OpenGL models have no sound.
}

sal_Int16 SAL_CALL OGLPlayer::getVolumeDB() throw ( uno::RuntimeException, std::exception )
{
    // OpenGL models have no sound.
    return 0;
}

void SAL_CALL OGLPlayer::setMute( sal_Bool /*bSet*/ ) throw ( uno::RuntimeException, std::exception )
{
    // OpenGL models have no sound.
}

sal_Bool SAL_CALL OGLPlayer::isMute() throw ( uno::RuntimeException, std::exception )
{
    // OpenGL models have no sound.
    return false;
}

awt::Size SAL_CALL OGLPlayer::getPreferredPlayerWindowSize() throw ( uno::RuntimeException, std::exception )
{
    return awt::Size( 480, 360 );
}

uno::Reference< media::XPlayerWindow > SAL_CALL OGLPlayer::createPlayerWindow( const uno::Sequence< uno::Any >& rArguments )
     throw ( uno::RuntimeException, std::exception )
{
    osl::MutexGuard aGuard( m_aMutex );

    assert( rArguments.getLength() >= 3 );
    assert(m_pHandle);

    sal_IntPtr pIntPtr = 0;
    rArguments[ 2 ] >>= pIntPtr;
    SystemChildWindow *pChildWindow = reinterpret_cast< SystemChildWindow* >( pIntPtr );

    if( !pChildWindow )
    {
        SAL_WARN("avmedia.opengl", "Failed to get the SystemChildWindow for rendering!");
        return uno::Reference< media::XPlayerWindow >();
    }

    if( !m_aContext.init(pChildWindow) )
    {
        SAL_WARN("avmedia.opengl", "Context initialization failed");
        return uno::Reference< media::XPlayerWindow >();
    }

    Size aSize = pChildWindow->GetSizePixel();
    m_aContext.setWinSize(aSize);
    m_pHandle->viewport.x = 0;
    m_pHandle->viewport.y = 0;
    m_pHandle->viewport.width = aSize.Width();
    m_pHandle->viewport.height = aSize.Height();

    // TODO: In libgltf different return values are defined (for different errors)
    // but these error codes are not part of the library interface
    int nRet = gltf_renderer_set_content(m_pHandle);
    if( nRet != 0 )
    {
        SAL_WARN("avmedia.opengl", "Error occured while parsing *.json file! Error code: " << nRet);
        return uno::Reference< media::XPlayerWindow >();
    }
    m_pOGLWindow = new OGLWindow(m_pHandle, &m_aContext, pChildWindow);
    return uno::Reference< media::XPlayerWindow >( m_pOGLWindow );
}

uno::Reference< media::XFrameGrabber > SAL_CALL OGLPlayer::createFrameGrabber()
     throw ( uno::RuntimeException, std::exception )
{
    osl::MutexGuard aGuard(m_aMutex);
    assert(m_pHandle);

    if( !m_aContext.init() )
    {
        SAL_WARN("avmedia.opengl", "Offscreen context initialization failed");
        return uno::Reference< media::XFrameGrabber >();
    }

    m_pHandle->viewport.x = 0;
    m_pHandle->viewport.y = 0;
    m_pHandle->viewport.width = getPreferredPlayerWindowSize().Width;
    m_pHandle->viewport.height = getPreferredPlayerWindowSize().Height;

    int nRet = gltf_renderer_set_content(m_pHandle);
    if( nRet != 0 )
    {
        SAL_WARN("avmedia.opengl", "Error occured while parsing *.json file! Error code: " << nRet);
        return uno::Reference< media::XFrameGrabber >();
    }
    OGLFrameGrabber *pFrameGrabber = new OGLFrameGrabber( m_pHandle );
    return uno::Reference< media::XFrameGrabber >( pFrameGrabber );
}

OUString SAL_CALL OGLPlayer::getImplementationName()
     throw ( ::com::sun::star::uno::RuntimeException, std::exception )
{
    return OUString("com.sun.star.comp.avmedia.Player_OpenGL");
}

sal_Bool SAL_CALL OGLPlayer::supportsService( const OUString& rServiceName )
     throw ( uno::RuntimeException, std::exception )
{
    return cppu::supportsService(this, rServiceName);
}

uno::Sequence< OUString > SAL_CALL OGLPlayer::getSupportedServiceNames()
     throw ( uno::RuntimeException, std::exception )
{
    uno::Sequence< OUString > aRet(1);
    aRet[0] = OUString("com.sun.star.media.Player_OpenGL");
    return aRet;
}

IMPL_LINK(OGLPlayer,TimerHandler,Timer*,pTimer)
{
    if (pTimer == &m_aTimer)
    {
        osl::MutexGuard aGuard(m_aMutex);
        assert(m_pOGLWindow);
        m_pOGLWindow->update();
    }

    return 0;
}

} // namespace ogl
} // namespace avmedia

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


<commit_before>/** \example benchmark/benchmark_rmf.cpp
 * \brief Benchmark typical creation, traversal and loading with different RMF
 *        backends.
 *
 * Copyright 2007-2013 IMP Inventors. All rights reserved.
 */

#include <boost/iterator/iterator_facade.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/timer.hpp>
#include <exception>
#include <iostream>
#include <string>
#include <vector>

#include "RMF/BufferHandle.h"
#include "RMF/FileConstHandle.h"
#include "RMF/FileHandle.h"
#include "RMF/ID.h"
#include "RMF/NodeConstHandle.h"
#include "RMF/NodeHandle.h"
#include "RMF/Vector.h"
#include "RMF/decorator/physics.h"
#include "RMF/decorator/sequence.h"
#include "RMF/HDF5/ConstFile.h"
#include "RMF/enums.h"
#include "RMF/infrastructure_macros.h"
#include "RMF/log.h"

namespace {
#ifndef NDEBUG
const int scale = 1;
#else
const int scale = 5;
#endif

std::string show_size(unsigned int sz) {
  std::ostringstream oss;
  if (sz > 1000000) {
    oss << sz / 1000000 << "M";
  } else if (sz > 1000) {
    oss << sz / 1000 << "k";
  } else {
    oss << sz << "b";
  }
  return oss.str();
}

void benchmark_size(std::string path, std::string type) {
  unsigned int size = 0;
  if (boost::filesystem::is_directory(path)) {
    for (boost::filesystem::directory_iterator it(path);
         it != boost::filesystem::directory_iterator(); it++) {
      size += boost::filesystem::file_size(*it);
    }
  } else {
    size = boost::filesystem::file_size(path);
  }
  std::cout << type << ", size, " << show_size(size) << ", " << size
            << std::endl;
}

std::size_t create_residue(RMF::NodeHandle nh, RMF::decorator::AtomFactory af,
                           RMF::decorator::ParticleFactory pf) {
  std::size_t total_size = 0;
  for (unsigned int i = 0; i < 2 * scale; ++i) {
    RMF::NodeHandle child = nh.add_child("CA", RMF::REPRESENTATION);
    pf.get(child).set_static_mass(1);
    pf.get(child).set_static_radius(1.0 + i / 18.77);
    af.get(child).set_static_element(7);
    total_size += sizeof(int) * 1 + sizeof(float) * 2;
  }
  return total_size;
}
std::size_t create_chain(RMF::NodeHandle nh, RMF::decorator::ResidueFactory rf,
                         RMF::decorator::AtomFactory af,
                         RMF::decorator::ParticleFactory pf) {
  std::size_t total_size = 0;
  for (unsigned int i = 0; i < 60 * scale; ++i) {
    std::ostringstream oss;
    oss << i;
    RMF::NodeHandle child = nh.add_child(oss.str(), RMF::REPRESENTATION);
    rf.get(child).set_static_residue_type("cys");
    rf.get(child).set_static_residue_index(i);
    total_size += sizeof(int) + 4;
    total_size += create_residue(child, af, pf);
  }
  return total_size;
}
std::size_t create_hierarchy(RMF::FileHandle file) {
  RMF::decorator::ChainFactory cf(file);
  RMF::decorator::AtomFactory af(file);
  RMF::decorator::ResidueFactory rf(file);
  RMF::decorator::ParticleFactory pf(file);
  RMF::NodeHandle n = file.get_root_node();
  std::size_t total_size = 0;
  for (unsigned int i = 0; i < 3 * scale; ++i) {
    std::ostringstream oss;
    oss << i;
    RMF::NodeHandle child = n.add_child(oss.str(), RMF::REPRESENTATION);
    cf.get(child).set_static_chain_id(oss.str());
    total_size += oss.str().size();
    total_size += create_chain(child, rf, af, pf);
  }
  return total_size;
}

std::pair<double, std::size_t> create_frame(RMF::FileHandle fh,
                                            RMF::decorator::ParticleFactory ipf,
                                            const RMF::NodeIDs& atoms,
                                            int frame) {
  RMF::Vector3 ret(0, 0, 0);
  std::size_t total_size = 0;
  RMF_FOREACH(RMF::NodeID n, atoms) {
    RMF::Vector3 v((n.get_index() + 0 + frame) / 17.0,
                   (n.get_index() + 1 + frame) / 19.0,
                   (n.get_index() + 2 + frame) / 23.0);
    ret[0] += v[0];
    ret[1] += v[1];
    ret[2] += v[2];
    ipf.get(fh.get_node(n)).set_frame_coordinates(v);
    total_size += sizeof(float) * 3;
  }
  return std::make_pair(ret[0] + ret[1] + ret[2], total_size);
}

boost::tuple<double, std::size_t, std::size_t> create(RMF::FileHandle file) {
  std::size_t hierarchy_size = create_hierarchy(file);
  RMF::NodeIDs atoms;
  RMF_FOREACH(RMF::NodeID n, file.get_node_ids()) {
    if (file.get_node(n).get_children().empty()) {
      atoms.push_back(n);
    }
  }
  RMF::decorator::ParticleFactory ipf(file);
  double check_value = 0;
  std::size_t frame_size = 0;
  for (unsigned int i = 0; i < 20; ++i) {
    file.add_frame("frame", RMF::FRAME);
    std::pair<double, std::size_t> cur = create_frame(file, ipf, atoms, i);
    check_value += cur.first;
    frame_size += cur.second;
  }
  return boost::make_tuple(check_value, hierarchy_size, frame_size);
}

double traverse(RMF::FileConstHandle file) {
  double ret = 0;
  RMF::NodeConstHandles queue(1, file.get_root_node());
  RMF::decorator::ParticleFactory ipcf(file);
  do {
    RMF::NodeConstHandle cur = queue.back();
    queue.pop_back();
    if (ipcf.get_is(cur)) {
      ret += ipcf.get(cur).get_radius();
    }
    RMF::NodeConstHandles children = cur.get_children();
    queue.insert(queue.end(), children.begin(), children.end());
  } while (!queue.empty());
  return ret;
}

double load(RMF::FileConstHandle file, const RMF::NodeIDs& nodes) {
  RMF::decorator::IntermediateParticleFactory ipcf(file);
  RMF::Vector3 v(0, 0, 0);
  RMF_FOREACH(RMF::FrameID fr, file.get_frames()) {
    file.set_current_frame(fr);
    RMF_FOREACH(RMF::NodeID n, nodes) {
      RMF::Vector3 cur = ipcf.get(file.get_node(n)).get_coordinates();
      v[0] += cur[0];
      v[1] += cur[1];
      v[2] += cur[2];
    }
  }
  return v[0] + v[1] + v[2];
}

std::pair<std::size_t, std::size_t> benchmark_create(RMF::FileHandle file,
                                                     std::string type) {
  boost::timer timer;
  boost::tuple<double, std::size_t, std::size_t> cur = create(file);
  std::cout << type << ", create, " << timer.elapsed() << ", " << cur.get<0>()
            << std::endl;
  return std::make_pair(cur.get<1>(), cur.get<2>());
}

void benchmark_traverse(RMF::FileConstHandle file, std::string type) {
  file.set_current_frame(RMF::FrameID(0));
  boost::timer timer;
  double count = 0;
  double t;
  while (timer.elapsed() < 1) {
    t = traverse(file);
    ++count;
  }
  std::cout << type << ", traverse, " << timer.elapsed() / count << ", " << t
            << std::endl;
}

void benchmark_load(RMF::FileConstHandle file, std::string type) {
  RMF::NodeIDs nodes;
  RMF::decorator::ParticleFactory ipcf(file);
  RMF_FOREACH(RMF::NodeID n, file.get_node_ids()) {
    if (ipcf.get_is(file.get_node(n))) nodes.push_back(n);
  }
  boost::timer timer;
  double dist = load(file, nodes);
  std::cout << type << ", load, " << timer.elapsed() << ", " << dist
            << std::endl;
}

RMF::FileConstHandle benchmark_open(std::string path, std::string type) {
  boost::timer timer;
  RMF::FileConstHandle ret;
  double count = 0;
  while (timer.elapsed() < 1) {
    ret = RMF::open_rmf_file_read_only(path);
    ++count;
  }
  std::cout << type << ", open, " << timer.elapsed() / count << ", 0"
            << std::endl;
  return ret;
}
}  // namespace

int main(int, char**) {
  try {
    RMF::set_log_level("Off");
    std::string name_base = RMF::internal::get_unique_path();
#ifndef NDEBUG
    std::cout << name_base << std::endl;
#endif
    {
      const std::string name = name_base + ".rmf3";
      {
        RMF::FileHandle fh = RMF::create_rmf_file(name);
        std::pair<std::size_t, std::size_t> sizes =
            benchmark_create(fh, "rmf3");
        std::cout << "raw, total, " << show_size(sizes.first + sizes.second)
                  << ", " << (sizes.first + sizes.second) << std::endl;
        std::cout << "raw, frame, " << show_size(sizes.second) << ", "
                  << sizes.second << std::endl;
      }
      {
        RMF::FileConstHandle fh = benchmark_open(name, "rmf3");
        benchmark_traverse(fh, "rmf3");
        benchmark_load(fh, "rmf3");
      }
      benchmark_size(name, "rmf3");
    }
    {
      const std::string name = name_base + ".rmfz";
      {
        RMF::FileHandle fh = RMF::create_rmf_file(name);
        benchmark_create(fh, "rmfz");
      }
      {
        RMF::FileConstHandle fh = benchmark_open(name, "rmfz");
        benchmark_traverse(fh, "rmfz");
        benchmark_load(fh, "rmfz");
      }
      benchmark_size(name, "rmfz");
    }
    {
      const std::string name = name_base + ".rmf";
      {
        RMF::FileHandle fh = RMF::create_rmf_file(name);
        benchmark_create(fh, "rmf");
      }
      {
        RMF::FileConstHandle fh = benchmark_open(name, "rmf");
        benchmark_traverse(fh, "rmf");
        benchmark_load(fh, "rmf");
      }
      benchmark_size(name, "rmf");
    }
    {
      RMF::BufferHandle buffer;
      {
        RMF::FileHandle fh = RMF::create_rmf_buffer(buffer);
        benchmark_create(fh, "buffer");
      }
      {
        RMF::FileConstHandle fh = RMF::open_rmf_buffer_read_only(buffer);
        benchmark_traverse(fh, "buffer");
        benchmark_load(fh, "buffer");
      }
    }
    {
      const std::string name = name_base + ".rmf2";
      {
        RMF::FileHandle fh = RMF::create_rmf_file(name);
        benchmark_create(fh, "rmf2");
      }
      {
        RMF::FileConstHandle fh = RMF::open_rmf_file_read_only(name);
        benchmark_traverse(fh, "rmf2");
        benchmark_load(fh, "rmf2");
      }
      benchmark_size(name, "rmf2");
    }
    {
      const std::string name = name_base + ".rmfa";
      {
        RMF::FileHandle fh = RMF::create_rmf_file(name);
        benchmark_create(fh, "rmfa");
      }
      {
        RMF::FileConstHandle fh = RMF::open_rmf_file_read_only(name);
        benchmark_traverse(fh, "rmfa");
        benchmark_load(fh, "rmfa");
      }
      benchmark_size(name, "rmfa");
    }
  }
  catch (const std::exception& e) {
    std::cerr << "Exception thrown: " << e.what() << std::endl;
  }
  return 0;
}
<commit_msg>clean up benchmark includes<commit_after>/** \example benchmark/benchmark_rmf.cpp
 * \brief Benchmark typical creation, traversal and loading with different RMF
 *        backends.
 *
 * Copyright 2007-2013 IMP Inventors. All rights reserved.
 */

#include <boost/iterator/iterator_facade.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/timer.hpp>
#include <exception>
#include <iostream>
#include <string>
#include <vector>

#include "RMF/BufferHandle.h"
#include "RMF/FileConstHandle.h"
#include "RMF/FileHandle.h"
#include "RMF/ID.h"
#include "RMF/NodeConstHandle.h"
#include "RMF/NodeHandle.h"
#include "RMF/Vector.h"
#include "RMF/decorator/physics.h"
#include "RMF/decorator/sequence.h"
#include "RMF/enums.h"
#include "RMF/infrastructure_macros.h"
#include "RMF/log.h"

namespace {
#ifndef NDEBUG
const int scale = 1;
#else
const int scale = 5;
#endif

std::string show_size(unsigned int sz) {
  std::ostringstream oss;
  if (sz > 1000000) {
    oss << sz / 1000000 << "M";
  } else if (sz > 1000) {
    oss << sz / 1000 << "k";
  } else {
    oss << sz << "b";
  }
  return oss.str();
}

void benchmark_size(std::string path, std::string type) {
  unsigned int size = 0;
  if (boost::filesystem::is_directory(path)) {
    for (boost::filesystem::directory_iterator it(path);
         it != boost::filesystem::directory_iterator(); it++) {
      size += boost::filesystem::file_size(*it);
    }
  } else {
    size = boost::filesystem::file_size(path);
  }
  std::cout << type << ", size, " << show_size(size) << ", " << size
            << std::endl;
}

std::size_t create_residue(RMF::NodeHandle nh, RMF::decorator::AtomFactory af,
                           RMF::decorator::ParticleFactory pf) {
  std::size_t total_size = 0;
  for (unsigned int i = 0; i < 2 * scale; ++i) {
    RMF::NodeHandle child = nh.add_child("CA", RMF::REPRESENTATION);
    pf.get(child).set_static_mass(1);
    pf.get(child).set_static_radius(1.0 + i / 18.77);
    af.get(child).set_static_element(7);
    total_size += sizeof(int) * 1 + sizeof(float) * 2;
  }
  return total_size;
}
std::size_t create_chain(RMF::NodeHandle nh, RMF::decorator::ResidueFactory rf,
                         RMF::decorator::AtomFactory af,
                         RMF::decorator::ParticleFactory pf) {
  std::size_t total_size = 0;
  for (unsigned int i = 0; i < 60 * scale; ++i) {
    std::ostringstream oss;
    oss << i;
    RMF::NodeHandle child = nh.add_child(oss.str(), RMF::REPRESENTATION);
    rf.get(child).set_static_residue_type("cys");
    rf.get(child).set_static_residue_index(i);
    total_size += sizeof(int) + 4;
    total_size += create_residue(child, af, pf);
  }
  return total_size;
}
std::size_t create_hierarchy(RMF::FileHandle file) {
  RMF::decorator::ChainFactory cf(file);
  RMF::decorator::AtomFactory af(file);
  RMF::decorator::ResidueFactory rf(file);
  RMF::decorator::ParticleFactory pf(file);
  RMF::NodeHandle n = file.get_root_node();
  std::size_t total_size = 0;
  for (unsigned int i = 0; i < 3 * scale; ++i) {
    std::ostringstream oss;
    oss << i;
    RMF::NodeHandle child = n.add_child(oss.str(), RMF::REPRESENTATION);
    cf.get(child).set_static_chain_id(oss.str());
    total_size += oss.str().size();
    total_size += create_chain(child, rf, af, pf);
  }
  return total_size;
}

std::pair<double, std::size_t> create_frame(RMF::FileHandle fh,
                                            RMF::decorator::ParticleFactory ipf,
                                            const RMF::NodeIDs& atoms,
                                            int frame) {
  RMF::Vector3 ret(0, 0, 0);
  std::size_t total_size = 0;
  RMF_FOREACH(RMF::NodeID n, atoms) {
    RMF::Vector3 v((n.get_index() + 0 + frame) / 17.0,
                   (n.get_index() + 1 + frame) / 19.0,
                   (n.get_index() + 2 + frame) / 23.0);
    ret[0] += v[0];
    ret[1] += v[1];
    ret[2] += v[2];
    ipf.get(fh.get_node(n)).set_frame_coordinates(v);
    total_size += sizeof(float) * 3;
  }
  return std::make_pair(ret[0] + ret[1] + ret[2], total_size);
}

boost::tuple<double, std::size_t, std::size_t> create(RMF::FileHandle file) {
  std::size_t hierarchy_size = create_hierarchy(file);
  RMF::NodeIDs atoms;
  RMF_FOREACH(RMF::NodeID n, file.get_node_ids()) {
    if (file.get_node(n).get_children().empty()) {
      atoms.push_back(n);
    }
  }
  RMF::decorator::ParticleFactory ipf(file);
  double check_value = 0;
  std::size_t frame_size = 0;
  for (unsigned int i = 0; i < 20; ++i) {
    file.add_frame("frame", RMF::FRAME);
    std::pair<double, std::size_t> cur = create_frame(file, ipf, atoms, i);
    check_value += cur.first;
    frame_size += cur.second;
  }
  return boost::make_tuple(check_value, hierarchy_size, frame_size);
}

double traverse(RMF::FileConstHandle file) {
  double ret = 0;
  RMF::NodeConstHandles queue(1, file.get_root_node());
  RMF::decorator::ParticleFactory ipcf(file);
  do {
    RMF::NodeConstHandle cur = queue.back();
    queue.pop_back();
    if (ipcf.get_is(cur)) {
      ret += ipcf.get(cur).get_radius();
    }
    RMF::NodeConstHandles children = cur.get_children();
    queue.insert(queue.end(), children.begin(), children.end());
  } while (!queue.empty());
  return ret;
}

double load(RMF::FileConstHandle file, const RMF::NodeIDs& nodes) {
  RMF::decorator::IntermediateParticleFactory ipcf(file);
  RMF::Vector3 v(0, 0, 0);
  RMF_FOREACH(RMF::FrameID fr, file.get_frames()) {
    file.set_current_frame(fr);
    RMF_FOREACH(RMF::NodeID n, nodes) {
      RMF::Vector3 cur = ipcf.get(file.get_node(n)).get_coordinates();
      v[0] += cur[0];
      v[1] += cur[1];
      v[2] += cur[2];
    }
  }
  return v[0] + v[1] + v[2];
}

std::pair<std::size_t, std::size_t> benchmark_create(RMF::FileHandle file,
                                                     std::string type) {
  boost::timer timer;
  boost::tuple<double, std::size_t, std::size_t> cur = create(file);
  std::cout << type << ", create, " << timer.elapsed() << ", " << cur.get<0>()
            << std::endl;
  return std::make_pair(cur.get<1>(), cur.get<2>());
}

void benchmark_traverse(RMF::FileConstHandle file, std::string type) {
  file.set_current_frame(RMF::FrameID(0));
  boost::timer timer;
  double count = 0;
  double t;
  while (timer.elapsed() < 1) {
    t = traverse(file);
    ++count;
  }
  std::cout << type << ", traverse, " << timer.elapsed() / count << ", " << t
            << std::endl;
}

void benchmark_load(RMF::FileConstHandle file, std::string type) {
  RMF::NodeIDs nodes;
  RMF::decorator::ParticleFactory ipcf(file);
  RMF_FOREACH(RMF::NodeID n, file.get_node_ids()) {
    if (ipcf.get_is(file.get_node(n))) nodes.push_back(n);
  }
  boost::timer timer;
  double dist = load(file, nodes);
  std::cout << type << ", load, " << timer.elapsed() << ", " << dist
            << std::endl;
}

RMF::FileConstHandle benchmark_open(std::string path, std::string type) {
  boost::timer timer;
  RMF::FileConstHandle ret;
  double count = 0;
  while (timer.elapsed() < 1) {
    ret = RMF::open_rmf_file_read_only(path);
    ++count;
  }
  std::cout << type << ", open, " << timer.elapsed() / count << ", 0"
            << std::endl;
  return ret;
}
}  // namespace

int main(int, char**) {
  try {
    RMF::set_log_level("Off");
    std::string name_base = RMF::internal::get_unique_path();
#ifndef NDEBUG
    std::cout << name_base << std::endl;
#endif
    {
      const std::string name = name_base + ".rmf";
      {
        RMF::FileHandle fh = RMF::create_rmf_file(name);
        std::pair<std::size_t, std::size_t> sizes =
            benchmark_create(fh, "rmf");
        std::cout << "raw, total, " << show_size(sizes.first + sizes.second)
                  << ", " << (sizes.first + sizes.second) << std::endl;
        std::cout << "raw, frame, " << show_size(sizes.second) << ", "
                  << sizes.second << std::endl;
      }
      {
        RMF::FileConstHandle fh = benchmark_open(name, "rmf");
        benchmark_traverse(fh, "rmf");
        benchmark_load(fh, "rmf");
      }
      benchmark_size(name, "rmf");
    }
    {
      const std::string name = name_base + ".rmfz";
      {
        RMF::FileHandle fh = RMF::create_rmf_file(name);
        benchmark_create(fh, "rmfz");
      }
      {
        RMF::FileConstHandle fh = benchmark_open(name, "rmfz");
        benchmark_traverse(fh, "rmfz");
        benchmark_load(fh, "rmfz");
      }
      benchmark_size(name, "rmfz");
    }
    {
      RMF::BufferHandle buffer;
      {
        RMF::FileHandle fh = RMF::create_rmf_buffer(buffer);
        benchmark_create(fh, "buffer");
      }
      {
        RMF::FileConstHandle fh = RMF::open_rmf_buffer_read_only(buffer);
        benchmark_traverse(fh, "buffer");
        benchmark_load(fh, "buffer");
      }
    }
  }
  catch (const std::exception& e) {
    std::cerr << "Exception thrown: " << e.what() << std::endl;
  }
  return 0;
}
<|endoftext|>


<commit_before>#include "scriptManager.hpp"

#include <fstream>
#include <sstream>

#include <SFML/Graphics/RenderWindow.hpp>
#include <SFML/Graphics/RectangleShape.hpp>

namespace aw
{
	ScriptManager::ScriptManager() :
		m_checkpoint(nullptr)
	{}

	void ScriptManager::update(Player &player, Camera &camera)
	{
		//Check for Scripts
		for (auto &it : m_scripts)
		{
			if (!it.used)
			{
				if (player.getVertexPosition(0).x - 15 >= it.xPos * 25.f) //Front vertex
				{
					it.used = true;

					switch (it.type)
					{
					case CHECKPOINT: checkPointAction(player, camera); break;
					case CHANGE_SPEED: changeSpeedAction(player, it.first); break;
					case CHANGE_GRAVITY: changeGravityAction(player, it.first); break;
					case FLIP_CAMERA: flipCameraAction(camera); break;
					case ZOOM: zoomAction(camera, it.first); break;
					case FLICKERING: flickeringAction(camera); break;
					case INVERT_COLOR: invertColorAction(camera); break;
					case COLOR_OVERLAY: colorOverlayAction(camera); break;
					default: break;
					}
				}
			}
		}
	}

	void ScriptManager::load(const std::string &path)
	{
		//Clear the script vector and the checkpoint pointer
		m_scripts.clear();
		m_checkpoint = nullptr;

		std::fstream file(path.c_str(), std::ios::in);

		if (!file.good())
			return;

		std::string line;
		while (std::getline(file, line))
		{
			if (line == "[Scripts]")
			{
				while (std::getline(file, line))
				{
					if (line == "[/Scripts]")
					{
						break;
					}

					int type;
					int xPos;
					float first, second, third;

					std::stringstream sstr(line);
					sstr >> type >> xPos >> first >> second >> third;

					m_scripts.push_back(Script(ScriptType(type), xPos, first, second, third));
				}
			}
		}

		file.close();
	}

	void ScriptManager::render(sf::RenderWindow &window)
	{
		int screenStartX = static_cast<int>(window.getView().getCenter().x - (window.getView().getSize().x / 2.f));
		int screenEndX = static_cast<int>(window.getView().getCenter().x + (window.getView().getSize().x / 2.f));

		sf::RectangleShape toDraw;

		for (auto &it : m_scripts)
		{
			if (it.xPos * 25.f >= screenStartX && it.xPos * 25.f <= screenEndX)
			{
				//The script is visible
				//update position of toDraw
				toDraw.setPosition(sf::Vector2f((it.xPos * 25.f) + 10.f, window.getView().getCenter().y - (window.getView().getSize().y / 2.f)));
				toDraw.setSize(sf::Vector2f(5, window.getView().getSize().y));

				//Color depends on the script type
				switch (it.type)
				{
				case ScriptType::CHECKPOINT: toDraw.setFillColor(sf::Color(255, 127, 36)); break;
				case ScriptType::CHANGE_GRAVITY: toDraw.setFillColor(sf::Color(138, 43, 226)); break;
				case ScriptType::CHANGE_SPEED: toDraw.setFillColor(sf::Color(138, 43, 226)); break;
				default: toDraw.setFillColor(sf::Color(0, 238, 238)); break;
				}

				//Draw it
				window.draw(toDraw);
				if (m_checkpoint)
				{
					m_checkpoint->savedPlayer.render(window);
				}
			}
		}
	}

	Checkpoint *ScriptManager::getLastCheckPoint()
	{
		if (m_checkpoint)
		{
			return &*m_checkpoint;
		}

		return nullptr;
	}

	void ScriptManager::deleteScripts()
	{
		m_scripts.clear();
	}

	void ScriptManager::resetScriptStates(bool resetCheckpoints)
	{
		if (resetCheckpoints)
		{
			m_checkpoint = nullptr;
		}

		for (auto &it : m_scripts)
		{
			if (it.type != ScriptType::CHECKPOINT || resetCheckpoints)
			{
				it.used = false;
			}
		}
	}

	////////ACTION FUNCTIONS//////////////////////////////////////////////////////////

	void ScriptManager::checkPointAction(Player &player, Camera &camera)
	{
		m_checkpoint = std::unique_ptr<Checkpoint>(new Checkpoint());
		m_checkpoint->savedPlayer = player;
		m_checkpoint->savedCamera = camera;
	}

	void ScriptManager::changeSpeedAction(Player &player, float first)
	{
		player.setSpeedX(first);
	}
	void ScriptManager::changeGravityAction(Player &player, float first)
	{
		player.setGravitation(first);
	}
	void ScriptManager::flipCameraAction(Camera &camera)
	{
        camera.flip();
	}
	void ScriptManager::zoomAction(Camera &camera, float first)
	{
		camera.zoom(first);
	}
	void ScriptManager::flickeringAction(Camera &camera)
	{

	}
	void ScriptManager::invertColorAction(Camera &camera)
	{

	}
	void ScriptManager::colorOverlayAction(Camera &camera)
	{

	}
}<commit_msg>Fixed a drawing issue in scriptmanager<commit_after>#include "scriptManager.hpp"

#include <fstream>
#include <sstream>

#include <SFML/Graphics/RenderWindow.hpp>
#include <SFML/Graphics/RectangleShape.hpp>

namespace aw
{
	ScriptManager::ScriptManager() :
		m_checkpoint(nullptr)
	{}

	void ScriptManager::update(Player &player, Camera &camera)
	{
		//Check for Scripts
		for (auto &it : m_scripts)
		{
			if (!it.used)
			{
				if (player.getVertexPosition(0).x - 15 >= it.xPos * 25.f) //Front vertex
				{
					it.used = true;

					switch (it.type)
					{
					case CHECKPOINT: checkPointAction(player, camera); break;
					case CHANGE_SPEED: changeSpeedAction(player, it.first); break;
					case CHANGE_GRAVITY: changeGravityAction(player, it.first); break;
					case FLIP_CAMERA: flipCameraAction(camera); break;
					case ZOOM: zoomAction(camera, it.first); break;
					case FLICKERING: flickeringAction(camera); break;
					case INVERT_COLOR: invertColorAction(camera); break;
					case COLOR_OVERLAY: colorOverlayAction(camera); break;
					default: break;
					}
				}
			}
		}
	}

	void ScriptManager::load(const std::string &path)
	{
		//Clear the script vector and the checkpoint pointer
		m_scripts.clear();
		m_checkpoint = nullptr;

		std::fstream file(path.c_str(), std::ios::in);

		if (!file.good())
			return;

		std::string line;
		while (std::getline(file, line))
		{
			if (line == "[Scripts]")
			{
				while (std::getline(file, line))
				{
					if (line == "[/Scripts]")
					{
						break;
					}

					int type;
					int xPos;
					float first, second, third;

					std::stringstream sstr(line);
					sstr >> type >> xPos >> first >> second >> third;

					m_scripts.push_back(Script(ScriptType(type), xPos, first, second, third));
				}
			}
		}

		file.close();
	}

	void ScriptManager::render(sf::RenderWindow &window)
	{
		int screenStartX = static_cast<int>(window.getView().getCenter().x - (window.getView().getSize().x / 2.f));
		int screenEndX = static_cast<int>(window.getView().getCenter().x + (window.getView().getSize().x / 2.f));

		sf::RectangleShape toDraw;

		for (auto &it : m_scripts)
		{
			//+16 to prevent the script to disappear too early (position + 10, size +5, +1 because i can xD )
			if (it.xPos * 25.f + 16 >= screenStartX && it.xPos * 25.f <= screenEndX)
			{
				//The script is visible
				//update position of toDraw
				toDraw.setPosition(sf::Vector2f((it.xPos * 25.f) + 10.f, window.getView().getCenter().y - (window.getView().getSize().y / 2.f)));
				toDraw.setSize(sf::Vector2f(5, window.getView().getSize().y));

				//Color depends on the script type
				switch (it.type)
				{
				case ScriptType::CHECKPOINT: toDraw.setFillColor(sf::Color(255, 127, 36)); break;
				case ScriptType::CHANGE_GRAVITY: toDraw.setFillColor(sf::Color(138, 43, 226)); break;
				case ScriptType::CHANGE_SPEED: toDraw.setFillColor(sf::Color(138, 43, 226)); break;
				default: toDraw.setFillColor(sf::Color(0, 238, 238)); break;
				}

				//Draw it
				window.draw(toDraw);
				if (m_checkpoint)
				{
					m_checkpoint->savedPlayer.render(window);
				}
			}
		}
	}

	Checkpoint *ScriptManager::getLastCheckPoint()
	{
		if (m_checkpoint)
		{
			return &*m_checkpoint;
		}

		return nullptr;
	}

	void ScriptManager::deleteScripts()
	{
		m_scripts.clear();
	}

	void ScriptManager::resetScriptStates(bool resetCheckpoints)
	{
		if (resetCheckpoints)
		{
			m_checkpoint = nullptr;
		}

		for (auto &it : m_scripts)
		{
			if (it.type != ScriptType::CHECKPOINT || resetCheckpoints)
			{
				it.used = false;
			}
		}
	}

	////////ACTION FUNCTIONS//////////////////////////////////////////////////////////

	void ScriptManager::checkPointAction(Player &player, Camera &camera)
	{
		m_checkpoint = std::unique_ptr<Checkpoint>(new Checkpoint());
		m_checkpoint->savedPlayer = player;
		m_checkpoint->savedCamera = camera;
	}

	void ScriptManager::changeSpeedAction(Player &player, float first)
	{
		player.setSpeedX(first);
	}
	void ScriptManager::changeGravityAction(Player &player, float first)
	{
		player.setGravitation(first);
	}
	void ScriptManager::flipCameraAction(Camera &camera)
	{
        camera.flip();
	}
	void ScriptManager::zoomAction(Camera &camera, float first)
	{
		camera.zoom(first);
	}
	void ScriptManager::flickeringAction(Camera &camera)
	{

	}
	void ScriptManager::invertColorAction(Camera &camera)
	{

	}
	void ScriptManager::colorOverlayAction(Camera &camera)
	{

	}
}<|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/.
 */

#include "oglplayer.hxx"
#include "oglframegrabber.hxx"
#include "oglwindow.hxx"

#include <cppuhelper/supportsservice.hxx>
#include <tools/stream.hxx>
#include <vcl/graph.hxx>
#include <vcl/graphicfilter.hxx>
#include <tools/urlobj.hxx>
#include <vcl/opengl/OpenGLHelper.hxx>

using namespace com::sun::star;

namespace avmedia { namespace ogl {

OGLPlayer::OGLPlayer()
    : Player_BASE(m_aMutex)
    , m_pHandle(NULL)
{
}

OGLPlayer::~OGLPlayer()
{
    // Comment out while it causes segmentation fault
    // gltf_renderer_release(m_pHandle);
}

static bool lcl_LoadFile( glTFFile* io_pFile, const OUString& rURL)
{
    SvFileStream aStream( rURL, STREAM_READ );
    if( !aStream.IsOpen() )
        return false;

    const sal_Int64 nBytes = aStream.remainingSize();
    char* pBuffer = new char[nBytes];
    aStream.Read( pBuffer, nBytes );
    aStream.Close();

    io_pFile->buffer = pBuffer;
    io_pFile->size = nBytes;

    return true;
}

bool OGLPlayer::create( const OUString& rURL )
{
    m_sURL = rURL;

    // Load *.json file and init renderer
    glTFFile aJsonFile;
    aJsonFile.type = GLTF_JSON;
    OString sFileName = OUStringToOString(INetURLObject(m_sURL).GetLastName(),RTL_TEXTENCODING_UTF8);
    aJsonFile.filename = (char*)sFileName.getStr();
    if( !lcl_LoadFile(&aJsonFile, m_sURL) )
    {
        SAL_WARN("avmedia.opengl", "Can't load *.json file: " + sFileName);
        return false;
    }

    m_pHandle = gltf_renderer_init(&aJsonFile);

    if( !m_pHandle || !m_pHandle->files )
    {
        SAL_WARN("avmedia.opengl", "gltf_renderer_init returned an invalid glTFHandle");
        return false;
    }

    // Load external resources
    for( size_t i = 0; i < m_pHandle->size; ++i )
    {
        glTFFile* pFile = m_pHandle->files[i];
        if( pFile && pFile->filename )
        {
            const OUString sFilesURL =
                INetURLObject::GetAbsURL(m_sURL,OStringToOUString(OString(pFile->filename),RTL_TEXTENCODING_UTF8));
            if( pFile->type == GLTF_IMAGE )
            {
                // Load images as bitmaps
                GraphicFilter aFilter;
                Graphic aGraphic;
                aFilter.ImportGraphic(aGraphic, INetURLObject(sFilesURL));
                const BitmapEx aBitmapEx = aGraphic.GetBitmapEx();
                pFile->buffer = (char*)OpenGLHelper::ConvertBitmapExToRGBABuffer(aBitmapEx);
                pFile->imagewidth = aBitmapEx.GetSizePixel().Width();
                pFile->imageheight = aBitmapEx.GetSizePixel().Height();
            }
            else if( pFile->type == GLTF_BINARY || pFile->type == GLTF_GLSL )
            {
                if( !lcl_LoadFile(pFile, sFilesURL) )
                {
                    SAL_WARN("avmedia.opengl", "Can't load glTF file: " + sFilesURL);
                    return false;
                }
            }
        }
    }

    // Set timer
    m_aTimer.SetTimeout(10);
    m_aTimer.SetTimeoutHdl(LINK(this,OGLPlayer,TimerHandler));
    return true;
}

void SAL_CALL OGLPlayer::start() throw ( uno::RuntimeException, std::exception )
{
    osl::MutexGuard aGuard(m_aMutex);
    gltf_animation_start(m_pHandle);
    m_aTimer.Start();
}

void SAL_CALL OGLPlayer::stop() throw ( uno::RuntimeException, std::exception )
{
    osl::MutexGuard aGuard(m_aMutex);
    gltf_animation_stop(m_pHandle);
    m_aTimer.Stop();
}

sal_Bool SAL_CALL OGLPlayer::isPlaying() throw ( uno::RuntimeException, std::exception )
{
    osl::MutexGuard aGuard(m_aMutex);
    return (sal_Bool)gltf_animation_is_playing(m_pHandle);
}

double SAL_CALL OGLPlayer::getDuration() throw ( uno::RuntimeException, std::exception )
{
    osl::MutexGuard aGuard(m_aMutex);
    return gltf_animation_get_duration(m_pHandle);
}

void SAL_CALL OGLPlayer::setMediaTime( double fTime ) throw ( uno::RuntimeException, std::exception )
{
    // TODO: doesn't work, but cause problem in playing
    osl::MutexGuard aGuard(m_aMutex);
    (void) fTime;
    //gltf_animation_set_time(m_pHandle, fTime);
}

double SAL_CALL OGLPlayer::getMediaTime() throw ( ::com::sun::star::uno::RuntimeException, std::exception )
{
    osl::MutexGuard aGuard(m_aMutex);
    return gltf_animation_get_time(m_pHandle);
}

double SAL_CALL OGLPlayer::getRate() throw ( uno::RuntimeException, std::exception )
{
    osl::MutexGuard aGuard(m_aMutex);
    // Seems unused
    return 1.0;
}

void SAL_CALL OGLPlayer::setPlaybackLoop( sal_Bool bSet ) throw ( uno::RuntimeException, std::exception )
{
    osl::MutexGuard aGuard(m_aMutex);
    gltf_animation_set_looping(m_pHandle, (int)bSet);
}

sal_Bool SAL_CALL OGLPlayer::isPlaybackLoop() throw ( uno::RuntimeException, std::exception )
{
    osl::MutexGuard aGuard(m_aMutex);
    return (sal_Bool)gltf_animation_get_looping(m_pHandle);
}

void SAL_CALL OGLPlayer::setVolumeDB( sal_Int16 /*nVolumDB*/ ) throw ( uno::RuntimeException, std::exception )
{
    // OpenGL models have no sound.
}

sal_Int16 SAL_CALL OGLPlayer::getVolumeDB() throw ( uno::RuntimeException, std::exception )
{
    // OpenGL models have no sound.
    return 0;
}

void SAL_CALL OGLPlayer::setMute( sal_Bool /*bSet*/ ) throw ( uno::RuntimeException, std::exception )
{
    // OpenGL models have no sound.
}

sal_Bool SAL_CALL OGLPlayer::isMute() throw ( uno::RuntimeException, std::exception )
{
    // OpenGL models have no sound.
    return false;
}

awt::Size SAL_CALL OGLPlayer::getPreferredPlayerWindowSize() throw ( uno::RuntimeException, std::exception )
{
    return awt::Size( 480, 360 );
}

uno::Reference< media::XPlayerWindow > SAL_CALL OGLPlayer::createPlayerWindow( const uno::Sequence< uno::Any >& rArguments )
     throw ( uno::RuntimeException, std::exception )
{
    osl::MutexGuard aGuard( m_aMutex );

    assert( rArguments.getLength() >= 3 );

    sal_IntPtr pIntPtr = 0;
    rArguments[ 2 ] >>= pIntPtr;
    SystemChildWindow *pChildWindow = reinterpret_cast< SystemChildWindow* >( pIntPtr );

    if( !m_aContext.init(pChildWindow) )
    {
        SAL_WARN("avmedia.opengl", "Context initialization failed");
        return uno::Reference< media::XPlayerWindow >();
    }

    Size aSize = pChildWindow->GetSizePixel();
    m_aContext.setWinSize(aSize);
    m_pHandle->viewport.x = 0;
    m_pHandle->viewport.y = 0;
    m_pHandle->viewport.width = aSize.Width();
    m_pHandle->viewport.height = aSize.Height();
    gltf_renderer_set_content(m_pHandle);
    m_pOGLWindow = new OGLWindow(m_pHandle, &m_aContext, pChildWindow);
    return uno::Reference< media::XPlayerWindow >( m_pOGLWindow );
}

uno::Reference< media::XFrameGrabber > SAL_CALL OGLPlayer::createFrameGrabber()
     throw ( uno::RuntimeException, std::exception )
{
    osl::MutexGuard aGuard(m_aMutex);

    if( !m_aContext.init() )
    {
        SAL_WARN("avmedia.opengl", "Offscreen context initialization failed");
        return uno::Reference< media::XFrameGrabber >();
    }

    m_pHandle->viewport.x = 0;
    m_pHandle->viewport.y = 0;
    m_pHandle->viewport.width = getPreferredPlayerWindowSize().Width;
    m_pHandle->viewport.height = getPreferredPlayerWindowSize().Height;
    gltf_renderer_set_content(m_pHandle);
    OGLFrameGrabber *pFrameGrabber = new OGLFrameGrabber( m_pHandle );
    return uno::Reference< media::XFrameGrabber >( pFrameGrabber );
}

OUString SAL_CALL OGLPlayer::getImplementationName()
     throw ( ::com::sun::star::uno::RuntimeException, std::exception )
{
    return OUString("com.sun.star.comp.avmedia.Player_OpenGL");
}

sal_Bool SAL_CALL OGLPlayer::supportsService( const OUString& rServiceName )
     throw ( uno::RuntimeException, std::exception )
{
    return cppu::supportsService(this, rServiceName);
}

uno::Sequence< OUString > SAL_CALL OGLPlayer::getSupportedServiceNames()
     throw ( uno::RuntimeException, std::exception )
{
    uno::Sequence< OUString > aRet(1);
    aRet[0] = OUString("com.sun.star.media.Player_OpenGL");
    return aRet;
}

IMPL_LINK(OGLPlayer,TimerHandler,Timer*,pTimer)
{
    if (pTimer == &m_aTimer)
    {
        m_pOGLWindow->update();
        m_aTimer.Start();
    }

    return 0;
}

} // namespace ogl
} // namespace avmedia

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>OGLPlayer: comment out gltf_animation_get_time<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/.
 */

#include "oglplayer.hxx"
#include "oglframegrabber.hxx"
#include "oglwindow.hxx"

#include <cppuhelper/supportsservice.hxx>
#include <tools/stream.hxx>
#include <vcl/graph.hxx>
#include <vcl/graphicfilter.hxx>
#include <tools/urlobj.hxx>
#include <vcl/opengl/OpenGLHelper.hxx>

using namespace com::sun::star;

namespace avmedia { namespace ogl {

OGLPlayer::OGLPlayer()
    : Player_BASE(m_aMutex)
    , m_pHandle(NULL)
{
}

OGLPlayer::~OGLPlayer()
{
    // Comment out while it causes segmentation fault
    // gltf_renderer_release(m_pHandle);
}

static bool lcl_LoadFile( glTFFile* io_pFile, const OUString& rURL)
{
    SvFileStream aStream( rURL, STREAM_READ );
    if( !aStream.IsOpen() )
        return false;

    const sal_Int64 nBytes = aStream.remainingSize();
    char* pBuffer = new char[nBytes];
    aStream.Read( pBuffer, nBytes );
    aStream.Close();

    io_pFile->buffer = pBuffer;
    io_pFile->size = nBytes;

    return true;
}

bool OGLPlayer::create( const OUString& rURL )
{
    m_sURL = rURL;

    // Load *.json file and init renderer
    glTFFile aJsonFile;
    aJsonFile.type = GLTF_JSON;
    OString sFileName = OUStringToOString(INetURLObject(m_sURL).GetLastName(),RTL_TEXTENCODING_UTF8);
    aJsonFile.filename = (char*)sFileName.getStr();
    if( !lcl_LoadFile(&aJsonFile, m_sURL) )
    {
        SAL_WARN("avmedia.opengl", "Can't load *.json file: " + sFileName);
        return false;
    }

    m_pHandle = gltf_renderer_init(&aJsonFile);

    if( !m_pHandle || !m_pHandle->files )
    {
        SAL_WARN("avmedia.opengl", "gltf_renderer_init returned an invalid glTFHandle");
        return false;
    }

    // Load external resources
    for( size_t i = 0; i < m_pHandle->size; ++i )
    {
        glTFFile* pFile = m_pHandle->files[i];
        if( pFile && pFile->filename )
        {
            const OUString sFilesURL =
                INetURLObject::GetAbsURL(m_sURL,OStringToOUString(OString(pFile->filename),RTL_TEXTENCODING_UTF8));
            if( pFile->type == GLTF_IMAGE )
            {
                // Load images as bitmaps
                GraphicFilter aFilter;
                Graphic aGraphic;
                aFilter.ImportGraphic(aGraphic, INetURLObject(sFilesURL));
                const BitmapEx aBitmapEx = aGraphic.GetBitmapEx();
                pFile->buffer = (char*)OpenGLHelper::ConvertBitmapExToRGBABuffer(aBitmapEx);
                pFile->imagewidth = aBitmapEx.GetSizePixel().Width();
                pFile->imageheight = aBitmapEx.GetSizePixel().Height();
            }
            else if( pFile->type == GLTF_BINARY || pFile->type == GLTF_GLSL )
            {
                if( !lcl_LoadFile(pFile, sFilesURL) )
                {
                    SAL_WARN("avmedia.opengl", "Can't load glTF file: " + sFilesURL);
                    return false;
                }
            }
        }
    }

    // Set timer
    m_aTimer.SetTimeout(10);
    m_aTimer.SetTimeoutHdl(LINK(this,OGLPlayer,TimerHandler));
    return true;
}

void SAL_CALL OGLPlayer::start() throw ( uno::RuntimeException, std::exception )
{
    osl::MutexGuard aGuard(m_aMutex);
    gltf_animation_start(m_pHandle);
    m_aTimer.Start();
}

void SAL_CALL OGLPlayer::stop() throw ( uno::RuntimeException, std::exception )
{
    osl::MutexGuard aGuard(m_aMutex);
    gltf_animation_stop(m_pHandle);
    m_aTimer.Stop();
}

sal_Bool SAL_CALL OGLPlayer::isPlaying() throw ( uno::RuntimeException, std::exception )
{
    osl::MutexGuard aGuard(m_aMutex);
    return (sal_Bool)gltf_animation_is_playing(m_pHandle);
}

double SAL_CALL OGLPlayer::getDuration() throw ( uno::RuntimeException, std::exception )
{
    osl::MutexGuard aGuard(m_aMutex);
    return gltf_animation_get_duration(m_pHandle);
}

void SAL_CALL OGLPlayer::setMediaTime( double fTime ) throw ( uno::RuntimeException, std::exception )
{
    // TODO: doesn't work, but cause problem in playing
    osl::MutexGuard aGuard(m_aMutex);
    (void) fTime;
    //gltf_animation_set_time(m_pHandle, fTime);
}

double SAL_CALL OGLPlayer::getMediaTime() throw ( ::com::sun::star::uno::RuntimeException, std::exception )
{
    osl::MutexGuard aGuard(m_aMutex);
    return 0.0; //gltf_animation_get_time(m_pHandle);
}

double SAL_CALL OGLPlayer::getRate() throw ( uno::RuntimeException, std::exception )
{
    osl::MutexGuard aGuard(m_aMutex);
    // Seems unused
    return 1.0;
}

void SAL_CALL OGLPlayer::setPlaybackLoop( sal_Bool bSet ) throw ( uno::RuntimeException, std::exception )
{
    osl::MutexGuard aGuard(m_aMutex);
    gltf_animation_set_looping(m_pHandle, (int)bSet);
}

sal_Bool SAL_CALL OGLPlayer::isPlaybackLoop() throw ( uno::RuntimeException, std::exception )
{
    osl::MutexGuard aGuard(m_aMutex);
    return (sal_Bool)gltf_animation_get_looping(m_pHandle);
}

void SAL_CALL OGLPlayer::setVolumeDB( sal_Int16 /*nVolumDB*/ ) throw ( uno::RuntimeException, std::exception )
{
    // OpenGL models have no sound.
}

sal_Int16 SAL_CALL OGLPlayer::getVolumeDB() throw ( uno::RuntimeException, std::exception )
{
    // OpenGL models have no sound.
    return 0;
}

void SAL_CALL OGLPlayer::setMute( sal_Bool /*bSet*/ ) throw ( uno::RuntimeException, std::exception )
{
    // OpenGL models have no sound.
}

sal_Bool SAL_CALL OGLPlayer::isMute() throw ( uno::RuntimeException, std::exception )
{
    // OpenGL models have no sound.
    return false;
}

awt::Size SAL_CALL OGLPlayer::getPreferredPlayerWindowSize() throw ( uno::RuntimeException, std::exception )
{
    return awt::Size( 480, 360 );
}

uno::Reference< media::XPlayerWindow > SAL_CALL OGLPlayer::createPlayerWindow( const uno::Sequence< uno::Any >& rArguments )
     throw ( uno::RuntimeException, std::exception )
{
    osl::MutexGuard aGuard( m_aMutex );

    assert( rArguments.getLength() >= 3 );

    sal_IntPtr pIntPtr = 0;
    rArguments[ 2 ] >>= pIntPtr;
    SystemChildWindow *pChildWindow = reinterpret_cast< SystemChildWindow* >( pIntPtr );

    if( !m_aContext.init(pChildWindow) )
    {
        SAL_WARN("avmedia.opengl", "Context initialization failed");
        return uno::Reference< media::XPlayerWindow >();
    }

    Size aSize = pChildWindow->GetSizePixel();
    m_aContext.setWinSize(aSize);
    m_pHandle->viewport.x = 0;
    m_pHandle->viewport.y = 0;
    m_pHandle->viewport.width = aSize.Width();
    m_pHandle->viewport.height = aSize.Height();
    gltf_renderer_set_content(m_pHandle);
    m_pOGLWindow = new OGLWindow(m_pHandle, &m_aContext, pChildWindow);
    return uno::Reference< media::XPlayerWindow >( m_pOGLWindow );
}

uno::Reference< media::XFrameGrabber > SAL_CALL OGLPlayer::createFrameGrabber()
     throw ( uno::RuntimeException, std::exception )
{
    osl::MutexGuard aGuard(m_aMutex);

    if( !m_aContext.init() )
    {
        SAL_WARN("avmedia.opengl", "Offscreen context initialization failed");
        return uno::Reference< media::XFrameGrabber >();
    }

    m_pHandle->viewport.x = 0;
    m_pHandle->viewport.y = 0;
    m_pHandle->viewport.width = getPreferredPlayerWindowSize().Width;
    m_pHandle->viewport.height = getPreferredPlayerWindowSize().Height;
    gltf_renderer_set_content(m_pHandle);
    OGLFrameGrabber *pFrameGrabber = new OGLFrameGrabber( m_pHandle );
    return uno::Reference< media::XFrameGrabber >( pFrameGrabber );
}

OUString SAL_CALL OGLPlayer::getImplementationName()
     throw ( ::com::sun::star::uno::RuntimeException, std::exception )
{
    return OUString("com.sun.star.comp.avmedia.Player_OpenGL");
}

sal_Bool SAL_CALL OGLPlayer::supportsService( const OUString& rServiceName )
     throw ( uno::RuntimeException, std::exception )
{
    return cppu::supportsService(this, rServiceName);
}

uno::Sequence< OUString > SAL_CALL OGLPlayer::getSupportedServiceNames()
     throw ( uno::RuntimeException, std::exception )
{
    uno::Sequence< OUString > aRet(1);
    aRet[0] = OUString("com.sun.star.media.Player_OpenGL");
    return aRet;
}

IMPL_LINK(OGLPlayer,TimerHandler,Timer*,pTimer)
{
    if (pTimer == &m_aTimer)
    {
        m_pOGLWindow->update();
        m_aTimer.Start();
    }

    return 0;
}

} // namespace ogl
} // namespace avmedia

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


<commit_before>#include "serialbusconnection.h"

#include "canconmanager.h"

#include <QCanBus>
#include <QCanBusFrame>
#include <QDateTime>
#include <QDebug>

/***********************************/
/****    class definition       ****/
/***********************************/

SerialBusConnection::SerialBusConnection(QString portName) :
    CANConnection(portName, CANCon::SOCKETCAN, 1, 4000, true),
    mTimer(this) /*NB: set connection as parent of timer to manage it from working thread */
{
}

SerialBusConnection::~SerialBusConnection()
{
    stop();
}

void SerialBusConnection::piStarted()
{
    connect(&mTimer, SIGNAL(timeout()), this, SLOT(testConnection()));
    mTimer.setInterval(1000);
    mTimer.setSingleShot(false); //keep ticking
    mTimer.start();
    mBusData[0].mBus.setEnabled(true);
    mBusData[0].mConfigured = true;
}

void SerialBusConnection::piSuspend(bool pSuspend)
{
    /* update capSuspended */
    setCapSuspended(pSuspend);

    /* flush queue if we are suspended */
    if(isCapSuspended())
        getQueue().flush();
}

void SerialBusConnection::piStop() {
    mTimer.stop();
    disconnectDevice();
}

bool SerialBusConnection::piGetBusSettings(int pBusIdx, CANBus& pBus)
{
    return getBusConfig(pBusIdx, pBus);
}

void SerialBusConnection::piSetBusSettings(int pBusIdx, CANBus bus)
{
    CANConStatus stats;
    /* sanity checks */
    if(0 != pBusIdx)
        return;

    /* disconnect device if we have one connected */
    disconnectDevice();

    /* copy bus config */
    setBusConfig(0, bus);

    /* if bus is not active we are done */
    if(!bus.active)
        return;

    /* create device */
    QString errorString;
    mDev_p = QCanBus::instance()->createDevice("socketcan", getPort(), &errorString);
    if (!mDev_p) {
        disconnectDevice();
        qDebug() << "Error: createDevice(" << getType() << getPort() << "):" << errorString;
        return;
    }

    /* connect slots */
    connect(mDev_p, &QCanBusDevice::errorOccurred, this, &SerialBusConnection::errorReceived);
    connect(mDev_p, &QCanBusDevice::framesWritten, this, &SerialBusConnection::framesWritten);
    connect(mDev_p, &QCanBusDevice::framesReceived, this, &SerialBusConnection::framesReceived);

    /* set configuration */
    /*if (p.useConfigurationEnabled) {
     foreach (const SettingsDialog::ConfigurationItem &item, p.configurations)
         mDev->setConfigurationParameter(item.first, item.second);
    }*/

    //You cannot set the speed of a socketcan interface, it has to be set with console commands.
    //mDev_p->setConfigurationParameter(QCanBusDevice::BitRateKey, bus.speed);

    /* connect device */
    if (!mDev_p->connectDevice()) {
        disconnectDevice();
        qDebug() << "can't connect device";
    }
}

bool SerialBusConnection::piSendFrame(const CANFrame& pFrame)
{
    /* sanity checks */
    if(0 != pFrame.bus || pFrame.len>8)
        return false;
    if (!mDev_p) return false;

    /* fill frame */
    QCanBusFrame frame;
    frame.setFrameId(pFrame.ID);
    frame.setExtendedFrameFormat(pFrame.extended);
    frame.setPayload(QByteArray(reinterpret_cast<const char *>(pFrame.data),
                                static_cast<int>(pFrame.len)));

    return mDev_p->writeFrame(frame);
}

/***********************************/
/****   private methods         ****/
/***********************************/

/* disconnect device */
void SerialBusConnection::disconnectDevice() {
    if(mDev_p) {
        mDev_p->disconnectDevice();
        delete mDev_p;
        mDev_p = nullptr;
    }
}

void SerialBusConnection::errorReceived(QCanBusDevice::CanBusError error) const
{
    switch (error) {
        case QCanBusDevice::ReadError:
        case QCanBusDevice::WriteError:
        case QCanBusDevice::ConnectionError:
        case QCanBusDevice::ConfigurationError:
        case QCanBusDevice::UnknownError:
        qWarning() << mDev_p->errorString();
        break;
    default:
        break;
    }
}

void SerialBusConnection::framesWritten(qint64 count)
{
    Q_UNUSED(count);
    //qDebug() << "Number of frames written:" << count;
}

void SerialBusConnection::framesReceived()
{
    uint64_t timeBasis = CANConManager::getInstance()->getTimeBasis();

    /* sanity checks */
    if(!mDev_p)
        return;

    /* read frame */
    while(true)
    {
        const QCanBusFrame recFrame = mDev_p->readFrame();

        /* exit case */
        if(!recFrame.isValid())
            break;

        /* drop frame if capture is suspended */
        if(isCapSuspended())
            continue;

        /* check frame */
        if (recFrame.payload().length() <= 8) {
            CANFrame* frame_p = getQueue().get();
            if(frame_p) {
                frame_p->len           = static_cast<uint32_t>(recFrame.payload().length());
                frame_p->bus           = 0;
                if (recFrame.frameType() == QCanBusFrame::ErrorFrame) {
                    // Constants defined in include/uapi/linux/can/error.h
                    switch (recFrame.error()) {
                        case QCanBusFrame::TransmissionTimeoutError:
                            frame_p->ID = 0x20000001;
                            break;
                        case QCanBusFrame::LostArbitrationError:
                            frame_p->ID = 0x20000002;
                            break;
                        case QCanBusFrame::ControllerError:
                            frame_p->ID = 0x20000004;
                            break;
                        case QCanBusFrame::ProtocolViolationError:
                            frame_p->ID = 0x20000008;
                            break;
                        case QCanBusFrame::TransceiverError:
                            frame_p->ID = 0x20000010;
                            break;
                        case QCanBusFrame::MissingAcknowledgmentError:
                            frame_p->ID = 0x20000020;
                            break;
                        case QCanBusFrame::BusOffError:
                            frame_p->ID = 0x20000040;
                            break;
                        case QCanBusFrame::BusError:
                            frame_p->ID = 0x20000080;
                            break;
                        case QCanBusFrame::ControllerRestartError:
                            frame_p->ID = 0x20000100;
                            break;
                        default:
                            break;
                    }
                    frame_p->extended = true;
                } else {
                    frame_p->extended      = recFrame.hasExtendedFrameFormat();
                    frame_p->ID            = recFrame.frameId();
                }
                frame_p->isReceived    = true;
                if (useSystemTime) {
                    frame_p->timestamp = QDateTime::currentMSecsSinceEpoch() * 1000ul;
                }
                else frame_p->timestamp     = (recFrame.timeStamp().seconds() * 1000000ul + recFrame.timeStamp().microSeconds()) - timeBasis;

                checkTargettedFrame(*frame_p);

                /* enqueue frame */
                getQueue().queue();
            }
#if 0
            else
                qDebug() << "can't get a frame, ERROR";
#endif
        }
    }
}

void SerialBusConnection::testConnection() {
    QCanBusDevice*  dev_p = QCanBus::instance()->createDevice("socketcan", getPort());
    CANConStatus stats;

    switch(getStatus())
    {
        case CANCon::CONNECTED:
            if (!dev_p || !dev_p->connectDevice()) {
                /* we have lost connectivity */
                disconnectDevice();

                setStatus(CANCon::NOT_CONNECTED);
                stats.conStatus = getStatus();
                stats.numHardwareBuses = mNumBuses;
                emit status(stats);
            }
            break;
        case CANCon::NOT_CONNECTED:
            if (dev_p && dev_p->connectDevice()) {
                if(!mDev_p) {
                    /* try to reconnect */
                    CANBus bus;
                    if(getBusConfig(0, bus))
                    {
                        bus.setEnabled(true);
                        setBusSettings(0, bus);
                    }
                }
                /* disconnect test instance */
                dev_p->disconnectDevice();

                setStatus(CANCon::CONNECTED);
                stats.conStatus = getStatus();
                stats.numHardwareBuses = mNumBuses;
                emit status(stats);
            }
            break;
        default: {}
    }

    if(dev_p)
        delete dev_p;
}
<commit_msg>Add accidentally removed line.<commit_after>#include "serialbusconnection.h"

#include "canconmanager.h"

#include <QCanBus>
#include <QCanBusFrame>
#include <QDateTime>
#include <QDebug>

/***********************************/
/****    class definition       ****/
/***********************************/

SerialBusConnection::SerialBusConnection(QString portName) :
    CANConnection(portName, CANCon::SOCKETCAN, 1, 4000, true),
    mTimer(this) /*NB: set connection as parent of timer to manage it from working thread */
{
}

SerialBusConnection::~SerialBusConnection()
{
    stop();
}

void SerialBusConnection::piStarted()
{
    connect(&mTimer, SIGNAL(timeout()), this, SLOT(testConnection()));
    mTimer.setInterval(1000);
    mTimer.setSingleShot(false); //keep ticking
    mTimer.start();
    mBusData[0].mBus.setEnabled(true);
    mBusData[0].mConfigured = true;
}

void SerialBusConnection::piSuspend(bool pSuspend)
{
    /* update capSuspended */
    setCapSuspended(pSuspend);

    /* flush queue if we are suspended */
    if(isCapSuspended())
        getQueue().flush();
}

void SerialBusConnection::piStop() {
    mTimer.stop();
    disconnectDevice();
}

bool SerialBusConnection::piGetBusSettings(int pBusIdx, CANBus& pBus)
{
    return getBusConfig(pBusIdx, pBus);
}

void SerialBusConnection::piSetBusSettings(int pBusIdx, CANBus bus)
{
    CANConStatus stats;
    /* sanity checks */
    if(0 != pBusIdx)
        return;

    /* disconnect device if we have one connected */
    disconnectDevice();

    /* copy bus config */
    setBusConfig(0, bus);

    /* if bus is not active we are done */
    if(!bus.active)
        return;

    /* create device */
    QString errorString;
    mDev_p = QCanBus::instance()->createDevice("socketcan", getPort(), &errorString);
    if (!mDev_p) {
        disconnectDevice();
        qDebug() << "Error: createDevice(" << getType() << getPort() << "):" << errorString;
        return;
    }

    /* connect slots */
    connect(mDev_p, &QCanBusDevice::errorOccurred, this, &SerialBusConnection::errorReceived);
    connect(mDev_p, &QCanBusDevice::framesWritten, this, &SerialBusConnection::framesWritten);
    connect(mDev_p, &QCanBusDevice::framesReceived, this, &SerialBusConnection::framesReceived);

    /* set configuration */
    /*if (p.useConfigurationEnabled) {
     foreach (const SettingsDialog::ConfigurationItem &item, p.configurations)
         mDev->setConfigurationParameter(item.first, item.second);
    }*/

    //You cannot set the speed of a socketcan interface, it has to be set with console commands.
    //mDev_p->setConfigurationParameter(QCanBusDevice::BitRateKey, bus.speed);

    /* connect device */
    if (!mDev_p->connectDevice()) {
        disconnectDevice();
        qDebug() << "can't connect device";
    }
}

bool SerialBusConnection::piSendFrame(const CANFrame& pFrame)
{
    /* sanity checks */
    if(0 != pFrame.bus || pFrame.len>8)
        return false;
    if (!mDev_p) return false;

    /* fill frame */
    QCanBusFrame frame;
    frame.setFrameId(pFrame.ID);
    frame.setExtendedFrameFormat(pFrame.extended);
    frame.setPayload(QByteArray(reinterpret_cast<const char *>(pFrame.data),
                                static_cast<int>(pFrame.len)));

    return mDev_p->writeFrame(frame);
}

/***********************************/
/****   private methods         ****/
/***********************************/

/* disconnect device */
void SerialBusConnection::disconnectDevice() {
    if(mDev_p) {
        mDev_p->disconnectDevice();
        delete mDev_p;
        mDev_p = nullptr;
    }
}

void SerialBusConnection::errorReceived(QCanBusDevice::CanBusError error) const
{
    switch (error) {
        case QCanBusDevice::ReadError:
        case QCanBusDevice::WriteError:
        case QCanBusDevice::ConnectionError:
        case QCanBusDevice::ConfigurationError:
        case QCanBusDevice::UnknownError:
        qWarning() << mDev_p->errorString();
        break;
    default:
        break;
    }
}

void SerialBusConnection::framesWritten(qint64 count)
{
    Q_UNUSED(count);
    //qDebug() << "Number of frames written:" << count;
}

void SerialBusConnection::framesReceived()
{
    uint64_t timeBasis = CANConManager::getInstance()->getTimeBasis();

    /* sanity checks */
    if(!mDev_p)
        return;

    /* read frame */
    while(true)
    {
        const QCanBusFrame recFrame = mDev_p->readFrame();

        /* exit case */
        if(!recFrame.isValid())
            break;

        /* drop frame if capture is suspended */
        if(isCapSuspended())
            continue;

        /* check frame */
        if (recFrame.payload().length() <= 8) {
            CANFrame* frame_p = getQueue().get();
            if(frame_p) {
                frame_p->len           = static_cast<uint32_t>(recFrame.payload().length());
                frame_p->bus           = 0;
                if (recFrame.frameType() == QCanBusFrame::ErrorFrame) {
                    // Constants defined in include/uapi/linux/can/error.h
                    switch (recFrame.error()) {
                        case QCanBusFrame::TransmissionTimeoutError:
                            frame_p->ID = 0x20000001;
                            break;
                        case QCanBusFrame::LostArbitrationError:
                            frame_p->ID = 0x20000002;
                            break;
                        case QCanBusFrame::ControllerError:
                            frame_p->ID = 0x20000004;
                            break;
                        case QCanBusFrame::ProtocolViolationError:
                            frame_p->ID = 0x20000008;
                            break;
                        case QCanBusFrame::TransceiverError:
                            frame_p->ID = 0x20000010;
                            break;
                        case QCanBusFrame::MissingAcknowledgmentError:
                            frame_p->ID = 0x20000020;
                            break;
                        case QCanBusFrame::BusOffError:
                            frame_p->ID = 0x20000040;
                            break;
                        case QCanBusFrame::BusError:
                            frame_p->ID = 0x20000080;
                            break;
                        case QCanBusFrame::ControllerRestartError:
                            frame_p->ID = 0x20000100;
                            break;
                        default:
                            break;
                    }
                    frame_p->extended = true;
                } else {
                    frame_p->extended      = recFrame.hasExtendedFrameFormat();
                    frame_p->ID            = recFrame.frameId();
                    memcpy(frame_p->data, recFrame.payload().data(), frame_p->len);
                }
                frame_p->isReceived    = true;
                if (useSystemTime) {
                    frame_p->timestamp = QDateTime::currentMSecsSinceEpoch() * 1000ul;
                }
                else frame_p->timestamp     = (recFrame.timeStamp().seconds() * 1000000ul + recFrame.timeStamp().microSeconds()) - timeBasis;

                checkTargettedFrame(*frame_p);

                /* enqueue frame */
                getQueue().queue();
            }
#if 0
            else
                qDebug() << "can't get a frame, ERROR";
#endif
        }
    }
}

void SerialBusConnection::testConnection() {
    QCanBusDevice*  dev_p = QCanBus::instance()->createDevice("socketcan", getPort());
    CANConStatus stats;

    switch(getStatus())
    {
        case CANCon::CONNECTED:
            if (!dev_p || !dev_p->connectDevice()) {
                /* we have lost connectivity */
                disconnectDevice();

                setStatus(CANCon::NOT_CONNECTED);
                stats.conStatus = getStatus();
                stats.numHardwareBuses = mNumBuses;
                emit status(stats);
            }
            break;
        case CANCon::NOT_CONNECTED:
            if (dev_p && dev_p->connectDevice()) {
                if(!mDev_p) {
                    /* try to reconnect */
                    CANBus bus;
                    if(getBusConfig(0, bus))
                    {
                        bus.setEnabled(true);
                        setBusSettings(0, bus);
                    }
                }
                /* disconnect test instance */
                dev_p->disconnectDevice();

                setStatus(CANCon::CONNECTED);
                stats.conStatus = getStatus();
                stats.numHardwareBuses = mNumBuses;
                emit status(stats);
            }
            break;
        default: {}
    }

    if(dev_p)
        delete dev_p;
}
<|endoftext|>


<commit_before>#include <iostream>
#include "lib/w2b.h"
using namespace std;

//#define BUFFERSIZE 10000000
#define BUFFERSIZE 1000000

int main(int argc, char* argv[]) {
  for (int i=1; i<argc; i++) {
    FILE* filp = fopen(argv[i], "rb" );
    if (!filp) {return 1;}

    char* buffer = new char[BUFFERSIZE];
    int read = fread(buffer, sizeof(char), BUFFERSIZE, filp);
    fclose(filp);

    cout << read << endl;
    short buffer_edited[read/2];
    int count = 0;
    char arr[6] = {0,0,0,0,0,0};
    int arrcount = 0;

    for (int j=0; j<read; j++) {
      if (buffer[j] == '\n') {
        std::string str(arr);
        buffer_edited[count] = stoi(str);
        //cout << "str: " << str << " | num: " << buffer_edited[count] << endl;
        //buffer_edited[count] = dec_converter(arr);
        count++;
        for (int k=0; k<6; k++) arr[k] = 0;
        arrcount = 0;
      }
      else {
        arr[arrcount] = buffer[j];
        arrcount++;
      }
    }

    //for (int j=0; j<count; j++) cout << buffer_edited[j] << endl;

   writeBuffer(0, "out.wav", buffer_edited, count);
  }

  return 0;
}
<commit_msg>unbrokified f2wav<commit_after>#include <iostream>
#include <fstream>
#include "lib/w2b.h"
using namespace std;

#define BUFFERSIZE 1000000

int main(int argc, char* argv[]) {
  string buffone;
  short int bufftwo[BUFFERSIZE];
  int index = 0;
  ifstream ourFile;

  ourFile.open(argv[1]);

  while (getline(ourFile, buffone)) {
    if (index >= BUFFERSIZE) {
      break;
    }
    bufftwo[index] = stoi(buffone);
    index++;
  }

  writeBuffer(0, "out.wav", bufftwo, index + 1);

  return 0;
}
<|endoftext|>