<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
    (Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2012 Torus Knot Software Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgreViewport.h"

#include "OgreLogManager.h"
#include "OgreRenderTarget.h"
#include "OgreCamera.h"
#include "OgreMath.h"
#include "OgreRoot.h"
#include "OgreMaterialManager.h"
#include "OgreRenderSystem.h"
#include "OgreRenderWindow.h"

namespace Ogre {
    OrientationMode Viewport::mDefaultOrientationMode = OR_DEGREE_0;
    //---------------------------------------------------------------------
    Viewport::Viewport(Camera* cam, RenderTarget* target, Real left, Real top, Real width, Real height, int ZOrder)
        : mCamera(cam)
        , mTarget(target)
        , mRelLeft(left)
        , mRelTop(top)
        , mRelWidth(width)
        , mRelHeight(height)
        // Actual dimensions will update later
        , mZOrder(ZOrder)
        , mBackColour(ColourValue::Black)
		, mDepthClearValue(1)
        , mClearEveryFrame(true)
		, mClearBuffers(FBT_COLOUR | FBT_DEPTH)
        , mUpdated(false)
        , mShowOverlays(true)
        , mShowSkies(true)
		, mShowShadows(true)
		, mVisibilityMask(0xFFFFFFFF)
		, mRQSequence(0)
		, mMaterialSchemeName(MaterialManager::DEFAULT_SCHEME_NAME)
		, mIsAutoUpdated(true)
    {
#if OGRE_COMPILER != OGRE_COMPILER_GCCE && OGRE_PLATFORM != OGRE_PLATFORM_ANDROID
		LogManager::getSingleton().stream(LML_TRIVIAL)
			<< "Creating viewport on target '" << target->getName() << "'"
			<< ", rendering from camera '" << (cam != 0 ? cam->getName() : "NULL") << "'"
			<< ", relative dimensions "	<< std::ios::fixed << std::setprecision(2)
			<< "L: " << left << " T: " << top << " W: " << width << " H: " << height
			<< " ZOrder: " << ZOrder;
#endif

        // Set the default orientation mode
        mOrientationMode = mDefaultOrientationMode;

        // Set the default material scheme
        RenderSystem* rs = Root::getSingleton().getRenderSystem();
        mMaterialSchemeName = rs->_getDefaultViewportMaterialScheme();

        // Calculate actual dimensions
        _updateDimensions();

        // notify camera
        if(cam) cam->_notifyViewport(this);
    }
    //---------------------------------------------------------------------
    Viewport::~Viewport()
    {
		for (ListenerList::iterator i = mListeners.begin(); i != mListeners.end(); ++i)
		{
			(*i)->viewportDestroyed(this);
		}

		RenderSystem* rs = Root::getSingleton().getRenderSystem();
		if ((rs) && (rs->_getViewport() == this))
		{
			rs->_setViewport(NULL);
		}
    }
    //---------------------------------------------------------------------
    bool Viewport::_isUpdated(void) const
    {
        return mUpdated;
    }
    //---------------------------------------------------------------------
    void Viewport::_clearUpdatedFlag(void)
    {
        mUpdated = false;
    }
    //---------------------------------------------------------------------
    void Viewport::_updateDimensions(void)
    {
        Real height = (Real) mTarget->getHeight();
        Real width = (Real) mTarget->getWidth();

        mActLeft = (int) (mRelLeft * width);
        mActTop = (int) (mRelTop * height);
        mActWidth = (int) (mRelWidth * width);
        mActHeight = (int) (mRelHeight * height);

        // This will check if the cameras getAutoAspectRatio() property is set.
        // If it's true its aspect ratio is fit to the current viewport
        // If it's false the camera remains unchanged.
        // This allows cameras to be used to render to many viewports,
        // which can have their own dimensions and aspect ratios.

        if (mCamera)
        {
            if (mCamera->getAutoAspectRatio())
                mCamera->setAspectRatio((Real) mActWidth / (Real) mActHeight);

#if OGRE_NO_VIEWPORT_ORIENTATIONMODE == 0
            mCamera->setOrientationMode(mOrientationMode);
#endif
        }

#if OGRE_COMPILER != OGRE_COMPILER_GCCE
		LogManager::getSingleton().stream(LML_TRIVIAL)
			<< "Viewport for camera '" << (mCamera != 0 ? mCamera->getName() : "NULL") << "'"
			<< ", actual dimensions "	<< std::ios::fixed << std::setprecision(2)
			<< "L: " << mActLeft << " T: " << mActTop << " W: " << mActWidth << " H: " << mActHeight;
#endif

		 mUpdated = true;

		for (ListenerList::iterator i = mListeners.begin(); i != mListeners.end(); ++i)
		{
			(*i)->viewportDimensionsChanged(this);
		}
	}
	//---------------------------------------------------------------------
	int Viewport::getZOrder(void) const
	{
		return mZOrder;
	}
	//---------------------------------------------------------------------
    RenderTarget* Viewport::getTarget(void) const
    {
        return mTarget;
    }
    //---------------------------------------------------------------------
    Camera* Viewport::getCamera(void) const
    {
        return mCamera;
    }
    //---------------------------------------------------------------------
    Real Viewport::getLeft(void) const
    {
        return mRelLeft;
    }
    //---------------------------------------------------------------------
    Real Viewport::getTop(void) const
    {
        return mRelTop;
    }
    //---------------------------------------------------------------------
    Real Viewport::getWidth(void) const
    {
        return mRelWidth;
    }
    //---------------------------------------------------------------------
    Real Viewport::getHeight(void) const
    {
        return mRelHeight;
    }
    //---------------------------------------------------------------------
    int Viewport::getActualLeft(void) const
    {
        return mActLeft;
    }
    //---------------------------------------------------------------------
    int Viewport::getActualTop(void) const
    {
        return mActTop;
    }
    //---------------------------------------------------------------------
    int Viewport::getActualWidth(void) const
    {
        return mActWidth;
    }
    //---------------------------------------------------------------------
    int Viewport::getActualHeight(void) const
    {
        return mActHeight;
    }
    //---------------------------------------------------------------------
    void Viewport::setDimensions(Real left, Real top, Real width, Real height)
    {
        mRelLeft = left;
        mRelTop = top;
        mRelWidth = width;
        mRelHeight = height;
        _updateDimensions();
    }
    //---------------------------------------------------------------------
    void Viewport::update(void)
    {
        if (mCamera)
        {
            // Tell Camera to render into me
            mCamera->_renderScene(this, mShowOverlays);
        }
    }
    //---------------------------------------------------------------------
    void Viewport::setOrientationMode(OrientationMode orientationMode, bool setDefault)
    {
#if OGRE_NO_VIEWPORT_ORIENTATIONMODE != 0
        OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,
                    "Setting Viewport orientation mode is not supported",
                    __FUNCTION__);
#endif
        mOrientationMode = orientationMode;

        if (setDefault)
        {
            setDefaultOrientationMode(orientationMode);
        }

        if (mCamera)
        {
            mCamera->setOrientationMode(mOrientationMode);
        }

	// Update the render system config
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS
        RenderSystem* rs = Root::getSingleton().getRenderSystem();
        if(mOrientationMode == OR_LANDSCAPELEFT)
            rs->setConfigOption("Orientation", "Landscape Left");
        else if(mOrientationMode == OR_LANDSCAPERIGHT)
            rs->setConfigOption("Orientation", "Landscape Right");
        else if(mOrientationMode == OR_PORTRAIT)
            rs->setConfigOption("Orientation", "Portrait");
#endif
    }
    //---------------------------------------------------------------------
    OrientationMode Viewport::getOrientationMode() const
    {
#if OGRE_NO_VIEWPORT_ORIENTATIONMODE != 0
        OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,
                    "Getting Viewport orientation mode is not supported",
                    __FUNCTION__);
#endif
        return mOrientationMode;
    }
    //---------------------------------------------------------------------
    void Viewport::setDefaultOrientationMode(OrientationMode orientationMode)
    {
#if OGRE_NO_VIEWPORT_ORIENTATIONMODE != 0
        OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,
                    "Setting default Viewport orientation mode is not supported",
                    __FUNCTION__);
#endif
        mDefaultOrientationMode = orientationMode;
    }
    //---------------------------------------------------------------------
    OrientationMode Viewport::getDefaultOrientationMode()
    {
#if OGRE_NO_VIEWPORT_ORIENTATIONMODE != 0
        OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,
                    "Getting default Viewport orientation mode is not supported",
                    __FUNCTION__);
#endif
        return mDefaultOrientationMode;
    }
    //---------------------------------------------------------------------
    void Viewport::setBackgroundColour(const ColourValue& colour)
    {
        mBackColour = colour;
    }
    //---------------------------------------------------------------------
    const ColourValue& Viewport::getBackgroundColour(void) const
    {
        return mBackColour;
    }
    //---------------------------------------------------------------------
	void Viewport::setDepthClear( Real depth )
    {
        mDepthClearValue = depth;
    }
    //---------------------------------------------------------------------
    Real Viewport::getDepthClear(void) const
    {
        return mDepthClearValue;
    }
	//---------------------------------------------------------------------
    void Viewport::setClearEveryFrame(bool inClear, unsigned int inBuffers)
    {
        mClearEveryFrame = inClear;
		mClearBuffers = inBuffers;
    }
    //---------------------------------------------------------------------
    bool Viewport::getClearEveryFrame(void) const
    {
        return mClearEveryFrame;
    }
    //---------------------------------------------------------------------
    unsigned int Viewport::getClearBuffers(void) const
    {
        return mClearBuffers;
    }
    //---------------------------------------------------------------------
	void Viewport::clear(unsigned int buffers, const ColourValue& col,
						 Real depth, unsigned short stencil)
	{
		RenderSystem* rs = Root::getSingleton().getRenderSystem();
		if (rs)
		{
			Viewport* currentvp = rs->_getViewport();
			if (currentvp && currentvp == this)
				rs->clearFrameBuffer(buffers, col, depth, stencil);
			else if (currentvp)
			{
				rs->_setViewport(this);
				rs->clearFrameBuffer(buffers, col, depth, stencil);
				rs->_setViewport(currentvp);
			}
		}
	}
    //---------------------------------------------------------------------
    void Viewport::getActualDimensions(int &left, int&top, int &width, int &height) const
    {
        left = mActLeft;
        top = mActTop;
        width = mActWidth;
        height = mActHeight;

    }
    //---------------------------------------------------------------------
    unsigned int Viewport::_getNumRenderedFaces(void) const
    {
		return mCamera ? mCamera->_getNumRenderedFaces() : 0;
    }
    //---------------------------------------------------------------------
    unsigned int Viewport::_getNumRenderedBatches(void) const
    {
		return mCamera ? mCamera->_getNumRenderedBatches() : 0;
    }
	//---------------------------------------------------------------------
	void Viewport::setCamera(Camera* cam)
	{
		if(mCamera)
		{
			if(mCamera->getViewport() == this)
			{
				mCamera->_notifyViewport(0);
			}
		}

		mCamera = cam;
		if (cam)
		{
			// update aspect ratio of new camera if needed.
			if (cam->getAutoAspectRatio())
			{
				cam->setAspectRatio((Real) mActWidth / (Real) mActHeight);
			}
#if OGRE_NO_VIEWPORT_ORIENTATIONMODE == 0
			cam->setOrientationMode(mOrientationMode);
#endif
			cam->_notifyViewport(this);
		}

		for (ListenerList::iterator i = mListeners.begin(); i != mListeners.end(); ++i)
		{
			(*i)->viewportCameraChanged(this);
		}
    }
    //---------------------------------------------------------------------
	void Viewport::setAutoUpdated(bool inAutoUpdated)
	{
		mIsAutoUpdated = inAutoUpdated;
	}
	//---------------------------------------------------------------------
	bool Viewport::isAutoUpdated() const
	{
		return mIsAutoUpdated;
	}
	//---------------------------------------------------------------------
    void Viewport::setOverlaysEnabled(bool enabled)
    {
        mShowOverlays = enabled;
    }
    //---------------------------------------------------------------------
    bool Viewport::getOverlaysEnabled(void) const
    {
        return mShowOverlays;
    }
    //---------------------------------------------------------------------
    void Viewport::setSkiesEnabled(bool enabled)
    {
        mShowSkies = enabled;
    }
    //---------------------------------------------------------------------
    bool Viewport::getSkiesEnabled(void) const
    {
        return mShowSkies;
    }
    //---------------------------------------------------------------------
    void Viewport::setShadowsEnabled(bool enabled)
    {
        mShowShadows = enabled;
    }
    //---------------------------------------------------------------------
    bool Viewport::getShadowsEnabled(void) const
    {
        return mShowShadows;
    }
	//-----------------------------------------------------------------------
	void Viewport::setRenderQueueInvocationSequenceName(const String& sequenceName)
	{
		mRQSequenceName = sequenceName;
		if (mRQSequenceName.empty())
		{
			mRQSequence = 0;
		}
		else
		{
			mRQSequence =
				Root::getSingleton().getRenderQueueInvocationSequence(mRQSequenceName);
		}
	}
	//-----------------------------------------------------------------------
	const String& Viewport::getRenderQueueInvocationSequenceName(void) const
	{
		return mRQSequenceName;
	}
	//-----------------------------------------------------------------------
	RenderQueueInvocationSequence* Viewport::_getRenderQueueInvocationSequence(void)
	{
		return mRQSequence;
	}
	//-----------------------------------------------------------------------
    void Viewport::pointOrientedToScreen(const Vector2 &v, int orientationMode, Vector2 &outv)
    {
        pointOrientedToScreen(v.x, v.y, orientationMode, outv.x, outv.y);
    }
	//-----------------------------------------------------------------------
    void Viewport::pointOrientedToScreen(Real orientedX, Real orientedY, int orientationMode,
                                         Real &screenX, Real &screenY)
    {
        Real orX = orientedX;
        Real orY = orientedY;
        switch (orientationMode)
        {
        case 1:
            screenX = orY;
            screenY = Real(1.0) - orX;
            break;
        case 2:
            screenX = Real(1.0) - orX;
            screenY = Real(1.0) - orY;
            break;
        case 3:
            screenX = Real(1.0) - orY;
            screenY = orX;
            break;
        default:
            screenX = orX;
            screenY = orY;
            break;
        }
    }
	//-----------------------------------------------------------------------
	void Viewport::addListener(Listener* l)
	{
		if (std::find(mListeners.begin(), mListeners.end(), l) == mListeners.end())
			mListeners.push_back(l);
	}
	//-----------------------------------------------------------------------
	void Viewport::removeListener(Listener* l)
	{
		ListenerList::iterator i = std::find(mListeners.begin(), mListeners.end(), l);
		if (i != mListeners.end())
			mListeners.erase(i);
	}

}
<commit_msg>Make it possible to call Viewport::removeListener during viewportDestroyed event<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
    (Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2012 Torus Knot Software Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgreViewport.h"

#include "OgreLogManager.h"
#include "OgreRenderTarget.h"
#include "OgreCamera.h"
#include "OgreMath.h"
#include "OgreRoot.h"
#include "OgreMaterialManager.h"
#include "OgreRenderSystem.h"
#include "OgreRenderWindow.h"

namespace Ogre {
    OrientationMode Viewport::mDefaultOrientationMode = OR_DEGREE_0;
    //---------------------------------------------------------------------
    Viewport::Viewport(Camera* cam, RenderTarget* target, Real left, Real top, Real width, Real height, int ZOrder)
        : mCamera(cam)
        , mTarget(target)
        , mRelLeft(left)
        , mRelTop(top)
        , mRelWidth(width)
        , mRelHeight(height)
        // Actual dimensions will update later
        , mZOrder(ZOrder)
        , mBackColour(ColourValue::Black)
		, mDepthClearValue(1)
        , mClearEveryFrame(true)
		, mClearBuffers(FBT_COLOUR | FBT_DEPTH)
        , mUpdated(false)
        , mShowOverlays(true)
        , mShowSkies(true)
		, mShowShadows(true)
		, mVisibilityMask(0xFFFFFFFF)
		, mRQSequence(0)
		, mMaterialSchemeName(MaterialManager::DEFAULT_SCHEME_NAME)
		, mIsAutoUpdated(true)
    {
#if OGRE_COMPILER != OGRE_COMPILER_GCCE && OGRE_PLATFORM != OGRE_PLATFORM_ANDROID
		LogManager::getSingleton().stream(LML_TRIVIAL)
			<< "Creating viewport on target '" << target->getName() << "'"
			<< ", rendering from camera '" << (cam != 0 ? cam->getName() : "NULL") << "'"
			<< ", relative dimensions "	<< std::ios::fixed << std::setprecision(2)
			<< "L: " << left << " T: " << top << " W: " << width << " H: " << height
			<< " ZOrder: " << ZOrder;
#endif

        // Set the default orientation mode
        mOrientationMode = mDefaultOrientationMode;

        // Set the default material scheme
        RenderSystem* rs = Root::getSingleton().getRenderSystem();
        mMaterialSchemeName = rs->_getDefaultViewportMaterialScheme();

        // Calculate actual dimensions
        _updateDimensions();

        // notify camera
        if(cam) cam->_notifyViewport(this);
    }
    //---------------------------------------------------------------------
    Viewport::~Viewport()
    {
		ListenerList listenersCopy;
		std::swap(mListeners, listenersCopy);
		for (ListenerList::iterator i = listenersCopy.begin(); i != listenersCopy.end(); ++i)
		{
			(*i)->viewportDestroyed(this);
		}

		RenderSystem* rs = Root::getSingleton().getRenderSystem();
		if ((rs) && (rs->_getViewport() == this))
		{
			rs->_setViewport(NULL);
		}
    }
    //---------------------------------------------------------------------
    bool Viewport::_isUpdated(void) const
    {
        return mUpdated;
    }
    //---------------------------------------------------------------------
    void Viewport::_clearUpdatedFlag(void)
    {
        mUpdated = false;
    }
    //---------------------------------------------------------------------
    void Viewport::_updateDimensions(void)
    {
        Real height = (Real) mTarget->getHeight();
        Real width = (Real) mTarget->getWidth();

        mActLeft = (int) (mRelLeft * width);
        mActTop = (int) (mRelTop * height);
        mActWidth = (int) (mRelWidth * width);
        mActHeight = (int) (mRelHeight * height);

        // This will check if the cameras getAutoAspectRatio() property is set.
        // If it's true its aspect ratio is fit to the current viewport
        // If it's false the camera remains unchanged.
        // This allows cameras to be used to render to many viewports,
        // which can have their own dimensions and aspect ratios.

        if (mCamera)
        {
            if (mCamera->getAutoAspectRatio())
                mCamera->setAspectRatio((Real) mActWidth / (Real) mActHeight);

#if OGRE_NO_VIEWPORT_ORIENTATIONMODE == 0
            mCamera->setOrientationMode(mOrientationMode);
#endif
        }

#if OGRE_COMPILER != OGRE_COMPILER_GCCE
		LogManager::getSingleton().stream(LML_TRIVIAL)
			<< "Viewport for camera '" << (mCamera != 0 ? mCamera->getName() : "NULL") << "'"
			<< ", actual dimensions "	<< std::ios::fixed << std::setprecision(2)
			<< "L: " << mActLeft << " T: " << mActTop << " W: " << mActWidth << " H: " << mActHeight;
#endif

		 mUpdated = true;

		for (ListenerList::iterator i = mListeners.begin(); i != mListeners.end(); ++i)
		{
			(*i)->viewportDimensionsChanged(this);
		}
	}
	//---------------------------------------------------------------------
	int Viewport::getZOrder(void) const
	{
		return mZOrder;
	}
	//---------------------------------------------------------------------
    RenderTarget* Viewport::getTarget(void) const
    {
        return mTarget;
    }
    //---------------------------------------------------------------------
    Camera* Viewport::getCamera(void) const
    {
        return mCamera;
    }
    //---------------------------------------------------------------------
    Real Viewport::getLeft(void) const
    {
        return mRelLeft;
    }
    //---------------------------------------------------------------------
    Real Viewport::getTop(void) const
    {
        return mRelTop;
    }
    //---------------------------------------------------------------------
    Real Viewport::getWidth(void) const
    {
        return mRelWidth;
    }
    //---------------------------------------------------------------------
    Real Viewport::getHeight(void) const
    {
        return mRelHeight;
    }
    //---------------------------------------------------------------------
    int Viewport::getActualLeft(void) const
    {
        return mActLeft;
    }
    //---------------------------------------------------------------------
    int Viewport::getActualTop(void) const
    {
        return mActTop;
    }
    //---------------------------------------------------------------------
    int Viewport::getActualWidth(void) const
    {
        return mActWidth;
    }
    //---------------------------------------------------------------------
    int Viewport::getActualHeight(void) const
    {
        return mActHeight;
    }
    //---------------------------------------------------------------------
    void Viewport::setDimensions(Real left, Real top, Real width, Real height)
    {
        mRelLeft = left;
        mRelTop = top;
        mRelWidth = width;
        mRelHeight = height;
        _updateDimensions();
    }
    //---------------------------------------------------------------------
    void Viewport::update(void)
    {
        if (mCamera)
        {
            // Tell Camera to render into me
            mCamera->_renderScene(this, mShowOverlays);
        }
    }
    //---------------------------------------------------------------------
    void Viewport::setOrientationMode(OrientationMode orientationMode, bool setDefault)
    {
#if OGRE_NO_VIEWPORT_ORIENTATIONMODE != 0
        OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,
                    "Setting Viewport orientation mode is not supported",
                    __FUNCTION__);
#endif
        mOrientationMode = orientationMode;

        if (setDefault)
        {
            setDefaultOrientationMode(orientationMode);
        }

        if (mCamera)
        {
            mCamera->setOrientationMode(mOrientationMode);
        }

	// Update the render system config
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS
        RenderSystem* rs = Root::getSingleton().getRenderSystem();
        if(mOrientationMode == OR_LANDSCAPELEFT)
            rs->setConfigOption("Orientation", "Landscape Left");
        else if(mOrientationMode == OR_LANDSCAPERIGHT)
            rs->setConfigOption("Orientation", "Landscape Right");
        else if(mOrientationMode == OR_PORTRAIT)
            rs->setConfigOption("Orientation", "Portrait");
#endif
    }
    //---------------------------------------------------------------------
    OrientationMode Viewport::getOrientationMode() const
    {
#if OGRE_NO_VIEWPORT_ORIENTATIONMODE != 0
        OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,
                    "Getting Viewport orientation mode is not supported",
                    __FUNCTION__);
#endif
        return mOrientationMode;
    }
    //---------------------------------------------------------------------
    void Viewport::setDefaultOrientationMode(OrientationMode orientationMode)
    {
#if OGRE_NO_VIEWPORT_ORIENTATIONMODE != 0
        OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,
                    "Setting default Viewport orientation mode is not supported",
                    __FUNCTION__);
#endif
        mDefaultOrientationMode = orientationMode;
    }
    //---------------------------------------------------------------------
    OrientationMode Viewport::getDefaultOrientationMode()
    {
#if OGRE_NO_VIEWPORT_ORIENTATIONMODE != 0
        OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,
                    "Getting default Viewport orientation mode is not supported",
                    __FUNCTION__);
#endif
        return mDefaultOrientationMode;
    }
    //---------------------------------------------------------------------
    void Viewport::setBackgroundColour(const ColourValue& colour)
    {
        mBackColour = colour;
    }
    //---------------------------------------------------------------------
    const ColourValue& Viewport::getBackgroundColour(void) const
    {
        return mBackColour;
    }
    //---------------------------------------------------------------------
	void Viewport::setDepthClear( Real depth )
    {
        mDepthClearValue = depth;
    }
    //---------------------------------------------------------------------
    Real Viewport::getDepthClear(void) const
    {
        return mDepthClearValue;
    }
	//---------------------------------------------------------------------
    void Viewport::setClearEveryFrame(bool inClear, unsigned int inBuffers)
    {
        mClearEveryFrame = inClear;
		mClearBuffers = inBuffers;
    }
    //---------------------------------------------------------------------
    bool Viewport::getClearEveryFrame(void) const
    {
        return mClearEveryFrame;
    }
    //---------------------------------------------------------------------
    unsigned int Viewport::getClearBuffers(void) const
    {
        return mClearBuffers;
    }
    //---------------------------------------------------------------------
	void Viewport::clear(unsigned int buffers, const ColourValue& col,
						 Real depth, unsigned short stencil)
	{
		RenderSystem* rs = Root::getSingleton().getRenderSystem();
		if (rs)
		{
			Viewport* currentvp = rs->_getViewport();
			if (currentvp && currentvp == this)
				rs->clearFrameBuffer(buffers, col, depth, stencil);
			else if (currentvp)
			{
				rs->_setViewport(this);
				rs->clearFrameBuffer(buffers, col, depth, stencil);
				rs->_setViewport(currentvp);
			}
		}
	}
    //---------------------------------------------------------------------
    void Viewport::getActualDimensions(int &left, int&top, int &width, int &height) const
    {
        left = mActLeft;
        top = mActTop;
        width = mActWidth;
        height = mActHeight;

    }
    //---------------------------------------------------------------------
    unsigned int Viewport::_getNumRenderedFaces(void) const
    {
		return mCamera ? mCamera->_getNumRenderedFaces() : 0;
    }
    //---------------------------------------------------------------------
    unsigned int Viewport::_getNumRenderedBatches(void) const
    {
		return mCamera ? mCamera->_getNumRenderedBatches() : 0;
    }
	//---------------------------------------------------------------------
	void Viewport::setCamera(Camera* cam)
	{
		if(mCamera)
		{
			if(mCamera->getViewport() == this)
			{
				mCamera->_notifyViewport(0);
			}
		}

		mCamera = cam;
		if (cam)
		{
			// update aspect ratio of new camera if needed.
			if (cam->getAutoAspectRatio())
			{
				cam->setAspectRatio((Real) mActWidth / (Real) mActHeight);
			}
#if OGRE_NO_VIEWPORT_ORIENTATIONMODE == 0
			cam->setOrientationMode(mOrientationMode);
#endif
			cam->_notifyViewport(this);
		}

		for (ListenerList::iterator i = mListeners.begin(); i != mListeners.end(); ++i)
		{
			(*i)->viewportCameraChanged(this);
		}
    }
    //---------------------------------------------------------------------
	void Viewport::setAutoUpdated(bool inAutoUpdated)
	{
		mIsAutoUpdated = inAutoUpdated;
	}
	//---------------------------------------------------------------------
	bool Viewport::isAutoUpdated() const
	{
		return mIsAutoUpdated;
	}
	//---------------------------------------------------------------------
    void Viewport::setOverlaysEnabled(bool enabled)
    {
        mShowOverlays = enabled;
    }
    //---------------------------------------------------------------------
    bool Viewport::getOverlaysEnabled(void) const
    {
        return mShowOverlays;
    }
    //---------------------------------------------------------------------
    void Viewport::setSkiesEnabled(bool enabled)
    {
        mShowSkies = enabled;
    }
    //---------------------------------------------------------------------
    bool Viewport::getSkiesEnabled(void) const
    {
        return mShowSkies;
    }
    //---------------------------------------------------------------------
    void Viewport::setShadowsEnabled(bool enabled)
    {
        mShowShadows = enabled;
    }
    //---------------------------------------------------------------------
    bool Viewport::getShadowsEnabled(void) const
    {
        return mShowShadows;
    }
	//-----------------------------------------------------------------------
	void Viewport::setRenderQueueInvocationSequenceName(const String& sequenceName)
	{
		mRQSequenceName = sequenceName;
		if (mRQSequenceName.empty())
		{
			mRQSequence = 0;
		}
		else
		{
			mRQSequence =
				Root::getSingleton().getRenderQueueInvocationSequence(mRQSequenceName);
		}
	}
	//-----------------------------------------------------------------------
	const String& Viewport::getRenderQueueInvocationSequenceName(void) const
	{
		return mRQSequenceName;
	}
	//-----------------------------------------------------------------------
	RenderQueueInvocationSequence* Viewport::_getRenderQueueInvocationSequence(void)
	{
		return mRQSequence;
	}
	//-----------------------------------------------------------------------
    void Viewport::pointOrientedToScreen(const Vector2 &v, int orientationMode, Vector2 &outv)
    {
        pointOrientedToScreen(v.x, v.y, orientationMode, outv.x, outv.y);
    }
	//-----------------------------------------------------------------------
    void Viewport::pointOrientedToScreen(Real orientedX, Real orientedY, int orientationMode,
                                         Real &screenX, Real &screenY)
    {
        Real orX = orientedX;
        Real orY = orientedY;
        switch (orientationMode)
        {
        case 1:
            screenX = orY;
            screenY = Real(1.0) - orX;
            break;
        case 2:
            screenX = Real(1.0) - orX;
            screenY = Real(1.0) - orY;
            break;
        case 3:
            screenX = Real(1.0) - orY;
            screenY = orX;
            break;
        default:
            screenX = orX;
            screenY = orY;
            break;
        }
    }
	//-----------------------------------------------------------------------
	void Viewport::addListener(Listener* l)
	{
		if (std::find(mListeners.begin(), mListeners.end(), l) == mListeners.end())
			mListeners.push_back(l);
	}
	//-----------------------------------------------------------------------
	void Viewport::removeListener(Listener* l)
	{
		ListenerList::iterator i = std::find(mListeners.begin(), mListeners.end(), l);
		if (i != mListeners.end())
			mListeners.erase(i);
	}

}
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "modules/video_coding/packet_buffer.h"
#include "system_wrappers/include/clock.h"
#include "test/fuzzers/fuzz_data_helper.h"

namespace webrtc {
namespace {
class NullCallback : public video_coding::OnReceivedFrameCallback {
  void OnReceivedFrame(std::unique_ptr<video_coding::RtpFrameObject> frame) {}
};
}  // namespace

void FuzzOneInput(const uint8_t* data, size_t size) {
  VCMPacket packet;
  NullCallback callback;
  SimulatedClock clock(0);
  rtc::scoped_refptr<video_coding::PacketBuffer> packet_buffer(
      video_coding::PacketBuffer::Create(&clock, 8, 1024, &callback));
  test::FuzzDataHelper helper(rtc::ArrayView<const uint8_t>(data, size));

  while (helper.BytesLeft())
    helper.CopyTo(&packet);
}

}  // namespace webrtc
<commit_msg>Actually input packets into the PacketBuffer.<commit_after>/*
 *  Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "modules/video_coding/packet_buffer.h"
#include "system_wrappers/include/clock.h"
#include "test/fuzzers/fuzz_data_helper.h"

namespace webrtc {
namespace {
class NullCallback : public video_coding::OnReceivedFrameCallback {
  void OnReceivedFrame(std::unique_ptr<video_coding::RtpFrameObject> frame) {}
};
}  // namespace

void FuzzOneInput(const uint8_t* data, size_t size) {
  VCMPacket packet;
  NullCallback callback;
  SimulatedClock clock(0);
  rtc::scoped_refptr<video_coding::PacketBuffer> packet_buffer(
      video_coding::PacketBuffer::Create(&clock, 8, 1024, &callback));
  test::FuzzDataHelper helper(rtc::ArrayView<const uint8_t>(data, size));

  while (helper.BytesLeft()) {
    // The RTPVideoHeader is a complex type, so overwriting it with random data
    // will put it in an invalid state. Therefore we save/restore it.
    uint8_t video_header_backup[sizeof(packet.video_header)];
    memcpy(&video_header_backup, &packet.video_header,
           sizeof(packet.video_header));

    helper.CopyTo(&packet);

    memcpy(&packet.video_header, &video_header_backup,
           sizeof(packet.video_header));

    // The packet buffer owns the payload of the packet.
    uint8_t payload_size;
    helper.CopyTo(&payload_size);
    packet.sizeBytes = payload_size;
    packet.dataPtr = new uint8_t[payload_size];

    packet_buffer->InsertPacket(&packet);
  }
}

}  // namespace webrtc
<|endoftext|>


<commit_before>/*
 * ArduinoNunchuk.cpp - Improved Wii Nunchuk library for Arduino
 *
 * Copyright 2011-2013 Gabriel Bianconi, http://www.gabrielbianconi.com/
 *
 * Project URL: http://www.gabrielbianconi.com/projects/arduinonunchuk/
 *
 * Based on the following resources:
 *   http://www.windmeadow.com/node/42
 *   http://todbot.com/blog/2008/02/18/wiichuck-wii-nunchuck-adapter-available/
 *   http://wiibrew.org/wiki/Wiimote/Extension_Controllers
 *
 */

#include <Arduino.h>
#include <Wire.h>
#include "ArduinoNunchuk.h"

#define ADDRESS 0x52

void ArduinoNunchuk::init()
{
  Wire.begin();

  ArduinoNunchuk::_sendByte(0x55, 0xF0);
  ArduinoNunchuk::_sendByte(0x00, 0xFB);

  ArduinoNunchuk::update();
}

void ArduinoNunchuk::update()
{
  int count = 0;
  int values[6];

  Wire.requestFrom(ADDRESS, 6);

  while(Wire.available())
  {
    values[count] = Wire.read();
    count++;
  }

  ArduinoNunchuk::analogX = values[0];
  ArduinoNunchuk::analogY = values[1];
  ArduinoNunchuk::accelX = values[2] * 2 * 2 + ((values[5] >> 2) & 1) * 2 + ((values[5] >> 3) & 1);
  ArduinoNunchuk::accelY = values[3] * 2 * 2 + ((values[5] >> 4) & 1) * 2 + ((values[5] >> 5) & 1);
  ArduinoNunchuk::accelZ = values[4] * 2 * 2 + ((values[5] >> 6) & 1) * 2 + ((values[5] >> 7) & 1);
  ArduinoNunchuk::zButton = !((values[5] >> 0) & 1);
  ArduinoNunchuk::cButton = !((values[5] >> 1) & 1);

  ArduinoNunchuk::_sendByte(0x00, 0x00);
}

void ArduinoNunchuk::_sendByte(byte data, byte location)
{
  Wire.beginTransmission(ADDRESS);

  Wire.write(location);
  Wire.write(data);

  Wire.endTransmission();

  delay(10);
}<commit_msg>Fixed Issue #2. Credit: MartyMacGyver<commit_after>/*
 * ArduinoNunchuk.cpp - Improved Wii Nunchuk library for Arduino
 *
 * Copyright 2011-2013 Gabriel Bianconi, http://www.gabrielbianconi.com/
 *
 * Project URL: http://www.gabrielbianconi.com/projects/arduinonunchuk/
 *
 * Based on the following resources:
 *   http://www.windmeadow.com/node/42
 *   http://todbot.com/blog/2008/02/18/wiichuck-wii-nunchuck-adapter-available/
 *   http://wiibrew.org/wiki/Wiimote/Extension_Controllers
 *
 */

#include <Arduino.h>
#include <Wire.h>
#include "ArduinoNunchuk.h"

#define ADDRESS 0x52

void ArduinoNunchuk::init()
{
  Wire.begin();

  ArduinoNunchuk::_sendByte(0x55, 0xF0);
  ArduinoNunchuk::_sendByte(0x00, 0xFB);

  ArduinoNunchuk::update();
}

void ArduinoNunchuk::update()
{
  int count = 0;
  int values[6];

  Wire.requestFrom(ADDRESS, 6);

  while(Wire.available())
  {
    values[count] = Wire.read();
    count++;
  }

  ArduinoNunchuk::analogX = values[0];
  ArduinoNunchuk::analogY = values[1];
  ArduinoNunchuk::accelX = (values[2] << 2) | ((values[5] >> 2) & 3);
  ArduinoNunchuk::accelY = (values[3] << 2) | ((values[5] >> 4) & 3);
  ArduinoNunchuk::accelZ = (values[4] << 2) | ((values[5] >> 6) & 3);
  ArduinoNunchuk::zButton = !((values[5] >> 0) & 1);
  ArduinoNunchuk::cButton = !((values[5] >> 1) & 1);

  ArduinoNunchuk::_sendByte(0x00, 0x00);
}

void ArduinoNunchuk::_sendByte(byte data, byte location)
{
  Wire.beginTransmission(ADDRESS);

  Wire.write(location);
  Wire.write(data);

  Wire.endTransmission();

  delay(10);
}<|endoftext|>


<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
*                                                                        *
* Author: The ALICE Off-line Project.                                    *
* Contributors are mentioned in the code where appropriate.              *
*                                                                        *
* Permission to use, copy, modify and distribute this software and its   *
* documentation strictly for non-commercial purposes is hereby granted   *
* without fee, provided that the above copyright notice appears in all   *
* copies and that both the copyright notice and this permission notice   *
* appear in the supporting documentation. The authors make no claims     *
* about the suitability of this software for any purpose. It is          *
* provided "as is" without express or implied warranty.                  *
**************************************************************************/
//
// Collection class for histograms
// Stores either histograms or vectors of histograms
//
// Author:
// Matus Kalisky  <matus.kalisky@cern.ch>
//

//#include <iostream>

#include <TH1F.h>
#include <TH2F.h>
#include <THnSparse.h>
#include <TProfile.h>
#include <TString.h>
#include <TBrowser.h>
#include <TMath.h>

#include "AliLog.h"
#include "AliHFEcollection.h"

using namespace std;

ClassImp(AliHFEcollection)

//___________________________________________________________________
AliHFEcollection::AliHFEcollection():
  TNamed()
  , fList(0x0)
{

  //
  // default constructor
  //

  fList = new THashList();
  if(!fList){
    AliError("Initialization of the list failed");
  }
  else{
    // list is owner of the objects. Once list is deleted, the objects
    // it contains will be deleted too
    //fList->SetOwner(kTRUE);
  }
  //Printf("%s:%d,%p",(char*)__FILE__,__LINE__,fInstance);

}
//___________________________________________________________________
AliHFEcollection::AliHFEcollection(char* name, char* title):
  TNamed(name, title)
  , fList(0x0)
{

  //
  // constructor
  //

  fList = new THashList();
  if(!fList){
    AliError("Initialization of the list failed");
  }
  else{
    // list is owner of the objects. Once list is deleted, the objects
    // it contains will be deleted too
    // fList->SetOwner(kTRUE);
  }
}
//___________________________________________________________________
AliHFEcollection::AliHFEcollection(const AliHFEcollection &c) :
  TNamed(c)
  , fList(0x0)
{

  //
  // copy operator
  //

  c.Copy(*this);
}
//___________________________________________________________________
AliHFEcollection &AliHFEcollection::operator=(const AliHFEcollection &ref)
{
  //
  // Assignment operator
  //

  if(this != &ref){
    ref.Copy(*this);
  }
  return *this;
}
//___________________________________________________________________
void AliHFEcollection::Copy(TObject &ref) const {

  //
  // Performs the copying of the object
  //

  AliHFEcollection &target = dynamic_cast<AliHFEcollection &>(ref);

  // Clone List Content
  target.fList = new THashList();
  for(Int_t ien = 0; ien < fList->GetEntries(); ien++)
    target.fList->Add(fList->At(ien)->Clone());
}
//___________________________________________________________________
AliHFEcollection::~AliHFEcollection(){

  //
  // Destructor
  //
  if(fList)
    fList->Delete();
  delete fList;
  AliInfo("DESTRUCTOR");
}
//___________________________________________________________________
Bool_t AliHFEcollection::CreateTH1F(const char* name, const char* title, Int_t nBin, Float_t nMin, Float_t nMax){

  //
  // Creates a TH1F histogram for the collection
  //

  if(!fList){
    AliError("No TList pointer ! ");
    return kFALSE;
  }
  else{
    fList->Add(new TH1F(name, title, nBin, nMin, nMax));
    return CheckObject(name);
  }
}
//___________________________________________________________________
Bool_t AliHFEcollection::CreateTH2F(const char* name, const char* title, Int_t nBinX, Float_t nMinX, Float_t nMaxX, Int_t nBinY, Float_t nMinY, Float_t nMaxY){

  //
  // Creates a TH2F histogram for the collection
  //

  if(!fList){
    AliError("No TList pointer ! ");
    return kFALSE;
  }
  fList->Add(new TH2F(name, title, nBinX, nMinX, nMaxX, nBinY, nMinY, nMaxY));
  return CheckObject(name);
}
//___________________________________________________________________
Bool_t AliHFEcollection::CreateTH1Fvector1(Int_t X, const char* name, const char* title, Int_t nBin, Float_t nMin, Float_t nMax){

  //
  // create a 1 dimensional array of size [X]
  //

  if(!fList){
    AliError("No TList pointer ! ");
    return kFALSE;
  }
  if(X <=0){
    AliError("can not create array with negative or zero size ");
    return kFALSE;
  }
  TString hname;
  for(Int_t i=0; i<X; ++i){
    hname = "";
    hname.Append(Form("%s_[%d]", name, i));
    //cout<<" -D: name: "<<name.str().c_str()<<endl;
    //cout<<" -D: nBin: "<<_nBin<<" ,Min: "<<_nMin<<" , Max: "<<_nMax<<endl;
    CreateTH1F(hname.Data(), title, nBin, nMin, nMax);
    if(!CheckObject(hname.Data())){
      AliError(Form("Not possible to create object: ", hname.Data()));
      return kFALSE;
    }
  }
  return kTRUE;
}
//___________________________________________________________________
Bool_t AliHFEcollection::CreateTH2Fvector1(Int_t X, const char* name, const char* title, Int_t nBinX, Float_t nMinX, Float_t nMaxX, Int_t nBinY, Float_t nMinY, Float_t nMaxY){

  //
  // create a 1 dimensinal array of TH2F histograms with size [X]
  //

  if(!fList){
    AliError("No TList pointer !");
    return kFALSE;
  }
  if(X <=0){
    AliError("can not create array with negative or zero size ");
    return kFALSE;
  }
  TString hname;
  for(Int_t i=0; i<X; ++i){
    hname = "";
    hname.Append(Form("%s_[%d]", name, i));
    //cout<<" -D: name: "<<name<<endl;
    //cout<<" -D: nBin: "<<_nBin<<" ,Min: "<<_nMin<<" , Max: "<<_nMax<<endl;
    CreateTH2F(hname.Data(), title, nBinX, nMinX, nMaxX, nBinY, nMinY, nMaxY);
    if(!CheckObject(hname.Data())){
      AliError(Form("Not possible to create object: %s", hname.Data()));
      return kFALSE;
    }
  }
  return kTRUE;
}
//___________________________________________________________________
Bool_t AliHFEcollection::CreateTH1Fvector2(Int_t X, Int_t Y, const char* name, const char* title, Int_t nBin, Float_t nMin, Float_t nMax){

  //
  // create a 2 dimensional array of histograms of size [X, Y]
  //

  if(!fList){
    AliError("No TList pointer ! ");
    return kFALSE;
  }
  if(X <=0 || Y <=0){
    AliError("can not create array with negative or zero size ");
    return kFALSE;
  }
  TString hname;
  for(Int_t i=0; i<X; ++i){
    for(Int_t j=0; j<Y; ++j){
      hname = "";
      hname.Append(Form("%s_[%d][%d]", name, i, j));
      //cout<<" -D: name: "<<name.str().c_str()<<endl;
      //cout<<" -D: nBin: "<<_nBin<<" ,Min: "<<_nMin<<" , Max: "<<_nMax<<endl;
      CreateTH1F(hname.Data(), title, nBin, nMin, nMax);
      if(!CheckObject(hname.Data())){
	      AliError(Form("Not possible to create object: %s", hname.Data()));
	      return kFALSE;
      }
    }
  }
  return kTRUE;
}
//___________________________________________________________________
Bool_t AliHFEcollection::CreateProfile(const char* name, const char* title, Int_t nbins, Double_t xmin, Double_t xmax){

  //
  // create a simple TProfile
  //

  if(!fList){
    AliError("No TList pointer ! ");
    return kFALSE;
  }
  fList->Add(new TProfile(name, title, nbins, xmin, xmax));
  return CheckObject(name);

}
//___________________________________________________________________
Bool_t AliHFEcollection::CreateTHnSparse(const char* name, const char* title, Int_t dim, Int_t* nbins, Double_t* xmin, Double_t* xmax){

  //
  // create 'dim' dimensional THnSparse
  //

  if(!fList){
    AliError("No TList pointer ! ");
    return kFALSE;
  }
  fList->Add(new THnSparseF(name, title, dim, nbins, xmin, xmax));
  return CheckObject(name);

}
//___________________________________________________________________
TObject* AliHFEcollection::Get(const char* name){

  //
  // Get histogram with the required name
  //

  if(!CheckObject(name)){
    AliWarning(Form("Not possible to return pointer to the object '%s'\n", name));
    return 0;
  }

  return fList->FindObject(name);

}
//___________________________________________________________________
Bool_t AliHFEcollection::Fill(const char* name, Double_t v){

  //
  // fill function for one TH1 histograms
  //

   if(!CheckObject(name)){
    AliError(Form("Not possible to return pointer to the object '%s'\n", name));
    return kFALSE;
  }

  // chack the possible object types
  if(fList->FindObject(name)->InheritsFrom("TH1")){
    (dynamic_cast<TH1F*>(fList->FindObject(name)))->Fill(v);
    return kTRUE;
  }

  return kFALSE;

}
//___________________________________________________________________
Bool_t AliHFEcollection::Fill(const char* name, Int_t X, Double_t v){

  //
  // fill function for one dimension arrays of TH1
  //

  const char* n = Form("%s_[%d]", name, X);
  TObject *o = Get(n);
  if(!o){
    return kFALSE;
  }
  Fill(o->GetName(), v);
  return kTRUE;
}
//___________________________________________________________________
Bool_t AliHFEcollection::Fill(const char* name, Int_t X, Int_t Y, Double_t v){

  //
  // Fill function fir 2 dimensional TH1 arrays
  //

  const char* n = Form("%s_[%d][%d]", name, X, Y);
  TObject *o = Get(n);
  if(!o){
    return kFALSE;
  }
  Fill(o->GetName(), v);
  return kTRUE;
}
//___________________________________________________________________
Bool_t AliHFEcollection::Fill(const char* name, Int_t X, Double_t v1, Double_t v2){

  //
  // fill function for one dimension array of TH2
  //

  const char* n = Form("%s_[%d]", name, X);
  TObject *o = Get(n);
  if(!o){
    return kFALSE;
  }
  Fill(o->GetName(), v1, v2);

  return kTRUE;
}
//___________________________________________________________________
Bool_t AliHFEcollection::Fill(const char* name, Double_t v1, Double_t v2){

  //
  // fill function for TH2 objects
  //

   if(!CheckObject(name)){
    AliError(Form("Not possible to return pointer to the object '%s'\n", name));
    return kFALSE;
  }

  // chack the possible object types
  if(fList->FindObject(name)->InheritsFrom("TH2")){
    (dynamic_cast<TH2F*>(fList->FindObject(name)))->Fill(v1, v2);
    return kTRUE;
  }
  if(fList->FindObject(name)->InheritsFrom("TProfile")){
    (dynamic_cast<TProfile*>(fList->FindObject(name)))->Fill(v1, v2);
    return kTRUE;
  }

  return kFALSE;

}

//___________________________________________________________________
Bool_t AliHFEcollection::CheckObject(const char* name){

  //
  // check wheter the creation of the histogram was succesfull
  //

  if(!fList){
    AliError("No TList pointer ! ");
    return kFALSE;
  }

  if(!fList->FindObject(name)){
    AliWarning(Form("Creating or Finding the object '%s' failed\n", name));
    return kFALSE;
  }
  return kTRUE;
}
//___________________________________________________________________
Bool_t AliHFEcollection::Sumw2(const char* name){
  //
  // Set Sumw2 for the given object
  //
  if(!CheckObject(name)){
    return kFALSE;
  }

  TObject *o = Get(name);
  if(o->InheritsFrom("THnSparse")){
    (dynamic_cast<THnSparse*>(o))->Sumw2();
  }
  return kTRUE;
}
//___________________________________________________________________
Bool_t AliHFEcollection::BinLogAxis(const char* name, Int_t dim){

  //
  // converts the axis (defined by the dimension) of THx or THnSparse
  // object to Log scale. Number of bins and bin min and bin max are preserved
  //

  if(!CheckObject(name)){
    return kFALSE;
  }

  TObject *o = Get(name);
  TAxis *axis = 0x0;
  if(o->InheritsFrom("TH1")){
    axis = (dynamic_cast<TH1F*>(o))->GetXaxis();
  }
  if(o->InheritsFrom("TH2")){
    if(0 == dim){
      axis = (dynamic_cast<TH2F*>(o))->GetXaxis();
    }
    else if(1 == dim){
      axis = (dynamic_cast<TH2F*>(o))->GetYaxis();
    }
     else{
       AliError("Only dim = 0 or 1 possible for TH2F");
     }
  }
  if(o->InheritsFrom("THnSparse")){
    axis = (dynamic_cast<THnSparse*>(o))->GetAxis(dim);
  }

  if(!axis){
    AliError(Form("Axis '%d' could not be identified in the object '%s'\n", dim, name));
    return kFALSE;
  }

  Int_t bins = axis->GetNbins();

  Double_t from = axis->GetXmin();
  Double_t to = axis->GetXmax();
  Double_t *newBins = new Double_t[bins+1];
  newBins[0] = from;
  Double_t factor = TMath::Power(to/from, 1./bins);
  for(Int_t i=1; i<=bins; ++i){
    newBins[i] = factor * newBins[i-1];
  }
  axis->Set(bins, newBins);
  delete newBins;

  return kTRUE;

}
//___________________________________________________________________
Long64_t AliHFEcollection::Merge(TCollection *list){

  //
  // Merge the collections
  //
  if(!list)
    return 0;
  if(list->IsEmpty())
    return 1;

  TIterator *iter = list->MakeIterator();
  TObject *o = NULL;
  Int_t index = 0;
  while((o = iter->Next())){
    AliHFEcollection *coll = dynamic_cast<AliHFEcollection *>(o);
    if(!coll) continue;
    TList templist;       // Create temporary list containing all the lists to merge
    templist.Add(coll->fList);
    fList->Merge(&templist);
    index++;
  }
  delete iter;
  return index + 1;
}
//____________________________________________________________________
void AliHFEcollection::Browse(TBrowser *b)
{

  //
  // Browse the content of the directory.
  //

   if (b) {
      TObject *obj = 0;
      TIter nextin(fList);

      //Add objects that are only in memory
      while ((obj = nextin())) {
         b->Add(obj, obj->GetName());
      }
   }
}
<commit_msg>Fixed warning<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
*                                                                        *
* Author: The ALICE Off-line Project.                                    *
* Contributors are mentioned in the code where appropriate.              *
*                                                                        *
* Permission to use, copy, modify and distribute this software and its   *
* documentation strictly for non-commercial purposes is hereby granted   *
* without fee, provided that the above copyright notice appears in all   *
* copies and that both the copyright notice and this permission notice   *
* appear in the supporting documentation. The authors make no claims     *
* about the suitability of this software for any purpose. It is          *
* provided "as is" without express or implied warranty.                  *
**************************************************************************/
//
// Collection class for histograms
// Stores either histograms or vectors of histograms
//
// Author:
// Matus Kalisky  <matus.kalisky@cern.ch>
//

//#include <iostream>

#include <TH1F.h>
#include <TH2F.h>
#include <THnSparse.h>
#include <TProfile.h>
#include <TString.h>
#include <TBrowser.h>
#include <TMath.h>

#include "AliLog.h"
#include "AliHFEcollection.h"

using namespace std;

ClassImp(AliHFEcollection)

//___________________________________________________________________
AliHFEcollection::AliHFEcollection():
  TNamed()
  , fList(0x0)
{

  //
  // default constructor
  //

  fList = new THashList();
  if(!fList){
    AliError("Initialization of the list failed");
  }
  else{
    // list is owner of the objects. Once list is deleted, the objects
    // it contains will be deleted too
    //fList->SetOwner(kTRUE);
  }
  //Printf("%s:%d,%p",(char*)__FILE__,__LINE__,fInstance);

}
//___________________________________________________________________
AliHFEcollection::AliHFEcollection(char* name, char* title):
  TNamed(name, title)
  , fList(0x0)
{

  //
  // constructor
  //

  fList = new THashList();
  if(!fList){
    AliError("Initialization of the list failed");
  }
  else{
    // list is owner of the objects. Once list is deleted, the objects
    // it contains will be deleted too
    // fList->SetOwner(kTRUE);
  }
}
//___________________________________________________________________
AliHFEcollection::AliHFEcollection(const AliHFEcollection &c) :
  TNamed(c)
  , fList(0x0)
{

  //
  // copy operator
  //

  c.Copy(*this);
}
//___________________________________________________________________
AliHFEcollection &AliHFEcollection::operator=(const AliHFEcollection &ref)
{
  //
  // Assignment operator
  //

  if(this != &ref){
    ref.Copy(*this);
  }
  return *this;
}
//___________________________________________________________________
void AliHFEcollection::Copy(TObject &ref) const {

  //
  // Performs the copying of the object
  //

  AliHFEcollection &target = dynamic_cast<AliHFEcollection &>(ref);

  // Clone List Content
  target.fList = new THashList();
  for(Int_t ien = 0; ien < fList->GetEntries(); ien++)
    target.fList->Add(fList->At(ien)->Clone());
}
//___________________________________________________________________
AliHFEcollection::~AliHFEcollection(){

  //
  // Destructor
  //
  if(fList)
    fList->Delete();
  delete fList;
  AliInfo("DESTRUCTOR");
}
//___________________________________________________________________
Bool_t AliHFEcollection::CreateTH1F(const char* name, const char* title, Int_t nBin, Float_t nMin, Float_t nMax){

  //
  // Creates a TH1F histogram for the collection
  //

  if(!fList){
    AliError("No TList pointer ! ");
    return kFALSE;
  }
  else{
    fList->Add(new TH1F(name, title, nBin, nMin, nMax));
    return CheckObject(name);
  }
}
//___________________________________________________________________
Bool_t AliHFEcollection::CreateTH2F(const char* name, const char* title, Int_t nBinX, Float_t nMinX, Float_t nMaxX, Int_t nBinY, Float_t nMinY, Float_t nMaxY){

  //
  // Creates a TH2F histogram for the collection
  //

  if(!fList){
    AliError("No TList pointer ! ");
    return kFALSE;
  }
  fList->Add(new TH2F(name, title, nBinX, nMinX, nMaxX, nBinY, nMinY, nMaxY));
  return CheckObject(name);
}
//___________________________________________________________________
Bool_t AliHFEcollection::CreateTH1Fvector1(Int_t X, const char* name, const char* title, Int_t nBin, Float_t nMin, Float_t nMax){

  //
  // create a 1 dimensional array of size [X]
  //

  if(!fList){
    AliError("No TList pointer ! ");
    return kFALSE;
  }
  if(X <=0){
    AliError("can not create array with negative or zero size ");
    return kFALSE;
  }
  TString hname;
  for(Int_t i=0; i<X; ++i){
    hname = "";
    hname.Append(Form("%s_[%d]", name, i));
    //cout<<" -D: name: "<<name.str().c_str()<<endl;
    //cout<<" -D: nBin: "<<_nBin<<" ,Min: "<<_nMin<<" , Max: "<<_nMax<<endl;
    CreateTH1F(hname.Data(), title, nBin, nMin, nMax);
    if(!CheckObject(hname.Data())){
      AliError(Form("Not possible to create object: %s", hname.Data()));
      return kFALSE;
    }
  }
  return kTRUE;
}
//___________________________________________________________________
Bool_t AliHFEcollection::CreateTH2Fvector1(Int_t X, const char* name, const char* title, Int_t nBinX, Float_t nMinX, Float_t nMaxX, Int_t nBinY, Float_t nMinY, Float_t nMaxY){

  //
  // create a 1 dimensinal array of TH2F histograms with size [X]
  //

  if(!fList){
    AliError("No TList pointer !");
    return kFALSE;
  }
  if(X <=0){
    AliError("can not create array with negative or zero size ");
    return kFALSE;
  }
  TString hname;
  for(Int_t i=0; i<X; ++i){
    hname = "";
    hname.Append(Form("%s_[%d]", name, i));
    //cout<<" -D: name: "<<name<<endl;
    //cout<<" -D: nBin: "<<_nBin<<" ,Min: "<<_nMin<<" , Max: "<<_nMax<<endl;
    CreateTH2F(hname.Data(), title, nBinX, nMinX, nMaxX, nBinY, nMinY, nMaxY);
    if(!CheckObject(hname.Data())){
      AliError(Form("Not possible to create object: %s", hname.Data()));
      return kFALSE;
    }
  }
  return kTRUE;
}
//___________________________________________________________________
Bool_t AliHFEcollection::CreateTH1Fvector2(Int_t X, Int_t Y, const char* name, const char* title, Int_t nBin, Float_t nMin, Float_t nMax){

  //
  // create a 2 dimensional array of histograms of size [X, Y]
  //

  if(!fList){
    AliError("No TList pointer ! ");
    return kFALSE;
  }
  if(X <=0 || Y <=0){
    AliError("can not create array with negative or zero size ");
    return kFALSE;
  }
  TString hname;
  for(Int_t i=0; i<X; ++i){
    for(Int_t j=0; j<Y; ++j){
      hname = "";
      hname.Append(Form("%s_[%d][%d]", name, i, j));
      //cout<<" -D: name: "<<name.str().c_str()<<endl;
      //cout<<" -D: nBin: "<<_nBin<<" ,Min: "<<_nMin<<" , Max: "<<_nMax<<endl;
      CreateTH1F(hname.Data(), title, nBin, nMin, nMax);
      if(!CheckObject(hname.Data())){
	      AliError(Form("Not possible to create object: %s", hname.Data()));
	      return kFALSE;
      }
    }
  }
  return kTRUE;
}
//___________________________________________________________________
Bool_t AliHFEcollection::CreateProfile(const char* name, const char* title, Int_t nbins, Double_t xmin, Double_t xmax){

  //
  // create a simple TProfile
  //

  if(!fList){
    AliError("No TList pointer ! ");
    return kFALSE;
  }
  fList->Add(new TProfile(name, title, nbins, xmin, xmax));
  return CheckObject(name);

}
//___________________________________________________________________
Bool_t AliHFEcollection::CreateTHnSparse(const char* name, const char* title, Int_t dim, Int_t* nbins, Double_t* xmin, Double_t* xmax){

  //
  // create 'dim' dimensional THnSparse
  //

  if(!fList){
    AliError("No TList pointer ! ");
    return kFALSE;
  }
  fList->Add(new THnSparseF(name, title, dim, nbins, xmin, xmax));
  return CheckObject(name);

}
//___________________________________________________________________
TObject* AliHFEcollection::Get(const char* name){

  //
  // Get histogram with the required name
  //

  if(!CheckObject(name)){
    AliWarning(Form("Not possible to return pointer to the object '%s'\n", name));
    return 0;
  }

  return fList->FindObject(name);

}
//___________________________________________________________________
Bool_t AliHFEcollection::Fill(const char* name, Double_t v){

  //
  // fill function for one TH1 histograms
  //

   if(!CheckObject(name)){
    AliError(Form("Not possible to return pointer to the object '%s'\n", name));
    return kFALSE;
  }

  // chack the possible object types
  if(fList->FindObject(name)->InheritsFrom("TH1")){
    (dynamic_cast<TH1F*>(fList->FindObject(name)))->Fill(v);
    return kTRUE;
  }

  return kFALSE;

}
//___________________________________________________________________
Bool_t AliHFEcollection::Fill(const char* name, Int_t X, Double_t v){

  //
  // fill function for one dimension arrays of TH1
  //

  const char* n = Form("%s_[%d]", name, X);
  TObject *o = Get(n);
  if(!o){
    return kFALSE;
  }
  Fill(o->GetName(), v);
  return kTRUE;
}
//___________________________________________________________________
Bool_t AliHFEcollection::Fill(const char* name, Int_t X, Int_t Y, Double_t v){

  //
  // Fill function fir 2 dimensional TH1 arrays
  //

  const char* n = Form("%s_[%d][%d]", name, X, Y);
  TObject *o = Get(n);
  if(!o){
    return kFALSE;
  }
  Fill(o->GetName(), v);
  return kTRUE;
}
//___________________________________________________________________
Bool_t AliHFEcollection::Fill(const char* name, Int_t X, Double_t v1, Double_t v2){

  //
  // fill function for one dimension array of TH2
  //

  const char* n = Form("%s_[%d]", name, X);
  TObject *o = Get(n);
  if(!o){
    return kFALSE;
  }
  Fill(o->GetName(), v1, v2);

  return kTRUE;
}
//___________________________________________________________________
Bool_t AliHFEcollection::Fill(const char* name, Double_t v1, Double_t v2){

  //
  // fill function for TH2 objects
  //

   if(!CheckObject(name)){
    AliError(Form("Not possible to return pointer to the object '%s'\n", name));
    return kFALSE;
  }

  // chack the possible object types
  if(fList->FindObject(name)->InheritsFrom("TH2")){
    (dynamic_cast<TH2F*>(fList->FindObject(name)))->Fill(v1, v2);
    return kTRUE;
  }
  if(fList->FindObject(name)->InheritsFrom("TProfile")){
    (dynamic_cast<TProfile*>(fList->FindObject(name)))->Fill(v1, v2);
    return kTRUE;
  }

  return kFALSE;

}

//___________________________________________________________________
Bool_t AliHFEcollection::CheckObject(const char* name){

  //
  // check wheter the creation of the histogram was succesfull
  //

  if(!fList){
    AliError("No TList pointer ! ");
    return kFALSE;
  }

  if(!fList->FindObject(name)){
    AliWarning(Form("Creating or Finding the object '%s' failed\n", name));
    return kFALSE;
  }
  return kTRUE;
}
//___________________________________________________________________
Bool_t AliHFEcollection::Sumw2(const char* name){
  //
  // Set Sumw2 for the given object
  //
  if(!CheckObject(name)){
    return kFALSE;
  }

  TObject *o = Get(name);
  if(o->InheritsFrom("THnSparse")){
    (dynamic_cast<THnSparse*>(o))->Sumw2();
  }
  return kTRUE;
}
//___________________________________________________________________
Bool_t AliHFEcollection::BinLogAxis(const char* name, Int_t dim){

  //
  // converts the axis (defined by the dimension) of THx or THnSparse
  // object to Log scale. Number of bins and bin min and bin max are preserved
  //

  if(!CheckObject(name)){
    return kFALSE;
  }

  TObject *o = Get(name);
  TAxis *axis = 0x0;
  if(o->InheritsFrom("TH1")){
    axis = (dynamic_cast<TH1F*>(o))->GetXaxis();
  }
  if(o->InheritsFrom("TH2")){
    if(0 == dim){
      axis = (dynamic_cast<TH2F*>(o))->GetXaxis();
    }
    else if(1 == dim){
      axis = (dynamic_cast<TH2F*>(o))->GetYaxis();
    }
     else{
       AliError("Only dim = 0 or 1 possible for TH2F");
     }
  }
  if(o->InheritsFrom("THnSparse")){
    axis = (dynamic_cast<THnSparse*>(o))->GetAxis(dim);
  }

  if(!axis){
    AliError(Form("Axis '%d' could not be identified in the object '%s'\n", dim, name));
    return kFALSE;
  }

  Int_t bins = axis->GetNbins();

  Double_t from = axis->GetXmin();
  Double_t to = axis->GetXmax();
  Double_t *newBins = new Double_t[bins+1];
  newBins[0] = from;
  Double_t factor = TMath::Power(to/from, 1./bins);
  for(Int_t i=1; i<=bins; ++i){
    newBins[i] = factor * newBins[i-1];
  }
  axis->Set(bins, newBins);
  delete newBins;

  return kTRUE;

}
//___________________________________________________________________
Long64_t AliHFEcollection::Merge(TCollection *list){

  //
  // Merge the collections
  //
  if(!list)
    return 0;
  if(list->IsEmpty())
    return 1;

  TIterator *iter = list->MakeIterator();
  TObject *o = NULL;
  Int_t index = 0;
  while((o = iter->Next())){
    AliHFEcollection *coll = dynamic_cast<AliHFEcollection *>(o);
    if(!coll) continue;
    TList templist;       // Create temporary list containing all the lists to merge
    templist.Add(coll->fList);
    fList->Merge(&templist);
    index++;
  }
  delete iter;
  return index + 1;
}
//____________________________________________________________________
void AliHFEcollection::Browse(TBrowser *b)
{

  //
  // Browse the content of the directory.
  //

   if (b) {
      TObject *obj = 0;
      TIter nextin(fList);

      //Add objects that are only in memory
      while ((obj = nextin())) {
         b->Add(obj, obj->GetName());
      }
   }
}
<|endoftext|>


<commit_before>/**
*  Copyright (C) 2015 3D Repo Ltd
*
*  This program is free software: you can redistribute it and/or modify
*  it under the terms of the GNU Affero General Public License as
*  published by the Free Software Foundation, either version 3 of the
*  License, or (at your option) any later version.
*
*  This program is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU Affero General Public License for more details.
*
*  You should have received a copy of the GNU Affero General Public License
*  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "repo_controller_internal.cpp.inl" //Inner class implementation
#include <ctime>
#include <boost/date_time.hpp>
#include "lib/repo_exception.h"
#include "lib/repo_license.h"

using namespace repo;

RepoController::RepoController(
	std::vector<lib::RepoAbstractListener*> listeners,
	const uint32_t &numConcurrentOps,
	const uint32_t &numDbConn)
{

	Licensing::LicenseValidator::RunActivation();

	//RepoController follows the Pimpl idiom http://www.gotw.ca/gotw/028.htm
	//This is done to avoid high dependencies on other headers for library users
	//Actual implementations are in _RepoControllerImpl
	impl = new RepoController::_RepoControllerImpl(listeners, numConcurrentOps, numDbConn);
}

RepoController::~RepoController()
{
	if (impl) delete impl;
}

void RepoController::addAlias(
	RepoController::RepoToken         *token,
	const std::string &alias)
{
	if (token)
		token->alias = alias;
}

RepoController::RepoToken* RepoController::init(
	std::string            &errMsg,
	const lib::RepoConfig  &config
)
{
	return impl->init(errMsg, config);
}

bool RepoController::commitAssetBundleBuffers(
	const RepoController::RepoToken *token,
	repo::core::model::RepoScene    *scene,
	const repo_web_buffers_t &buffers)
{
	return impl->commitAssetBundleBuffers(token, scene, buffers);
}

uint8_t RepoController::commitScene(
	const RepoController::RepoToken    *token,
	repo::core::model::RepoScene        *scene,
	const std::string                   &owner,
	const std::string                      &tag,
	const std::string                      &desc,
	const repo::lib::RepoUUID           &revId)
{
	return impl->commitScene(token, scene, owner, tag, desc, revId);
}

uint64_t RepoController::countItemsInCollection(
	const RepoController::RepoToken            *token,
	const std::string    &database,
	const std::string    &collection)
{
	return impl->countItemsInCollection(token, database, collection);
}

void RepoController::destroyToken(RepoController::RepoToken* token)
{
	if (token) delete token;
}

void RepoController::disconnectFromDatabase(const RepoController::RepoToken* token)
{
	impl->disconnectFromDatabase(token);
}

repo::core::model::RepoScene* RepoController::fetchScene(
	const RepoController::RepoToken      *token,
	const std::string    &database,
	const std::string    &collection,
	const std::string    &uuid,
	const bool           &headRevision,
	const bool           &lightFetch,
	const bool           &ignoreRefScene,
	const bool           &skeletonFetch,
	const std::vector<repo::core::model::RevisionNode::UploadStatus> &includeStatus)
{
	return impl->fetchScene(token, database, collection, uuid, headRevision, lightFetch, ignoreRefScene, skeletonFetch, includeStatus);
}

bool RepoController::generateAndCommitSelectionTree(
	const RepoController::RepoToken                         *token,
	repo::core::model::RepoScene            *scene)
{
	return impl->generateAndCommitSelectionTree(token, scene);
}

bool RepoController::generateAndCommitStashGraph(
	const RepoController::RepoToken              *token,
	repo::core::model::RepoScene* scene
)
{
	return impl->generateAndCommitStashGraph(token, scene);
}

std::vector < repo::core::model::RepoBSON >
RepoController::getAllFromCollectionContinuous(
	const RepoController::RepoToken      *token,
	const std::string    &database,
	const std::string    &collection,
	const uint64_t       &skip,
	const uint32_t       &limit)
{
	return impl->getAllFromCollectionContinuous(token, database, collection, skip, limit);
}

std::vector < repo::core::model::RepoBSON >
RepoController::getAllFromCollectionContinuous(
	const RepoController::RepoToken              *token,
	const std::string            &database,
	const std::string            &collection,
	const std::list<std::string> &fields,
	const std::string            &sortField,
	const int                    &sortOrder,
	const uint64_t               &skip,
	const uint32_t               &limit)
{
	return impl->getAllFromCollectionContinuous(token, database, collection, fields, sortField, sortOrder, skip, limit);
}

std::vector < repo::core::model::RepoRole > RepoController::getRolesFromDatabase(
	const RepoController::RepoToken              *token,
	const std::string            &database,
	const uint64_t               &skip,
	const uint32_t               &limit)
{
	return impl->getRolesFromDatabase(token, database, skip, limit);
}

std::list<std::string> RepoController::getDatabases(const RepoController::RepoToken *token)
{
	return impl->getDatabases(token);
}

std::map<std::string, std::list<std::string>>
RepoController::getDatabasesWithProjects(
	const RepoController::RepoToken  *token,
	const std::list<std::string>     &databases)
{
	return impl->getDatabasesWithProjects(token, databases);
}

bool RepoController::insertBinaryFileToDatabase(
	const RepoController::RepoToken            *token,
	const std::string          &database,
	const std::string          &collection,
	const std::string          &name,
	const std::vector<uint8_t> &rawData,
	const std::string          &mimeType)
{
	return impl->insertBinaryFileToDatabase(token, database, collection, name, rawData, mimeType);
}

void RepoController::insertRole(
	const RepoController::RepoToken   *token,
	const repo::core::model::RepoRole &role
)
{
	impl->insertRole(token, role);
}

void RepoController::insertUser(
	const RepoController::RepoToken    *token,
	const repo::core::model::RepoUser  &user)
{
	impl->insertUser(token, user);
}

bool RepoController::removeCollection(
	const RepoController::RepoToken             *token,
	const std::string     &databaseName,
	const std::string     &collectionName,
	std::string			  &errMsg
)
{
	return impl->removeCollection(token, databaseName, collectionName, errMsg);
}

bool RepoController::removeDatabase(
	const RepoController::RepoToken       *token,
	const std::string     &databaseName,
	std::string			  &errMsg
)
{
	return impl->removeDatabase(token, databaseName, errMsg);
}

void RepoController::removeDocument(
	const RepoController::RepoToken          *token,
	const std::string                        &databaseName,
	const std::string                        &collectionName,
	const repo::core::model::RepoBSON        &bson)
{
	impl->removeDocument(token, databaseName, collectionName, bson);
}

bool RepoController::removeProject(
	const RepoController::RepoToken          *token,
	const std::string                        &databaseName,
	const std::string                        &projectName,
	std::string								 &errMsg)
{
	return impl->removeProject(token, databaseName, projectName, errMsg);
}

void RepoController::removeRole(
	const RepoController::RepoToken          *token,
	const repo::core::model::RepoRole        &role)
{
	impl->removeRole(token, role);
}

void RepoController::removeUser(
	const RepoController::RepoToken    *token,
	const repo::core::model::RepoUser  &user)
{
	impl->removeUser(token, user);
}

void RepoController::updateRole(
	const RepoController::RepoToken          *token,
	const repo::core::model::RepoRole        &role)
{
	impl->updateRole(token, role);
}

void RepoController::updateUser(
	const RepoController::RepoToken    *token,
	const repo::core::model::RepoUser  &user)
{
	impl->updateUser(token, user);
}

void RepoController::upsertDocument(
	const RepoController::RepoToken          *token,
	const std::string                        &databaseName,
	const std::string                        &collectionName,
	const repo::core::model::RepoBSON        &bson)
{
	impl->upsertDocument(token, databaseName, collectionName, bson);
}

void RepoController::setLoggingLevel(const repo::lib::RepoLog::RepoLogLevel &level)
{
	impl->setLoggingLevel(level);
}

void RepoController::logToFile(const std::string &filePath)
{
	impl->logToFile(filePath);
}

repo::core::model::RepoScene* RepoController::createFederatedScene(
	const std::map<repo::core::model::TransformationNode, repo::core::model::ReferenceNode> &fedMap)
{
	return impl->createFederatedScene(fedMap);
}

bool RepoController::generateAndCommitGLTFBuffer(
	const RepoController::RepoToken    *token,
	repo::core::model::RepoScene *scene)
{
	return impl->generateAndCommitGLTFBuffer(token, scene);
}

bool RepoController::generateAndCommitSRCBuffer(
	const RepoController::RepoToken    *token,
	repo::core::model::RepoScene *scene)
{
	return impl->generateAndCommitSRCBuffer(token, scene);
}

repo_web_buffers_t RepoController::generateGLTFBuffer(
	repo::core::model::RepoScene *scene)
{
	return impl->generateGLTFBuffer(scene);
}

repo_web_buffers_t RepoController::generateSRCBuffer(
	repo::core::model::RepoScene *scene)
{
	return impl->generateSRCBuffer(scene);
}

std::list<std::string> RepoController::getAdminDatabaseRoles(const RepoController::RepoToken *token)
{
	return impl->getAdminDatabaseRoles(token);
}

std::string RepoController::getNameOfAdminDatabase(const RepoController::RepoToken *token)
{
	return impl->getNameOfAdminDatabase(token);
}

std::shared_ptr<repo_partitioning_tree_t>
RepoController::getScenePartitioning(
	const repo::core::model::RepoScene *scene,
	const uint32_t                     &maxDepth
)
{
	return impl->getScenePartitioning(scene, maxDepth);
}

std::list<std::string> RepoController::getStandardDatabaseRoles(const RepoController::RepoToken *token)
{
	return impl->getStandardDatabaseRoles(token);
}

std::string RepoController::getSupportedImportFormats()
{
	return impl->getSupportedImportFormats();
}

std::string RepoController::getSupportedExportFormats()
{
	return impl->getSupportedExportFormats();
}

std::vector<std::shared_ptr<repo::core::model::MeshNode>> RepoController::initialiseAssetBuffer(
	const RepoController::RepoToken                    *token,
	repo::core::model::RepoScene *scene,
	std::unordered_map<std::string, std::vector<uint8_t>> &jsonFiles,
	repo::core::model::RepoUnityAssets &unityAssets,
	std::vector<std::vector<uint16_t>> &serialisedFaceBuf,
	std::vector<std::vector<std::vector<float>>> &idMapBuf,
	std::vector<std::vector<std::vector<repo_mesh_mapping_t>>> &meshMappings)
{
	return impl->initialiseAssetBuffer(token, scene, jsonFiles, unityAssets, serialisedFaceBuf, idMapBuf, meshMappings);
}

repo::core::model::RepoNodeSet RepoController::loadMetadataFromFile(
	const std::string &filePath,
	const char        &delimiter)
{
	return impl->loadMetadataFromFile(filePath, delimiter);
}

repo::core::model::RepoScene*
RepoController::loadSceneFromFile(
	const std::string                                          &filePath,
	uint8_t                                                    &err,
	const repo::manipulator::modelconvertor::ModelImportConfig &config)
{
	return impl->loadSceneFromFile(filePath, err, config);
}

bool RepoController::saveOriginalFiles(
	const RepoController::RepoToken    *token,
	const repo::core::model::RepoScene *scene,
	const std::string                   &directory)
{
	return impl->saveOriginalFiles(token, scene, directory);
}

bool RepoController::saveOriginalFiles(
	const RepoController::RepoToken     *token,
	const std::string                   &database,
	const std::string                   &project,
	const std::string                   &directory)
{
	return impl->saveOriginalFiles(token, database, project, directory);
}

bool RepoController::saveSceneToFile(
	const std::string &filePath,
	const repo::core::model::RepoScene* scene)
{
	return impl->saveSceneToFile(filePath, scene);
}

void RepoController::reduceTransformations(
	const RepoController::RepoToken              *token,
	repo::core::model::RepoScene *scene)
{
	impl->reduceTransformations(token, scene);
}

void RepoController::compareScenes(
	const RepoController::RepoToken    *token,
	repo::core::model::RepoScene       *base,
	repo::core::model::RepoScene       *compare,
	repo_diff_result_t                         &baseResults,
	repo_diff_result_t                         &compResults,
	const repo::DiffMode                     &diffMode
)
{
	impl->compareScenes(token, base, compare, baseResults, compResults, diffMode);
}

bool RepoController::isVREnabled(const RepoController::RepoToken *token,
	const repo::core::model::RepoScene *scene)
{
	return impl->isVREnabled(token, scene);
}

std::string RepoController::getVersion()
{
	return impl->getVersion();
}

std::string RepoController::getLicenseInfo()
{
	std::stringstream ss;
	ss << "License is valid until: ";
#ifdef VALID_UNTIL
	int64_t validity = VALID_UNTIL;
	auto timeUntil = boost::posix_time::from_time_t(validity);
	ss << boost::posix_time::to_iso_extended_string(timeUntil) << " (timestamp in seconds: " << validity << ")";
#else
	ss << "Forever";
#endif
	return ss.str();
}<commit_msg>ISSUE #519 calling the license deactivate function<commit_after>/**
*  Copyright (C) 2015 3D Repo Ltd
*
*  This program is free software: you can redistribute it and/or modify
*  it under the terms of the GNU Affero General Public License as
*  published by the Free Software Foundation, either version 3 of the
*  License, or (at your option) any later version.
*
*  This program is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU Affero General Public License for more details.
*
*  You should have received a copy of the GNU Affero General Public License
*  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "repo_controller_internal.cpp.inl" //Inner class implementation
#include <ctime>
#include <boost/date_time.hpp>
#include "lib/repo_exception.h"
#include "lib/repo_license.h"

using namespace repo;

RepoController::RepoController(
	std::vector<lib::RepoAbstractListener*> listeners,
	const uint32_t &numConcurrentOps,
	const uint32_t &numDbConn)
{

	Licensing::LicenseValidator::RunActivation();

	//RepoController follows the Pimpl idiom http://www.gotw.ca/gotw/028.htm
	//This is done to avoid high dependencies on other headers for library users
	//Actual implementations are in _RepoControllerImpl
	impl = new RepoController::_RepoControllerImpl(listeners, numConcurrentOps, numDbConn);
}

RepoController::~RepoController()
{
	Licensing::LicenseValidator::RunDeactivation();
	if (impl) delete impl;
}

void RepoController::addAlias(
	RepoController::RepoToken         *token,
	const std::string &alias)
{
	if (token)
		token->alias = alias;
}

RepoController::RepoToken* RepoController::init(
	std::string            &errMsg,
	const lib::RepoConfig  &config
)
{
	return impl->init(errMsg, config);
}

bool RepoController::commitAssetBundleBuffers(
	const RepoController::RepoToken *token,
	repo::core::model::RepoScene    *scene,
	const repo_web_buffers_t &buffers)
{
	return impl->commitAssetBundleBuffers(token, scene, buffers);
}

uint8_t RepoController::commitScene(
	const RepoController::RepoToken    *token,
	repo::core::model::RepoScene        *scene,
	const std::string                   &owner,
	const std::string                      &tag,
	const std::string                      &desc,
	const repo::lib::RepoUUID           &revId)
{
	return impl->commitScene(token, scene, owner, tag, desc, revId);
}

uint64_t RepoController::countItemsInCollection(
	const RepoController::RepoToken            *token,
	const std::string    &database,
	const std::string    &collection)
{
	return impl->countItemsInCollection(token, database, collection);
}

void RepoController::destroyToken(RepoController::RepoToken* token)
{
	if (token) delete token;
}

void RepoController::disconnectFromDatabase(const RepoController::RepoToken* token)
{
	impl->disconnectFromDatabase(token);
}

repo::core::model::RepoScene* RepoController::fetchScene(
	const RepoController::RepoToken      *token,
	const std::string    &database,
	const std::string    &collection,
	const std::string    &uuid,
	const bool           &headRevision,
	const bool           &lightFetch,
	const bool           &ignoreRefScene,
	const bool           &skeletonFetch,
	const std::vector<repo::core::model::RevisionNode::UploadStatus> &includeStatus)
{
	return impl->fetchScene(token, database, collection, uuid, headRevision, lightFetch, ignoreRefScene, skeletonFetch, includeStatus);
}

bool RepoController::generateAndCommitSelectionTree(
	const RepoController::RepoToken                         *token,
	repo::core::model::RepoScene            *scene)
{
	return impl->generateAndCommitSelectionTree(token, scene);
}

bool RepoController::generateAndCommitStashGraph(
	const RepoController::RepoToken              *token,
	repo::core::model::RepoScene* scene
)
{
	return impl->generateAndCommitStashGraph(token, scene);
}

std::vector < repo::core::model::RepoBSON >
RepoController::getAllFromCollectionContinuous(
	const RepoController::RepoToken      *token,
	const std::string    &database,
	const std::string    &collection,
	const uint64_t       &skip,
	const uint32_t       &limit)
{
	return impl->getAllFromCollectionContinuous(token, database, collection, skip, limit);
}

std::vector < repo::core::model::RepoBSON >
RepoController::getAllFromCollectionContinuous(
	const RepoController::RepoToken              *token,
	const std::string            &database,
	const std::string            &collection,
	const std::list<std::string> &fields,
	const std::string            &sortField,
	const int                    &sortOrder,
	const uint64_t               &skip,
	const uint32_t               &limit)
{
	return impl->getAllFromCollectionContinuous(token, database, collection, fields, sortField, sortOrder, skip, limit);
}

std::vector < repo::core::model::RepoRole > RepoController::getRolesFromDatabase(
	const RepoController::RepoToken              *token,
	const std::string            &database,
	const uint64_t               &skip,
	const uint32_t               &limit)
{
	return impl->getRolesFromDatabase(token, database, skip, limit);
}

std::list<std::string> RepoController::getDatabases(const RepoController::RepoToken *token)
{
	return impl->getDatabases(token);
}

std::map<std::string, std::list<std::string>>
RepoController::getDatabasesWithProjects(
	const RepoController::RepoToken  *token,
	const std::list<std::string>     &databases)
{
	return impl->getDatabasesWithProjects(token, databases);
}

bool RepoController::insertBinaryFileToDatabase(
	const RepoController::RepoToken            *token,
	const std::string          &database,
	const std::string          &collection,
	const std::string          &name,
	const std::vector<uint8_t> &rawData,
	const std::string          &mimeType)
{
	return impl->insertBinaryFileToDatabase(token, database, collection, name, rawData, mimeType);
}

void RepoController::insertRole(
	const RepoController::RepoToken   *token,
	const repo::core::model::RepoRole &role
)
{
	impl->insertRole(token, role);
}

void RepoController::insertUser(
	const RepoController::RepoToken    *token,
	const repo::core::model::RepoUser  &user)
{
	impl->insertUser(token, user);
}

bool RepoController::removeCollection(
	const RepoController::RepoToken             *token,
	const std::string     &databaseName,
	const std::string     &collectionName,
	std::string			  &errMsg
)
{
	return impl->removeCollection(token, databaseName, collectionName, errMsg);
}

bool RepoController::removeDatabase(
	const RepoController::RepoToken       *token,
	const std::string     &databaseName,
	std::string			  &errMsg
)
{
	return impl->removeDatabase(token, databaseName, errMsg);
}

void RepoController::removeDocument(
	const RepoController::RepoToken          *token,
	const std::string                        &databaseName,
	const std::string                        &collectionName,
	const repo::core::model::RepoBSON        &bson)
{
	impl->removeDocument(token, databaseName, collectionName, bson);
}

bool RepoController::removeProject(
	const RepoController::RepoToken          *token,
	const std::string                        &databaseName,
	const std::string                        &projectName,
	std::string								 &errMsg)
{
	return impl->removeProject(token, databaseName, projectName, errMsg);
}

void RepoController::removeRole(
	const RepoController::RepoToken          *token,
	const repo::core::model::RepoRole        &role)
{
	impl->removeRole(token, role);
}

void RepoController::removeUser(
	const RepoController::RepoToken    *token,
	const repo::core::model::RepoUser  &user)
{
	impl->removeUser(token, user);
}

void RepoController::updateRole(
	const RepoController::RepoToken          *token,
	const repo::core::model::RepoRole        &role)
{
	impl->updateRole(token, role);
}

void RepoController::updateUser(
	const RepoController::RepoToken    *token,
	const repo::core::model::RepoUser  &user)
{
	impl->updateUser(token, user);
}

void RepoController::upsertDocument(
	const RepoController::RepoToken          *token,
	const std::string                        &databaseName,
	const std::string                        &collectionName,
	const repo::core::model::RepoBSON        &bson)
{
	impl->upsertDocument(token, databaseName, collectionName, bson);
}

void RepoController::setLoggingLevel(const repo::lib::RepoLog::RepoLogLevel &level)
{
	impl->setLoggingLevel(level);
}

void RepoController::logToFile(const std::string &filePath)
{
	impl->logToFile(filePath);
}

repo::core::model::RepoScene* RepoController::createFederatedScene(
	const std::map<repo::core::model::TransformationNode, repo::core::model::ReferenceNode> &fedMap)
{
	return impl->createFederatedScene(fedMap);
}

bool RepoController::generateAndCommitGLTFBuffer(
	const RepoController::RepoToken    *token,
	repo::core::model::RepoScene *scene)
{
	return impl->generateAndCommitGLTFBuffer(token, scene);
}

bool RepoController::generateAndCommitSRCBuffer(
	const RepoController::RepoToken    *token,
	repo::core::model::RepoScene *scene)
{
	return impl->generateAndCommitSRCBuffer(token, scene);
}

repo_web_buffers_t RepoController::generateGLTFBuffer(
	repo::core::model::RepoScene *scene)
{
	return impl->generateGLTFBuffer(scene);
}

repo_web_buffers_t RepoController::generateSRCBuffer(
	repo::core::model::RepoScene *scene)
{
	return impl->generateSRCBuffer(scene);
}

std::list<std::string> RepoController::getAdminDatabaseRoles(const RepoController::RepoToken *token)
{
	return impl->getAdminDatabaseRoles(token);
}

std::string RepoController::getNameOfAdminDatabase(const RepoController::RepoToken *token)
{
	return impl->getNameOfAdminDatabase(token);
}

std::shared_ptr<repo_partitioning_tree_t>
RepoController::getScenePartitioning(
	const repo::core::model::RepoScene *scene,
	const uint32_t                     &maxDepth
)
{
	return impl->getScenePartitioning(scene, maxDepth);
}

std::list<std::string> RepoController::getStandardDatabaseRoles(const RepoController::RepoToken *token)
{
	return impl->getStandardDatabaseRoles(token);
}

std::string RepoController::getSupportedImportFormats()
{
	return impl->getSupportedImportFormats();
}

std::string RepoController::getSupportedExportFormats()
{
	return impl->getSupportedExportFormats();
}

std::vector<std::shared_ptr<repo::core::model::MeshNode>> RepoController::initialiseAssetBuffer(
	const RepoController::RepoToken                    *token,
	repo::core::model::RepoScene *scene,
	std::unordered_map<std::string, std::vector<uint8_t>> &jsonFiles,
	repo::core::model::RepoUnityAssets &unityAssets,
	std::vector<std::vector<uint16_t>> &serialisedFaceBuf,
	std::vector<std::vector<std::vector<float>>> &idMapBuf,
	std::vector<std::vector<std::vector<repo_mesh_mapping_t>>> &meshMappings)
{
	return impl->initialiseAssetBuffer(token, scene, jsonFiles, unityAssets, serialisedFaceBuf, idMapBuf, meshMappings);
}

repo::core::model::RepoNodeSet RepoController::loadMetadataFromFile(
	const std::string &filePath,
	const char        &delimiter)
{
	return impl->loadMetadataFromFile(filePath, delimiter);
}

repo::core::model::RepoScene*
RepoController::loadSceneFromFile(
	const std::string                                          &filePath,
	uint8_t                                                    &err,
	const repo::manipulator::modelconvertor::ModelImportConfig &config)
{
	return impl->loadSceneFromFile(filePath, err, config);
}

bool RepoController::saveOriginalFiles(
	const RepoController::RepoToken    *token,
	const repo::core::model::RepoScene *scene,
	const std::string                   &directory)
{
	return impl->saveOriginalFiles(token, scene, directory);
}

bool RepoController::saveOriginalFiles(
	const RepoController::RepoToken     *token,
	const std::string                   &database,
	const std::string                   &project,
	const std::string                   &directory)
{
	return impl->saveOriginalFiles(token, database, project, directory);
}

bool RepoController::saveSceneToFile(
	const std::string &filePath,
	const repo::core::model::RepoScene* scene)
{
	return impl->saveSceneToFile(filePath, scene);
}

void RepoController::reduceTransformations(
	const RepoController::RepoToken              *token,
	repo::core::model::RepoScene *scene)
{
	impl->reduceTransformations(token, scene);
}

void RepoController::compareScenes(
	const RepoController::RepoToken    *token,
	repo::core::model::RepoScene       *base,
	repo::core::model::RepoScene       *compare,
	repo_diff_result_t                         &baseResults,
	repo_diff_result_t                         &compResults,
	const repo::DiffMode                     &diffMode
)
{
	impl->compareScenes(token, base, compare, baseResults, compResults, diffMode);
}

bool RepoController::isVREnabled(const RepoController::RepoToken *token,
	const repo::core::model::RepoScene *scene)
{
	return impl->isVREnabled(token, scene);
}

std::string RepoController::getVersion()
{
	return impl->getVersion();
}

std::string RepoController::getLicenseInfo()
{
	std::stringstream ss;
	ss << "License is valid until: ";
#ifdef VALID_UNTIL
	int64_t validity = VALID_UNTIL;
	auto timeUntil = boost::posix_time::from_time_t(validity);
	ss << boost::posix_time::to_iso_extended_string(timeUntil) << " (timestamp in seconds: " << validity << ")";
#else
	ss << "Forever";
#endif
	return ss.str();
}<|endoftext|>