<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-2014 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 "OgreRoot.h"
#include "OgreException.h"
#include "OgreLogManager.h"
#include "OgreStringConverter.h"
#include "OgreWindowEventUtilities.h"

#include "OgreGLES2Prerequisites.h"
#include "OgreGLES2RenderSystem.h"

#include "OgreAndroidEGLSupport.h"
#include "OgreAndroidEGLWindow.h"
#include "OgreAndroidEGLContext.h"
#include "OgreGLES2ManagedResourceManager.h"
#include "OgreViewport.h"

#include <iostream>
#include <algorithm>
#include <climits>

namespace Ogre {
    AndroidEGLWindow::AndroidEGLWindow(AndroidEGLSupport *glsupport)
        : EGLWindow(glsupport),
          mMaxBufferSize(32),
          mMinBufferSize(16),
          mMaxDepthSize(16),
          mMaxStencilSize(0),
          mMSAA(0),
          mCSAA(0)
    {
    }

    AndroidEGLWindow::~AndroidEGLWindow()
    {
    }

    EGLContext* AndroidEGLWindow::createEGLContext() const
    {
        return new AndroidEGLContext(mEglDisplay, mGLSupport, mEglConfig, mEglSurface);
    }

    void AndroidEGLWindow::getLeftAndTopFromNativeWindow( int & left, int & top, uint width, uint height )
    {
        // We don't have a native window.... but I think all android windows are origined
        left = top = 0;
    }

    void AndroidEGLWindow::initNativeCreatedWindow(const NameValuePairList *miscParams)
    {
    }

    void AndroidEGLWindow::createNativeWindow( int &left, int &top, uint &width, uint &height, String &title )
    {
    }

    void AndroidEGLWindow::reposition( int left, int top )
    {
    }

    void AndroidEGLWindow::resize(uint width, uint height)
    {
    }

    void AndroidEGLWindow::windowMovedOrResized()
    {
        if(mActive)
        {
			// When using GPU rendering for Android UI the os creates a context in the main thread
			// Now we have 2 choices create OGRE in its own thread or set our context current before doing
			// anything else. I put this code here because this function called before any rendering is done.
			// Because the events for screen rotation / resizing did not worked on all devices it is the best way
			// to query the correct dimensions.
	        mContext->setCurrent();
            eglQuerySurface(mEglDisplay, mEglSurface, EGL_WIDTH, (EGLint*)&mWidth);
            eglQuerySurface(mEglDisplay, mEglSurface, EGL_HEIGHT, (EGLint*)&mHeight);

            // Notify viewports of resize
            ViewportList::iterator it = mViewportList.begin();
            while( it != mViewportList.end() )
                (*it++).second->_updateDimensions();
        }
    }

    void AndroidEGLWindow::switchFullScreen(bool fullscreen)
    {

    }

    void AndroidEGLWindow::create(const String& name, uint width, uint height,
                               bool fullScreen, const NameValuePairList *miscParams)
    {
        mName = name;
        mWidth = width;
        mHeight = height;
        mLeft = 0;
        mTop = 0;
        mIsFullScreen = fullScreen;
        void* eglContext = NULL;
        AConfiguration* config = NULL;

        if (miscParams)
        {
            NameValuePairList::const_iterator opt;
            NameValuePairList::const_iterator end = miscParams->end();

            if ((opt = miscParams->find("currentGLContext")) != end &&
                StringConverter::parseBool(opt->second))
            {
                eglContext = eglGetCurrentContext();
                if (eglContext)
                {
                    OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
                                "currentGLContext was specified with no current GL context",
                                "EGLWindow::create");
                }

                eglContext = eglGetCurrentContext();
                mEglSurface = eglGetCurrentSurface(EGL_DRAW);
            }

            if((opt = miscParams->find("externalWindowHandle")) != end)
            {
                mWindow = (ANativeWindow*)(Ogre::StringConverter::parseInt(opt->second));
            }

            if((opt = miscParams->find("androidConfig")) != end)
            {
                config = (AConfiguration*)(Ogre::StringConverter::parseInt(opt->second));
            }

            int ctxHandle = -1;
            if((miscParams->find("externalGLContext")) != end)
            {
                mIsExternalGLControl = true;
                ctxHandle = Ogre::StringConverter::parseInt(opt->second);
            }

            if((opt = miscParams->find("maxColourBufferSize")) != end)
            {
                mMaxBufferSize = Ogre::StringConverter::parseInt(opt->second);
            }

            if((opt = miscParams->find("maxDepthBufferSize")) != end)
            {
                mMaxDepthSize = Ogre::StringConverter::parseInt(opt->second);
            }

            if((opt = miscParams->find("maxStencilBufferSize")) != end)
            {
                mMaxStencilSize = Ogre::StringConverter::parseInt(opt->second);
            }

            if((opt = miscParams->find("minColourBufferSize")) != end)
            {
                mMinBufferSize = Ogre::StringConverter::parseInt(opt->second);
                if (mMinBufferSize > mMaxBufferSize) mMinBufferSize = mMaxBufferSize;
            }

            if((opt = miscParams->find("MSAA")) != end)
            {
                mMSAA = Ogre::StringConverter::parseInt(opt->second);
            }

            if((opt = miscParams->find("CSAA")) != end)
            {
                mCSAA = Ogre::StringConverter::parseInt(opt->second);
            }
        }

        initNativeCreatedWindow(miscParams);

        if (mEglSurface)
        {
            mEglConfig = mGLSupport->getGLConfigFromDrawable (mEglSurface, &width, &height);
        }

        if (!mEglConfig && eglContext)
        {
            mEglConfig = mGLSupport->getGLConfigFromContext(eglContext);

            if (!mEglConfig)
            {
                // This should never happen.
                OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
                            "Unexpected failure to determine a EGLFBConfig",
                            "EGLWindow::create");
            }
        }

        mIsExternal = (mEglSurface != 0);

        if (!mEglConfig)
        {
            _createInternalResources(mWindow, config);
            mHwGamma = false;
        }

        mContext = createEGLContext();
        mContext->setCurrent();

        eglQuerySurface(mEglDisplay, mEglSurface, EGL_WIDTH, (EGLint*)&mWidth);
        eglQuerySurface(mEglDisplay, mEglSurface, EGL_HEIGHT, (EGLint*)&mHeight);
        EGL_CHECK_ERROR

        mActive = true;
        mVisible = true;
        mClosed = false;
    }

    void AndroidEGLWindow::_destroyInternalResources()
    {
        mContext->setCurrent();

        GLES2RenderSystem::getResourceManager()->notifyOnContextLost();
        mContext->_destroyInternalResources();

        eglDestroySurface(mEglDisplay, mEglSurface);
        EGL_CHECK_ERROR

        eglTerminate(mEglDisplay);
        EGL_CHECK_ERROR

        mEglDisplay = 0;
        mEglSurface = 0;

        mActive = false;
        mVisible = false;
        mClosed = true;
    }

    void AndroidEGLWindow::_createInternalResources(NativeWindowType window, AConfiguration* config)
    {
        mWindow = window;

        int minAttribs[] = {
            EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
            EGL_BUFFER_SIZE, mMinBufferSize,
            EGL_DEPTH_SIZE, 16,
            EGL_NONE
        };

        int maxAttribs[] = {
            EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
            EGL_BUFFER_SIZE, mMaxBufferSize,
            EGL_DEPTH_SIZE, mMaxDepthSize,
            EGL_STENCIL_SIZE, mMaxStencilSize,
            EGL_NONE
        };

        bool bAASuccess = false;
        if (mCSAA)
        {
            try
            {
                int CSAAminAttribs[] = {
                    EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
                    EGL_BUFFER_SIZE, mMinBufferSize,
                    EGL_DEPTH_SIZE, 16,
                    EGL_COVERAGE_BUFFERS_NV, 1,
                    EGL_COVERAGE_SAMPLES_NV, mCSAA,
                    EGL_NONE
                };
                int CSAAmaxAttribs[] = {
                    EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
                    EGL_BUFFER_SIZE, mMaxBufferSize,
                    EGL_DEPTH_SIZE, mMaxDepthSize,
                    EGL_STENCIL_SIZE, mMaxStencilSize,
                    EGL_COVERAGE_BUFFERS_NV, 1,
                    EGL_COVERAGE_SAMPLES_NV, mCSAA,
                    EGL_NONE
                };
                mEglConfig = mGLSupport->selectGLConfig(CSAAminAttribs, CSAAmaxAttribs);
                bAASuccess = true;
            }
            catch (Exception& e)
            {
                LogManager::getSingleton().logMessage("AndroidEGLWindow::_createInternalResources: setting CSAA failed");
            }
        }

        if (mMSAA && !bAASuccess)
        {
            try
            {
                int MSAAminAttribs[] = {
                    EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
                    EGL_BUFFER_SIZE, mMinBufferSize,
                    EGL_DEPTH_SIZE, 16,
                    EGL_SAMPLE_BUFFERS, 1,
                    EGL_SAMPLES, mMSAA,
                    EGL_NONE
                };
                int MSAAmaxAttribs[] = {
                    EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
                    EGL_BUFFER_SIZE, mMaxBufferSize,
                    EGL_DEPTH_SIZE, mMaxDepthSize,
                    EGL_STENCIL_SIZE, mMaxStencilSize,
                    EGL_SAMPLE_BUFFERS, 1,
                    EGL_SAMPLES, mMSAA,
                    EGL_NONE
                };
                mEglConfig = mGLSupport->selectGLConfig(MSAAminAttribs, MSAAmaxAttribs);
                bAASuccess = true;
            }
            catch (Exception& e)
            {
                LogManager::getSingleton().logMessage("AndroidEGLWindow::_createInternalResources: setting MSAA failed");
            }
        }

        mEglDisplay = mGLSupport->getGLDisplay();
        if (!bAASuccess) mEglConfig = mGLSupport->selectGLConfig(minAttribs, maxAttribs);

        EGLint format;
        eglGetConfigAttrib(mEglDisplay, mEglConfig, EGL_NATIVE_VISUAL_ID, &format);
        EGL_CHECK_ERROR

        ANativeWindow_setBuffersGeometry(mWindow, 0, 0, format);

        mEglSurface = createSurfaceFromWindow(mEglDisplay, mWindow);

        if(config)
        {
            bool isLandscape = (int)AConfiguration_getOrientation(config) == 2;
            mGLSupport->setConfigOption("Orientation", isLandscape ? "Landscape" : "Portrait");
        }

        if(mContext)
        {
            mActive = true;
            mVisible = true;
            mClosed = false;

            mContext->_createInternalResources(mEglDisplay, mEglConfig, mEglSurface, NULL);

            static_cast<GLES2RenderSystem*>(Ogre::Root::getSingletonPtr()->getRenderSystem())->resetRenderer(this);
        }
    }
}<commit_msg>Fixed bug in android which happened if you called Ogre::AndroidEGLWindow::_destroyInternalResources() multiple times.<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-2014 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 "OgreRoot.h"
#include "OgreException.h"
#include "OgreLogManager.h"
#include "OgreStringConverter.h"
#include "OgreWindowEventUtilities.h"

#include "OgreGLES2Prerequisites.h"
#include "OgreGLES2RenderSystem.h"

#include "OgreAndroidEGLSupport.h"
#include "OgreAndroidEGLWindow.h"
#include "OgreAndroidEGLContext.h"
#include "OgreGLES2ManagedResourceManager.h"
#include "OgreViewport.h"

#include <iostream>
#include <algorithm>
#include <climits>

namespace Ogre {
    AndroidEGLWindow::AndroidEGLWindow(AndroidEGLSupport *glsupport)
        : EGLWindow(glsupport),
          mMaxBufferSize(32),
          mMinBufferSize(16),
          mMaxDepthSize(16),
          mMaxStencilSize(0),
          mMSAA(0),
          mCSAA(0)
    {
    }

    AndroidEGLWindow::~AndroidEGLWindow()
    {
    }

    EGLContext* AndroidEGLWindow::createEGLContext() const
    {
        return new AndroidEGLContext(mEglDisplay, mGLSupport, mEglConfig, mEglSurface);
    }

    void AndroidEGLWindow::getLeftAndTopFromNativeWindow( int & left, int & top, uint width, uint height )
    {
        // We don't have a native window.... but I think all android windows are origined
        left = top = 0;
    }

    void AndroidEGLWindow::initNativeCreatedWindow(const NameValuePairList *miscParams)
    {
    }

    void AndroidEGLWindow::createNativeWindow( int &left, int &top, uint &width, uint &height, String &title )
    {
    }

    void AndroidEGLWindow::reposition( int left, int top )
    {
    }

    void AndroidEGLWindow::resize(uint width, uint height)
    {
    }

    void AndroidEGLWindow::windowMovedOrResized()
    {
        if(mActive)
        {
			// When using GPU rendering for Android UI the os creates a context in the main thread
			// Now we have 2 choices create OGRE in its own thread or set our context current before doing
			// anything else. I put this code here because this function called before any rendering is done.
			// Because the events for screen rotation / resizing did not worked on all devices it is the best way
			// to query the correct dimensions.
	        mContext->setCurrent();
            eglQuerySurface(mEglDisplay, mEglSurface, EGL_WIDTH, (EGLint*)&mWidth);
            eglQuerySurface(mEglDisplay, mEglSurface, EGL_HEIGHT, (EGLint*)&mHeight);

            // Notify viewports of resize
            ViewportList::iterator it = mViewportList.begin();
            while( it != mViewportList.end() )
                (*it++).second->_updateDimensions();
        }
    }

    void AndroidEGLWindow::switchFullScreen(bool fullscreen)
    {

    }

    void AndroidEGLWindow::create(const String& name, uint width, uint height,
                               bool fullScreen, const NameValuePairList *miscParams)
    {
        mName = name;
        mWidth = width;
        mHeight = height;
        mLeft = 0;
        mTop = 0;
        mIsFullScreen = fullScreen;
        void* eglContext = NULL;
        AConfiguration* config = NULL;

        if (miscParams)
        {
            NameValuePairList::const_iterator opt;
            NameValuePairList::const_iterator end = miscParams->end();

            if ((opt = miscParams->find("currentGLContext")) != end &&
                StringConverter::parseBool(opt->second))
            {
                eglContext = eglGetCurrentContext();
                if (eglContext)
                {
                    OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
                                "currentGLContext was specified with no current GL context",
                                "EGLWindow::create");
                }

                eglContext = eglGetCurrentContext();
                mEglSurface = eglGetCurrentSurface(EGL_DRAW);
            }

            if((opt = miscParams->find("externalWindowHandle")) != end)
            {
                mWindow = (ANativeWindow*)(Ogre::StringConverter::parseInt(opt->second));
            }

            if((opt = miscParams->find("androidConfig")) != end)
            {
                config = (AConfiguration*)(Ogre::StringConverter::parseInt(opt->second));
            }

            int ctxHandle = -1;
            if((miscParams->find("externalGLContext")) != end)
            {
                mIsExternalGLControl = true;
                ctxHandle = Ogre::StringConverter::parseInt(opt->second);
            }

            if((opt = miscParams->find("maxColourBufferSize")) != end)
            {
                mMaxBufferSize = Ogre::StringConverter::parseInt(opt->second);
            }

            if((opt = miscParams->find("maxDepthBufferSize")) != end)
            {
                mMaxDepthSize = Ogre::StringConverter::parseInt(opt->second);
            }

            if((opt = miscParams->find("maxStencilBufferSize")) != end)
            {
                mMaxStencilSize = Ogre::StringConverter::parseInt(opt->second);
            }

            if((opt = miscParams->find("minColourBufferSize")) != end)
            {
                mMinBufferSize = Ogre::StringConverter::parseInt(opt->second);
                if (mMinBufferSize > mMaxBufferSize) mMinBufferSize = mMaxBufferSize;
            }

            if((opt = miscParams->find("MSAA")) != end)
            {
                mMSAA = Ogre::StringConverter::parseInt(opt->second);
            }

            if((opt = miscParams->find("CSAA")) != end)
            {
                mCSAA = Ogre::StringConverter::parseInt(opt->second);
            }
        }

        initNativeCreatedWindow(miscParams);

        if (mEglSurface)
        {
            mEglConfig = mGLSupport->getGLConfigFromDrawable (mEglSurface, &width, &height);
        }

        if (!mEglConfig && eglContext)
        {
            mEglConfig = mGLSupport->getGLConfigFromContext(eglContext);

            if (!mEglConfig)
            {
                // This should never happen.
                OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
                            "Unexpected failure to determine a EGLFBConfig",
                            "EGLWindow::create");
            }
        }

        mIsExternal = (mEglSurface != 0);

        if (!mEglConfig)
        {
            _createInternalResources(mWindow, config);
            mHwGamma = false;
        }

        mContext = createEGLContext();
        mContext->setCurrent();

        eglQuerySurface(mEglDisplay, mEglSurface, EGL_WIDTH, (EGLint*)&mWidth);
        eglQuerySurface(mEglDisplay, mEglSurface, EGL_HEIGHT, (EGLint*)&mHeight);
        EGL_CHECK_ERROR

        mActive = true;
        mVisible = true;
        mClosed = false;
    }

    void AndroidEGLWindow::_destroyInternalResources()
    {
		if(mClosed)
			return;

        mContext->setCurrent();

        GLES2RenderSystem::getResourceManager()->notifyOnContextLost();
        mContext->_destroyInternalResources();

        eglDestroySurface(mEglDisplay, mEglSurface);
        EGL_CHECK_ERROR

        eglTerminate(mEglDisplay);
        EGL_CHECK_ERROR

        mEglDisplay = 0;
        mEglSurface = 0;

        mActive = false;
        mVisible = false;
        mClosed = true;
    }

    void AndroidEGLWindow::_createInternalResources(NativeWindowType window, AConfiguration* config)
    {
        mWindow = window;

        int minAttribs[] = {
            EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
            EGL_BUFFER_SIZE, mMinBufferSize,
            EGL_DEPTH_SIZE, 16,
            EGL_NONE
        };

        int maxAttribs[] = {
            EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
            EGL_BUFFER_SIZE, mMaxBufferSize,
            EGL_DEPTH_SIZE, mMaxDepthSize,
            EGL_STENCIL_SIZE, mMaxStencilSize,
            EGL_NONE
        };

        bool bAASuccess = false;
        if (mCSAA)
        {
            try
            {
                int CSAAminAttribs[] = {
                    EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
                    EGL_BUFFER_SIZE, mMinBufferSize,
                    EGL_DEPTH_SIZE, 16,
                    EGL_COVERAGE_BUFFERS_NV, 1,
                    EGL_COVERAGE_SAMPLES_NV, mCSAA,
                    EGL_NONE
                };
                int CSAAmaxAttribs[] = {
                    EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
                    EGL_BUFFER_SIZE, mMaxBufferSize,
                    EGL_DEPTH_SIZE, mMaxDepthSize,
                    EGL_STENCIL_SIZE, mMaxStencilSize,
                    EGL_COVERAGE_BUFFERS_NV, 1,
                    EGL_COVERAGE_SAMPLES_NV, mCSAA,
                    EGL_NONE
                };
                mEglConfig = mGLSupport->selectGLConfig(CSAAminAttribs, CSAAmaxAttribs);
                bAASuccess = true;
            }
            catch (Exception& e)
            {
                LogManager::getSingleton().logMessage("AndroidEGLWindow::_createInternalResources: setting CSAA failed");
            }
        }

        if (mMSAA && !bAASuccess)
        {
            try
            {
                int MSAAminAttribs[] = {
                    EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
                    EGL_BUFFER_SIZE, mMinBufferSize,
                    EGL_DEPTH_SIZE, 16,
                    EGL_SAMPLE_BUFFERS, 1,
                    EGL_SAMPLES, mMSAA,
                    EGL_NONE
                };
                int MSAAmaxAttribs[] = {
                    EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
                    EGL_BUFFER_SIZE, mMaxBufferSize,
                    EGL_DEPTH_SIZE, mMaxDepthSize,
                    EGL_STENCIL_SIZE, mMaxStencilSize,
                    EGL_SAMPLE_BUFFERS, 1,
                    EGL_SAMPLES, mMSAA,
                    EGL_NONE
                };
                mEglConfig = mGLSupport->selectGLConfig(MSAAminAttribs, MSAAmaxAttribs);
                bAASuccess = true;
            }
            catch (Exception& e)
            {
                LogManager::getSingleton().logMessage("AndroidEGLWindow::_createInternalResources: setting MSAA failed");
            }
        }

        mEglDisplay = mGLSupport->getGLDisplay();
        if (!bAASuccess) mEglConfig = mGLSupport->selectGLConfig(minAttribs, maxAttribs);

        EGLint format;
        eglGetConfigAttrib(mEglDisplay, mEglConfig, EGL_NATIVE_VISUAL_ID, &format);
        EGL_CHECK_ERROR

        ANativeWindow_setBuffersGeometry(mWindow, 0, 0, format);

        mEglSurface = createSurfaceFromWindow(mEglDisplay, mWindow);

        if(config)
        {
            bool isLandscape = (int)AConfiguration_getOrientation(config) == 2;
            mGLSupport->setConfigOption("Orientation", isLandscape ? "Landscape" : "Portrait");
        }

        if(mContext)
        {
            mActive = true;
            mVisible = true;
            mClosed = false;

            mContext->_createInternalResources(mEglDisplay, mEglConfig, mEglSurface, NULL);

            static_cast<GLES2RenderSystem*>(Ogre::Root::getSingletonPtr()->getRenderSystem())->resetRenderer(this);
        }
    }
}<|endoftext|>


<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of NLE
(NonLinear Engine)
For the latest info, see https://github.com/AlexandrSachkov/NonLinearEngine

Copyright (c) 2014 Alexandr Sachkov & NonLinear Engine Team

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 "NL_GlfwApplicationLayer.h"
#include "NL_GlfwInputMap.h"
#include "NLE\NL_Nle.h"

#define GLFW_INCLUDE_NONE
#define GL_TRUE 1
#define GL_FALSE 0

#include "GLFW\glfw3.h"

#include <assert.h>

NLEGlfwApplicationLayer* NLEGlfwApplicationLayer::_glfwAppLayer = nullptr;

//===========================================================================================================================
NLEGlfwApplicationLayer& NLEGlfwApplicationLayer::instance()
{
	if (!_glfwAppLayer)
	{
		_glfwAppLayer = new NLEGlfwApplicationLayer();
	}
	return *_glfwAppLayer;
}

//===========================================================================================================================
NLEGlfwApplicationLayer::NLEGlfwApplicationLayer()
{
	_nle = NULL;
	_title = "NonLinear Engine";

	_width = 0;
	_height = 0;
	_window = NULL;
	_fullscreen = true;
}

//===========================================================================================================================
NLEGlfwApplicationLayer::~NLEGlfwApplicationLayer()
{
	if (_nle)
		_nle->release();
	glfwDestroyWindow(_window);
	glfwTerminate();
}

//===========================================================================================================================
bool NLEGlfwApplicationLayer::initialize()
{
	glfwSetErrorCallback(glfwErrorCallback);
	if (!glfwInit())
	{
		printf("GLFW failed to initialize.\n");
		return false;
	}

	if (_fullscreen || _width == 0 || _height == 0)
	{
		const GLFWvidmode * mode = glfwGetVideoMode(glfwGetPrimaryMonitor());
		_width = mode->width;
		_height = mode->height;
	}

	setResizableHint(false);

	glfwWindowHint(GLFW_SAMPLES, 4); // 4x antialiasing
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
	glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

	if (_fullscreen)
	{
		_window = glfwCreateWindow(_width, _height, _title.c_str(), glfwGetPrimaryMonitor(), NULL);
	}
	else
	{
		_window = glfwCreateWindow(_width, _height, _title.c_str(), NULL, NULL);
	}

	if (!_window)
	{
		glfwTerminate();
		printf("Window failed to initialize.\n");
		return false;
	}
	setWindowCallbacks(_window);

	_nle = NLE::instance();

	_nle->attachPollEvents([&](){
		if (!glfwWindowShouldClose(_window))
		{
			glfwPollEvents();
		}
		else
		{
			_nle->stop();
		}
	});

	_nle->attachMakeContextCurrent([&](){
		glfwMakeContextCurrent(_window);
	});

	_nle->attachConfigureVSync([&](){
		glfwSwapInterval(0);
	});

	_nle->attachSwapBuffers([&](){
		glfwSwapBuffers(_window);
	});

	if (!_nle->initialize()) return false;

	printf("======> Application Layer successfully initialized.\n");
	return true;
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::setWindowCallbacks(GLFWwindow* window)
{
	glfwSetKeyCallback(window, onKeyEvent);
	glfwSetCharCallback(window, onCharEvent);
	glfwSetMouseButtonCallback(window, onMouseButtonEvent);
	glfwSetCursorPosCallback(window, onCursorPositionEvent);
	glfwSetCursorEnterCallback(window, onCursorEnterEvent);
	glfwSetScrollCallback(window, onScrollEvent);

	glfwSetWindowPosCallback(window, onWindowPositionEvent);
	glfwSetWindowSizeCallback(window, onWindowSizeEvent);
	glfwSetWindowCloseCallback(window, onWindowCloseEvent);
	glfwSetWindowRefreshCallback(window, onWindowRefreshEvent);
	glfwSetWindowFocusCallback(window, onWindowFocusEvent);
	glfwSetWindowIconifyCallback(window, onWindowIconifyEvent);
}

//===========================================================================================================================
NLE::INle* NLEGlfwApplicationLayer::getNLE()
{
	return _nle;
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::getClientSize(int& width, int& height)
{
	glfwGetWindowSize(_window, &width, &height);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::setWindowSizeHint(int width, int height)
{
	_width = width;
	_height = height;
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::setFullscreenHint(bool option)
{
	_fullscreen = option;
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::setResizableHint(bool option)
{
	glfwWindowHint(GLFW_RESIZABLE, option == true ? GL_TRUE : GL_FALSE);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::setDecoratedHint(bool option)
{
	glfwWindowHint(GLFW_DECORATED, option == true ? GL_TRUE : GL_FALSE);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::setTitle(std::wstring title)
{
	std::string textOut(title.begin(), title.end());
	glfwSetWindowTitle(_window, textOut.c_str());
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::setWindowPosition(int x, int y)
{
	glfwSetWindowPos(_window, x, y);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::getWindowPosition(int& x, int& y)
{
	glfwGetWindowPos(_window, &x, &y);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::iconify()
{
	glfwIconifyWindow(_window);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::restore()
{
	glfwRestoreWindow(_window);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::show()
{
	glfwShowWindow(_window);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::hide()
{
	glfwHideWindow(_window);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::run()
{
	_nle->run();
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::closeWindow()
{
	glfwSetWindowShouldClose(_window, GL_TRUE);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::copyText(std::wstring text)
{
	std::string textOut(text.begin(), text.end());
	glfwSetClipboardString(_window, textOut.c_str());
}

//===========================================================================================================================
std::wstring NLEGlfwApplicationLayer::pasteText()
{
	std::string text(glfwGetClipboardString(_window));
	std::wstring textOut(text.begin(), text.end());
	return textOut;
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::glfwErrorCallback(int error, const char* description)
{
	printf("Application Layer Error: %i, %s", error, description);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::onKeyEvent(GLFWwindow *window, int key, int scancode, int action, int mods)
{
	if (key == GLFW_KEY_ESCAPE) _glfwAppLayer->closeWindow();

	NLE::INPUT::Event event;
	event.eventType = NLE::INPUT::EVENT_TYPE::EVENT_KEY;
	event.eventData.keyEvent.action = NLE::INPUT::GLFWtoNLEAction(action);
	event.eventData.keyEvent.key = NLE::INPUT::GLFWtoNLEKey(key);
	event.eventData.keyEvent.mods = NLE::INPUT::GLFWtoNLEMod(mods);
	event.eventData.keyEvent.scancode = scancode;

	_glfwAppLayer->getNLE()->processEvent(event);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::onCharEvent(GLFWwindow *window, unsigned int codepoint)
{
	NLE::INPUT::Event event;
	event.eventType = NLE::INPUT::EVENT_TYPE::EVENT_CHAR;
	event.eventData.charEvent.code = codepoint;

	_glfwAppLayer->getNLE()->processEvent(event);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::onMouseButtonEvent(GLFWwindow *window, int button, int action, int mods)
{
	NLE::INPUT::Event event;
	event.eventType = NLE::INPUT::EVENT_TYPE::EVENT_MOUSE_BUTTON;
	event.eventData.mouseButtonEvent.action = NLE::INPUT::GLFWtoNLEAction(action);
	event.eventData.mouseButtonEvent.button = NLE::INPUT::GLFWtoNLEMouse(button);
	event.eventData.mouseButtonEvent.mods = NLE::INPUT::GLFWtoNLEMod(mods);

	_glfwAppLayer->getNLE()->processEvent(event);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::onCursorPositionEvent(GLFWwindow *window, double xPos, double yPos)
{
	NLE::INPUT::Event event;
	event.eventType = NLE::INPUT::EVENT_TYPE::EVENT_CURSOR_POSITION;
	event.eventData.cursorPositionEvent.xPos = xPos;
	event.eventData.cursorPositionEvent.yPos = yPos;

	_glfwAppLayer->getNLE()->processEvent(event);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::onCursorEnterEvent(GLFWwindow *window, int entered)
{
	NLE::INPUT::Event event;
	event.eventType = NLE::INPUT::EVENT_TYPE::EVENT_CURSOR_ENTER;
	event.eventData.cursorEnterEvent.entered = entered == GL_TRUE ? true : false;

	_glfwAppLayer->getNLE()->processEvent(event);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::onScrollEvent(GLFWwindow *window, double xOffset, double yOffset)
{
	NLE::INPUT::Event event;
	event.eventType = NLE::INPUT::EVENT_TYPE::EVENT_SCROLL;
	event.eventData.scrollEvent.xOffset = xOffset;
	event.eventData.scrollEvent.yOffset = yOffset;

	_glfwAppLayer->getNLE()->processEvent(event);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::onWindowPositionEvent(GLFWwindow *window, int xPos, int yPos)
{
	NLE::INPUT::Event event;
	event.eventType = NLE::INPUT::EVENT_TYPE::EVENT_WINDOW_POSITION;
	event.eventData.windowPositionEvent.xPos = xPos;
	event.eventData.windowPositionEvent.yPos = yPos;

	_glfwAppLayer->getNLE()->processEvent(event);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::onWindowSizeEvent(GLFWwindow *window, int width, int height)
{
	NLE::INPUT::Event event;
	event.eventType = NLE::INPUT::EVENT_TYPE::EVENT_WINDOW_SIZE;
	event.eventData.windowSizeEvent.width = width;
	event.eventData.windowSizeEvent.height = height;

	_glfwAppLayer->getNLE()->processEvent(event);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::onWindowCloseEvent(GLFWwindow *window)
{
	NLE::INPUT::Event event;
	event.eventType = NLE::INPUT::EVENT_TYPE::EVENT_WINDOW_CLOSE;

	_glfwAppLayer->getNLE()->processEvent(event);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::onWindowRefreshEvent(GLFWwindow *window)
{
	NLE::INPUT::Event event;
	event.eventType = NLE::INPUT::EVENT_TYPE::EVENT_WINDOW_REFRESH;

	_glfwAppLayer->getNLE()->processEvent(event);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::onWindowFocusEvent(GLFWwindow *window, int focused)
{
	NLE::INPUT::Event event;
	event.eventType = NLE::INPUT::EVENT_TYPE::EVENT_WINDOW_FOCUS;
	event.eventData.windowFocusEvent.focused = focused == GL_TRUE ? true : false;

	_glfwAppLayer->getNLE()->processEvent(event);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::onWindowIconifyEvent(GLFWwindow *window, int iconified)
{
	NLE::INPUT::Event event;
	event.eventType = NLE::INPUT::EVENT_TYPE::EVENT_WINDOW_ICONIFY;
	event.eventData.windowIconifyEvent.iconified = iconified == GL_TRUE ? true : false;

	_glfwAppLayer->getNLE()->processEvent(event);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::onClipboardCopyEvent()
{
	NLE::INPUT::Event event;
	event.eventType = NLE::INPUT::EVENT_TYPE::EVENT_CLIPBOARD_COPY;

	_glfwAppLayer->getNLE()->processEvent(event);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::onClipboardCutEvent()
{
	NLE::INPUT::Event event;
	event.eventType = NLE::INPUT::EVENT_TYPE::EVENT_CLIPBOARD_CUT;

	_glfwAppLayer->getNLE()->processEvent(event);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::onClipboardPasteEvent()
{
	NLE::INPUT::Event event;
	event.eventType = NLE::INPUT::EVENT_TYPE::EVENT_CLIPBOARD_PASTE;

	_glfwAppLayer->getNLE()->processEvent(event);
}<commit_msg>cleaned up GL_TRUE/FALSE references<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of NLE
(NonLinear Engine)
For the latest info, see https://github.com/AlexandrSachkov/NonLinearEngine

Copyright (c) 2014 Alexandr Sachkov & NonLinear Engine Team

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 "NL_GlfwApplicationLayer.h"
#include "NL_GlfwInputMap.h"
#include "NLE\NL_Nle.h"

#define GLFW_INCLUDE_NONE
#include "GLFW\glfw3.h"

#include <assert.h>

NLEGlfwApplicationLayer* NLEGlfwApplicationLayer::_glfwAppLayer = nullptr;

//===========================================================================================================================
NLEGlfwApplicationLayer& NLEGlfwApplicationLayer::instance()
{
	if (!_glfwAppLayer)
	{
		_glfwAppLayer = new NLEGlfwApplicationLayer();
	}
	return *_glfwAppLayer;
}

//===========================================================================================================================
NLEGlfwApplicationLayer::NLEGlfwApplicationLayer()
{
	_nle = NULL;
	_title = "NonLinear Engine";

	_width = 0;
	_height = 0;
	_window = NULL;
	_fullscreen = true;
}

//===========================================================================================================================
NLEGlfwApplicationLayer::~NLEGlfwApplicationLayer()
{
	if (_nle)
		_nle->release();
	glfwDestroyWindow(_window);
	glfwTerminate();
}

//===========================================================================================================================
bool NLEGlfwApplicationLayer::initialize()
{
	glfwSetErrorCallback(glfwErrorCallback);
	if (!glfwInit())
	{
		printf("GLFW failed to initialize.\n");
		return false;
	}

	if (_fullscreen || _width == 0 || _height == 0)
	{
		const GLFWvidmode * mode = glfwGetVideoMode(glfwGetPrimaryMonitor());
		_width = mode->width;
		_height = mode->height;
	}

	setResizableHint(false);

	glfwWindowHint(GLFW_SAMPLES, 4); // 4x antialiasing
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
	glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, true);
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

	if (_fullscreen)
	{
		_window = glfwCreateWindow(_width, _height, _title.c_str(), glfwGetPrimaryMonitor(), NULL);
	}
	else
	{
		_window = glfwCreateWindow(_width, _height, _title.c_str(), NULL, NULL);
	}

	if (!_window)
	{
		glfwTerminate();
		printf("Window failed to initialize.\n");
		return false;
	}
	setWindowCallbacks(_window);

	_nle = NLE::instance();

	_nle->attachPollEvents([&](){
		if (!glfwWindowShouldClose(_window))
		{
			glfwPollEvents();
		}
		else
		{
			_nle->stop();
		}
	});

	_nle->attachMakeContextCurrent([&](){
		glfwMakeContextCurrent(_window);
	});

	_nle->attachConfigureVSync([&](){
		glfwSwapInterval(0);
	});

	_nle->attachSwapBuffers([&](){
		glfwSwapBuffers(_window);
	});

	if (!_nle->initialize()) return false;

	printf("======> Application Layer successfully initialized.\n");
	return true;
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::setWindowCallbacks(GLFWwindow* window)
{
	glfwSetKeyCallback(window, onKeyEvent);
	glfwSetCharCallback(window, onCharEvent);
	glfwSetMouseButtonCallback(window, onMouseButtonEvent);
	glfwSetCursorPosCallback(window, onCursorPositionEvent);
	glfwSetCursorEnterCallback(window, onCursorEnterEvent);
	glfwSetScrollCallback(window, onScrollEvent);

	glfwSetWindowPosCallback(window, onWindowPositionEvent);
	glfwSetWindowSizeCallback(window, onWindowSizeEvent);
	glfwSetWindowCloseCallback(window, onWindowCloseEvent);
	glfwSetWindowRefreshCallback(window, onWindowRefreshEvent);
	glfwSetWindowFocusCallback(window, onWindowFocusEvent);
	glfwSetWindowIconifyCallback(window, onWindowIconifyEvent);
}

//===========================================================================================================================
NLE::INle* NLEGlfwApplicationLayer::getNLE()
{
	return _nle;
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::getClientSize(int& width, int& height)
{
	glfwGetWindowSize(_window, &width, &height);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::setWindowSizeHint(int width, int height)
{
	_width = width;
	_height = height;
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::setFullscreenHint(bool option)
{
	_fullscreen = option;
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::setResizableHint(bool option)
{
	glfwWindowHint(GLFW_RESIZABLE, option);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::setDecoratedHint(bool option)
{
	glfwWindowHint(GLFW_DECORATED, option);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::setTitle(std::wstring title)
{
	std::string textOut(title.begin(), title.end());
	glfwSetWindowTitle(_window, textOut.c_str());
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::setWindowPosition(int x, int y)
{
	glfwSetWindowPos(_window, x, y);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::getWindowPosition(int& x, int& y)
{
	glfwGetWindowPos(_window, &x, &y);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::iconify()
{
	glfwIconifyWindow(_window);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::restore()
{
	glfwRestoreWindow(_window);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::show()
{
	glfwShowWindow(_window);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::hide()
{
	glfwHideWindow(_window);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::run()
{
	_nle->run();
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::closeWindow()
{
	glfwSetWindowShouldClose(_window, true);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::copyText(std::wstring text)
{
	std::string textOut(text.begin(), text.end());
	glfwSetClipboardString(_window, textOut.c_str());
}

//===========================================================================================================================
std::wstring NLEGlfwApplicationLayer::pasteText()
{
	std::string text(glfwGetClipboardString(_window));
	std::wstring textOut(text.begin(), text.end());
	return textOut;
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::glfwErrorCallback(int error, const char* description)
{
	printf("Application Layer Error: %i, %s", error, description);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::onKeyEvent(GLFWwindow *window, int key, int scancode, int action, int mods)
{
	if (key == GLFW_KEY_ESCAPE) _glfwAppLayer->closeWindow();

	NLE::INPUT::Event event;
	event.eventType = NLE::INPUT::EVENT_TYPE::EVENT_KEY;
	event.eventData.keyEvent.action = NLE::INPUT::GLFWtoNLEAction(action);
	event.eventData.keyEvent.key = NLE::INPUT::GLFWtoNLEKey(key);
	event.eventData.keyEvent.mods = NLE::INPUT::GLFWtoNLEMod(mods);
	event.eventData.keyEvent.scancode = scancode;

	_glfwAppLayer->getNLE()->processEvent(event);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::onCharEvent(GLFWwindow *window, unsigned int codepoint)
{
	NLE::INPUT::Event event;
	event.eventType = NLE::INPUT::EVENT_TYPE::EVENT_CHAR;
	event.eventData.charEvent.code = codepoint;

	_glfwAppLayer->getNLE()->processEvent(event);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::onMouseButtonEvent(GLFWwindow *window, int button, int action, int mods)
{
	NLE::INPUT::Event event;
	event.eventType = NLE::INPUT::EVENT_TYPE::EVENT_MOUSE_BUTTON;
	event.eventData.mouseButtonEvent.action = NLE::INPUT::GLFWtoNLEAction(action);
	event.eventData.mouseButtonEvent.button = NLE::INPUT::GLFWtoNLEMouse(button);
	event.eventData.mouseButtonEvent.mods = NLE::INPUT::GLFWtoNLEMod(mods);

	_glfwAppLayer->getNLE()->processEvent(event);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::onCursorPositionEvent(GLFWwindow *window, double xPos, double yPos)
{
	NLE::INPUT::Event event;
	event.eventType = NLE::INPUT::EVENT_TYPE::EVENT_CURSOR_POSITION;
	event.eventData.cursorPositionEvent.xPos = xPos;
	event.eventData.cursorPositionEvent.yPos = yPos;

	_glfwAppLayer->getNLE()->processEvent(event);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::onCursorEnterEvent(GLFWwindow *window, int entered)
{
	NLE::INPUT::Event event;
	event.eventType = NLE::INPUT::EVENT_TYPE::EVENT_CURSOR_ENTER;
	event.eventData.cursorEnterEvent.entered = entered == 1 ? true : false;

	_glfwAppLayer->getNLE()->processEvent(event);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::onScrollEvent(GLFWwindow *window, double xOffset, double yOffset)
{
	NLE::INPUT::Event event;
	event.eventType = NLE::INPUT::EVENT_TYPE::EVENT_SCROLL;
	event.eventData.scrollEvent.xOffset = xOffset;
	event.eventData.scrollEvent.yOffset = yOffset;

	_glfwAppLayer->getNLE()->processEvent(event);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::onWindowPositionEvent(GLFWwindow *window, int xPos, int yPos)
{
	NLE::INPUT::Event event;
	event.eventType = NLE::INPUT::EVENT_TYPE::EVENT_WINDOW_POSITION;
	event.eventData.windowPositionEvent.xPos = xPos;
	event.eventData.windowPositionEvent.yPos = yPos;

	_glfwAppLayer->getNLE()->processEvent(event);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::onWindowSizeEvent(GLFWwindow *window, int width, int height)
{
	NLE::INPUT::Event event;
	event.eventType = NLE::INPUT::EVENT_TYPE::EVENT_WINDOW_SIZE;
	event.eventData.windowSizeEvent.width = width;
	event.eventData.windowSizeEvent.height = height;

	_glfwAppLayer->getNLE()->processEvent(event);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::onWindowCloseEvent(GLFWwindow *window)
{
	NLE::INPUT::Event event;
	event.eventType = NLE::INPUT::EVENT_TYPE::EVENT_WINDOW_CLOSE;

	_glfwAppLayer->getNLE()->processEvent(event);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::onWindowRefreshEvent(GLFWwindow *window)
{
	NLE::INPUT::Event event;
	event.eventType = NLE::INPUT::EVENT_TYPE::EVENT_WINDOW_REFRESH;

	_glfwAppLayer->getNLE()->processEvent(event);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::onWindowFocusEvent(GLFWwindow *window, int focused)
{
	NLE::INPUT::Event event;
	event.eventType = NLE::INPUT::EVENT_TYPE::EVENT_WINDOW_FOCUS;
	event.eventData.windowFocusEvent.focused = focused == 1 ? true : false;

	_glfwAppLayer->getNLE()->processEvent(event);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::onWindowIconifyEvent(GLFWwindow *window, int iconified)
{
	NLE::INPUT::Event event;
	event.eventType = NLE::INPUT::EVENT_TYPE::EVENT_WINDOW_ICONIFY;
	event.eventData.windowIconifyEvent.iconified = iconified == 1 ? true : false;

	_glfwAppLayer->getNLE()->processEvent(event);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::onClipboardCopyEvent()
{
	NLE::INPUT::Event event;
	event.eventType = NLE::INPUT::EVENT_TYPE::EVENT_CLIPBOARD_COPY;

	_glfwAppLayer->getNLE()->processEvent(event);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::onClipboardCutEvent()
{
	NLE::INPUT::Event event;
	event.eventType = NLE::INPUT::EVENT_TYPE::EVENT_CLIPBOARD_CUT;

	_glfwAppLayer->getNLE()->processEvent(event);
}

//===========================================================================================================================
void NLEGlfwApplicationLayer::onClipboardPasteEvent()
{
	NLE::INPUT::Event event;
	event.eventType = NLE::INPUT::EVENT_TYPE::EVENT_CLIPBOARD_PASTE;

	_glfwAppLayer->getNLE()->processEvent(event);
}<|endoftext|>


<commit_before>#include "gtest/gtest.h"
#include "code/ylikuutio/command_line/command_line_master.hpp"

TEST(is_key_must_function_properly, no_keys)
{
    const int argc = 1; // the executable itself is also in `argv`.
    char first_arg[] = "foo_executable";
    const char* argv[] = { first_arg };
    yli::command_line::CommandLineMaster command_line_master(argc, argv);
    ASSERT_FALSE(command_line_master.is_key("foo_executable"));
    ASSERT_FALSE(command_line_master.is_key("foo"));
    ASSERT_FALSE(command_line_master.is_key("bar"));
}

TEST(is_key_must_function_properly, one_key_without_value)
{
    const int argc = 2; // the executable itself is also in `argv`.
    char first_arg[] = "foo_executable";
    char second_arg[] = "bar";
    const char* argv[] = { first_arg, second_arg };
    yli::command_line::CommandLineMaster command_line_master(argc, argv);
    ASSERT_FALSE(command_line_master.is_key("foo_executable"));
    ASSERT_FALSE(command_line_master.is_key("foo"));
    ASSERT_TRUE(command_line_master.is_key("bar"));
    ASSERT_FALSE(command_line_master.is_key("baz"));
}

TEST(is_key_must_function_properly, one_key_with_value)
{
    const int argc = 2; // the executable itself is also in `argv`.
    char first_arg[] = "foo_executable";
    char second_arg[] = "bar=baz";
    const char* argv[] = { first_arg, second_arg };
    yli::command_line::CommandLineMaster command_line_master(argc, argv);
    ASSERT_FALSE(command_line_master.is_key("foo_executable"));
    ASSERT_FALSE(command_line_master.is_key("foo"));
    ASSERT_TRUE(command_line_master.is_key("bar"));
    ASSERT_FALSE(command_line_master.is_key("bar="));
    ASSERT_FALSE(command_line_master.is_key("=bar"));
    ASSERT_FALSE(command_line_master.is_key("bar=baz"));
    ASSERT_FALSE(command_line_master.is_key("=bar=baz"));
    ASSERT_FALSE(command_line_master.is_key("baz"));
    ASSERT_FALSE(command_line_master.is_key("=baz"));
    ASSERT_FALSE(command_line_master.is_key("baz=baz"));
    ASSERT_FALSE(command_line_master.is_key("qux"));
}

TEST(is_key_must_function_properly, two_keys_with_value)
{
    const int argc = 3; // the executable itself is also in `argv`.
    char first_arg[] = "foo_executable";
    char second_arg[] = "bar=baz";
    char third_arg[] = "qux=quux";
    const char* argv[] = { first_arg, second_arg, third_arg };
    yli::command_line::CommandLineMaster command_line_master(argc, argv);
    ASSERT_FALSE(command_line_master.is_key("foo_executable"));
    ASSERT_FALSE(command_line_master.is_key("foo"));
    ASSERT_TRUE(command_line_master.is_key("bar"));
    ASSERT_FALSE(command_line_master.is_key("bar="));
    ASSERT_FALSE(command_line_master.is_key("=bar"));
    ASSERT_FALSE(command_line_master.is_key("bar=baz"));
    ASSERT_FALSE(command_line_master.is_key("baz"));
    ASSERT_FALSE(command_line_master.is_key("=baz"));
    ASSERT_FALSE(command_line_master.is_key("baz=baz"));
    ASSERT_TRUE(command_line_master.is_key("qux"));
    ASSERT_FALSE(command_line_master.is_key("qux="));
    ASSERT_FALSE(command_line_master.is_key("=qux"));
    ASSERT_FALSE(command_line_master.is_key("qux=quux"));
    ASSERT_FALSE(command_line_master.is_key("quux"));
    ASSERT_FALSE(command_line_master.is_key("quux="));
    ASSERT_FALSE(command_line_master.is_key("=quux"));
}

TEST(is_key_must_function_properly, two_keys_without_value)
{
    const int argc = 3; // the executable itself is also in `argv`.
    char first_arg[] = "foo_executable";
    char second_arg[] = "bar";
    char third_arg[] = "baz";
    const char* argv[] = { first_arg, second_arg, third_arg };
    yli::command_line::CommandLineMaster command_line_master(argc, argv);
    ASSERT_FALSE(command_line_master.is_key("foo_executable"));
    ASSERT_FALSE(command_line_master.is_key("foo"));
    ASSERT_TRUE(command_line_master.is_key("bar"));
    ASSERT_TRUE(command_line_master.is_key("baz"));
    ASSERT_FALSE(command_line_master.is_key("qux"));
}
<commit_msg>Reordered tests.<commit_after>#include "gtest/gtest.h"
#include "code/ylikuutio/command_line/command_line_master.hpp"

TEST(is_key_must_function_properly, no_keys)
{
    const int argc = 1; // the executable itself is also in `argv`.
    char first_arg[] = "foo_executable";
    const char* argv[] = { first_arg };
    yli::command_line::CommandLineMaster command_line_master(argc, argv);
    ASSERT_FALSE(command_line_master.is_key("foo_executable"));
    ASSERT_FALSE(command_line_master.is_key("foo"));
    ASSERT_FALSE(command_line_master.is_key("bar"));
}

TEST(is_key_must_function_properly, one_key_without_value)
{
    const int argc = 2; // the executable itself is also in `argv`.
    char first_arg[] = "foo_executable";
    char second_arg[] = "bar";
    const char* argv[] = { first_arg, second_arg };
    yli::command_line::CommandLineMaster command_line_master(argc, argv);
    ASSERT_FALSE(command_line_master.is_key("foo_executable"));
    ASSERT_FALSE(command_line_master.is_key("foo"));
    ASSERT_TRUE(command_line_master.is_key("bar"));
    ASSERT_FALSE(command_line_master.is_key("baz"));
}

TEST(is_key_must_function_properly, one_key_with_value)
{
    const int argc = 2; // the executable itself is also in `argv`.
    char first_arg[] = "foo_executable";
    char second_arg[] = "bar=baz";
    const char* argv[] = { first_arg, second_arg };
    yli::command_line::CommandLineMaster command_line_master(argc, argv);
    ASSERT_FALSE(command_line_master.is_key("foo_executable"));
    ASSERT_FALSE(command_line_master.is_key("foo"));
    ASSERT_TRUE(command_line_master.is_key("bar"));
    ASSERT_FALSE(command_line_master.is_key("bar="));
    ASSERT_FALSE(command_line_master.is_key("=bar"));
    ASSERT_FALSE(command_line_master.is_key("bar=baz"));
    ASSERT_FALSE(command_line_master.is_key("=bar=baz"));
    ASSERT_FALSE(command_line_master.is_key("baz"));
    ASSERT_FALSE(command_line_master.is_key("=baz"));
    ASSERT_FALSE(command_line_master.is_key("baz=baz"));
    ASSERT_FALSE(command_line_master.is_key("qux"));
}

TEST(is_key_must_function_properly, two_keys_without_value)
{
    const int argc = 3; // the executable itself is also in `argv`.
    char first_arg[] = "foo_executable";
    char second_arg[] = "bar";
    char third_arg[] = "baz";
    const char* argv[] = { first_arg, second_arg, third_arg };
    yli::command_line::CommandLineMaster command_line_master(argc, argv);
    ASSERT_FALSE(command_line_master.is_key("foo_executable"));
    ASSERT_FALSE(command_line_master.is_key("foo"));
    ASSERT_TRUE(command_line_master.is_key("bar"));
    ASSERT_TRUE(command_line_master.is_key("baz"));
    ASSERT_FALSE(command_line_master.is_key("qux"));
}

TEST(is_key_must_function_properly, two_keys_with_value)
{
    const int argc = 3; // the executable itself is also in `argv`.
    char first_arg[] = "foo_executable";
    char second_arg[] = "bar=baz";
    char third_arg[] = "qux=quux";
    const char* argv[] = { first_arg, second_arg, third_arg };
    yli::command_line::CommandLineMaster command_line_master(argc, argv);
    ASSERT_FALSE(command_line_master.is_key("foo_executable"));
    ASSERT_FALSE(command_line_master.is_key("foo"));
    ASSERT_TRUE(command_line_master.is_key("bar"));
    ASSERT_FALSE(command_line_master.is_key("bar="));
    ASSERT_FALSE(command_line_master.is_key("=bar"));
    ASSERT_FALSE(command_line_master.is_key("bar=baz"));
    ASSERT_FALSE(command_line_master.is_key("baz"));
    ASSERT_FALSE(command_line_master.is_key("=baz"));
    ASSERT_FALSE(command_line_master.is_key("baz=baz"));
    ASSERT_TRUE(command_line_master.is_key("qux"));
    ASSERT_FALSE(command_line_master.is_key("qux="));
    ASSERT_FALSE(command_line_master.is_key("=qux"));
    ASSERT_FALSE(command_line_master.is_key("qux=quux"));
    ASSERT_FALSE(command_line_master.is_key("quux"));
    ASSERT_FALSE(command_line_master.is_key("quux="));
    ASSERT_FALSE(command_line_master.is_key("=quux"));
}
<|endoftext|>


<commit_before>#include <editor.hpp>

#include <ECS/ECSUtil.hpp>

#include <Core/Containers/UniquePointer.hpp>
#include <PlatformCore/PlatformCore.hpp>
#include <PlatformCore/Window/Window.hpp>
#include <Rendering/Pipeline/ShaderProgram.hpp>

#include <ECS/System.hpp>
#include <ECS/Component.hpp>
#include <ECS/ComponentStore.hpp>

#define GLEW_STATIC 1

#include <GL/glew.h>
#include <GL/wglew.h>
#include <GL/GL.h>

#include <Windows.h>
#include <iostream>

#include <Gameplay/Components/Landscape2D.hpp>
#include <Rendering/Texture.hpp>

namespace Fade {

HDC			DeviceContext;
HGLRC		RenderingContext;

unsigned int VBO, VAO, EBO;
Rendering::Pipeline::CShaderProgram Program, SpriteProgram;

float vertices[] = {
	// positions          // texture coords
	 0.5f,  0.5f, 0.0f,   1.0f, 1.0f,   // top right
	 0.5f, -0.5f, 0.0f,   1.0f, 0.0f,   // bottom right
	-0.5f, -0.5f, 0.0f,   0.0f, 0.0f,   // bottom left
	-0.5f,  0.5f, 0.0f,   0.0f, 1.0f    // top left
};

unsigned int indices[] = {
	0, 1, 3, // first triangle
	1, 2, 3  // second triangle
};

f32 g_XPosAdd = 0.f;
float g_XPosTimer = 0.f;
Rendering::CTexture texture;
Rendering::CTexture sprite;
Rendering::CTexture tilesheet;
float g_AnimTime;
float g_FrameTime = 0.25f;

int g_Column = 0;

CLandscapeChunk g_Chunk;

ETickResult CEditor::Tick(double a_DeltaTime)
{
	float fDeltaTime = float(a_DeltaTime);
	g_XPosTimer += fDeltaTime;
	g_XPosAdd = std::sin(g_XPosTimer);

	glClear(GL_COLOR_BUFFER_BIT/* | GL_DEPTH_BUFFER_BIT*/);

	/*Program.Use();

	Program.SetFloatValue(std::string("xPos"), g_XPosAdd);

	glBindTexture(GL_TEXTURE_2D, texture.GetTextureID());
	glBindVertexArray(VAO);
	glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);

	SpriteProgram.Use();

	g_AnimTime += fDeltaTime;
	if (g_AnimTime > g_FrameTime)
	{
		g_Column = (g_Column + 1) % 4;
		g_AnimTime = 0.f;
	}

	const static float nx = 1.f / 9.f;
	const static float ny = 1.f / 4.f;

	float Column = float(g_Column);
	float Row = 0;

	SpriteProgram.SetFloatValue("nx", nx);
	SpriteProgram.SetFloatValue("ny", ny);
	SpriteProgram.SetFloatValue("Column", Column);
	SpriteProgram.SetFloatValue("Row", Row);

	glBindTexture(GL_TEXTURE_2D, sprite.GetTextureID());
	glBindVertexArray(VAO);
	glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);*/

	FW::FileWatcher::Get().update();

	g_Chunk.Draw(glm::mat4(0.f));

	SwapBuffers(DeviceContext);

	return ETickResult::CONTINUE;
}

void CEditor::FixedTick(double a_FixedDeltaTime)
{

}

bool CEditor::PreInitialize()
{
	m_MainWindow = GetWindow();

	auto& Components = Fade::ECS::Util::Registry<ECS::CComponentBase>::GetRegisteredObjects();
	std::cout << "Registered components: " << Components.size() << "\n";
	for (auto& Component : Components)
	{
		std::cout << "\t- " << Component << "\n";
		auto* Comp = Fade::ECS::Util::Registry<ECS::CComponentBase>::CreateObject(Component);
		std::cout << "\tID: " << Comp->GetID() << "\n";
	}

	return true;
}

bool CEditor::Initialize()
{
	m_CurTime = 0;

	Fade::PlatformCore::SWindowSettings WindowSettings{};
	WindowSettings.m_Title = "Fake Window";
	WindowSettings.m_HasBorder = true;
	WindowSettings.m_IsRegular = true;
	WindowSettings.m_SupportsMaximize = true;
	WindowSettings.m_SupportsMinimize = true;
	WindowSettings.m_HasSizingFrame = true;
	WindowSettings.m_PosX = 0;
	WindowSettings.m_PosY = 0;
	WindowSettings.m_Width = 1080;
	WindowSettings.m_Height = 720;

	HDC		FakeDC;
	HGLRC	FakeRC;
	TUniquePtr<Fade::PlatformCore::CWindow> FakeWindow = GetWindow();
	{
		FakeWindow->Create(WindowSettings);

		// Setup rendering context using that window
		HWND FakeWindowHandle = static_cast<HWND>(FakeWindow->GetWindowHandle());
		FakeDC = GetDC(FakeWindowHandle);

		//https://mariuszbartosik.com/opengl-4-x-initialization-in-windows-without-a-framework/
		PIXELFORMATDESCRIPTOR FakePDF = { 0 };
		FakePDF.nSize = sizeof(PIXELFORMATDESCRIPTOR);
		FakePDF.nVersion = 1;
		FakePDF.dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW;
		FakePDF.iPixelType = PFD_TYPE_RGBA;
		FakePDF.cColorBits = 32;
		FakePDF.cAlphaBits = 8;
		FakePDF.cDepthBits = 24;

		int nPixelFormat = ChoosePixelFormat(FakeDC, &FakePDF);
		if (nPixelFormat == 0)
		{
			std::cout << "ChoosePixelFormat() failed.\n";
			return false;
		}

		if (!SetPixelFormat(FakeDC, nPixelFormat, &FakePDF))
		{
			std::cout << "SetPixelFormat() failed.\n";
			return false;
		}

		FakeRC = wglCreateContext(FakeDC);
		if (!FakeRC)
		{
			std::cout << "wglCreateContext() failed.\n";
			return false;
		}

		if (!wglMakeCurrent(FakeDC, FakeRC))
		{
			std::cout << "wglMakeCurrent() failed.\n";
			return false;
		}
	}

	// Now that we've initialized a non-modern opengl context
	// we can get the newer functionality.
	GLenum err = glewInit();
	if (GLEW_OK != err)
	{
		std::cout << "GLEW is not initialized!\n";
		return false;
	}

	if (wglewIsSupported("WGL_ARB_create_context") == 1)
	{
		WindowSettings.m_Title = "OpenGL Window";
		m_MainWindow->Create(WindowSettings);
		HWND WindowHandle = static_cast<HWND>(m_MainWindow->GetWindowHandle());

		DeviceContext = GetDC(WindowHandle);

		const int pixelAttribs[] =
		{
			WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
			WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
			WGL_DOUBLE_BUFFER_ARB, GL_TRUE,
			WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB,
			WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB,
			WGL_COLOR_BITS_ARB, 32,
			WGL_ALPHA_BITS_ARB, 8,
			WGL_DEPTH_BITS_ARB, 24,
			WGL_STENCIL_BITS_ARB, 8,
			WGL_SAMPLE_BUFFERS_ARB, GL_TRUE,
			WGL_SAMPLES_ARB, 4,
			0
		};

		int pixelFormatID; UINT numFormats;
		bool status = bool(wglChoosePixelFormatARB(DeviceContext, pixelAttribs, NULL, 1, &pixelFormatID, &numFormats));
		if (status == false || numFormats == 0)
		{
			std::cout << "wglChoosePixelFormatARB() failed.\n";
			return false;
		}

		PIXELFORMATDESCRIPTOR PFD;
		DescribePixelFormat(DeviceContext, pixelFormatID, sizeof(PFD), &PFD);
		if (!SetPixelFormat(DeviceContext, pixelFormatID, &PFD))
		{
			std::cout << "SetPixelFormat(). failed\n";
			return false;
		}

		int OpenGLVersion[2];
		glGetIntegerv(GL_MAJOR_VERSION, &OpenGLVersion[0]);
		glGetIntegerv(GL_MINOR_VERSION, &OpenGLVersion[1]);

		int  contextAttribs[] =
		{
			WGL_CONTEXT_MAJOR_VERSION_ARB, OpenGLVersion[0],
			WGL_CONTEXT_MINOR_VERSION_ARB, OpenGLVersion[1],
			WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
			0
		};

		RenderingContext = wglCreateContextAttribsARB(DeviceContext, nullptr, contextAttribs);
		if (!RenderingContext)
		{
			std::cout << "wglCreateContextAttribsARB() failed.\n";
			return false;
		}

		wglMakeCurrent(NULL, NULL);
		wglDeleteContext(FakeRC);
		ReleaseDC(static_cast<HWND>(FakeWindow->GetWindowHandle()), FakeDC);
		FakeWindow->Destroy();
		if (!wglMakeCurrent(DeviceContext, RenderingContext))
		{
			std::cout << "wglMakeCurrent(). failed\n";
			return false;
		}
	}
	else
	{	//It's not possible to make a GL 3.x context. Use the old style context (GL 2.1 and before)
		m_MainWindow = Fade::Move(FakeWindow);
		RenderingContext = FakeRC;
	}

	HWND MainWindowHandle = static_cast<HWND>(m_MainWindow->GetWindowHandle());
	SetWindowText(MainWindowHandle, (LPCSTR)glGetString(GL_VERSION));
	m_MainWindow->Show();

	glClearColor(0.2f, 0.3f, 0.3f, 1.0f);

	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	g_Chunk.Create(4, 4);
	g_Chunk.SetTileAtlas(Rendering::CTileAtlas(".\\Images\\TempTilemap.tga", glm::vec2(56), 4));
	g_Chunk.SetTilemap(Rendering::CTexture(".\\Images\\Tilemap.tga"));

	return true;
}

bool CEditor::PostInitialize()
{
	auto Objects = ECS::Util::Registry<ECS::CComponentBase>::GetRegisteredObjects();
	for (auto& it: Objects)
	{
		std::cout << "Registered component: " << it << "\n";
	}
	return true;
}

bool CEditor::DeInitialize()
{
	wglDeleteContext(RenderingContext);
	ReleaseDC(static_cast<HWND>(m_MainWindow->GetWindowHandle()), DeviceContext);
	m_MainWindow->Destroy();
	return true;
}

}

/** Needs to be defined out of the namespace */
Fade::TUniquePtr<Fade::CApplication> Fade::GetApplication()
{
	return Fade::MakeUnique<CEditor>();
}

<commit_msg>Delete lowercase duplicate file<commit_after><|endoftext|>


<commit_before>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "otbSamplingRateCalculator.h"

#include "otbStatisticsXMLFileReader.h"
#include "itkVariableLengthVector.h"

int otbSamplingRateCalculatorNew(int itkNotUsed(argc), char* itkNotUsed(argv) [])
{
  typedef otb::SamplingRateCalculator RateCalculatorype;

  RateCalculatorype::Pointer rateCalculator = RateCalculatorype::New();
  std::cout << rateCalculator << std::endl;
  return EXIT_SUCCESS;
}

int otbSamplingRateCalculator(int itkNotUsed(argc), char* argv[])
{
  std::string xmlPath(argv[1]);
  unsigned int nbSamples = atoi(argv[2]);
  std::string outputRatesTxt(argv[3]);

  typedef std::map<std::string, unsigned long>      ClassCountMapType;
  typedef itk::VariableLengthVector<float> MeasurementType;
  typedef otb::StatisticsXMLFileReader<MeasurementType> ReaderType;
  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName(xmlPath.c_str());
  ClassCountMapType classCount = reader->GetStatisticMapByName<ClassCountMapType>("classCounts");

  typedef otb::SamplingRateCalculator RateCalculatorype;
  RateCalculatorype::Pointer rateCalculator = RateCalculatorype::New();
  rateCalculator->SetNbOfSamplesAllClasses(nbSamples);
  rateCalculator->Write(outputRatesTxt);
  rateCalculator->Print(std::cout);

  return EXIT_SUCCESS;
}
<commit_msg>TEST: testing the Read() method as well<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "otbSamplingRateCalculator.h"

#include "otbStatisticsXMLFileReader.h"
#include "itkVariableLengthVector.h"

int otbSamplingRateCalculatorNew(int itkNotUsed(argc), char* itkNotUsed(argv) [])
{
  typedef otb::SamplingRateCalculator RateCalculatorype;

  RateCalculatorype::Pointer rateCalculator = RateCalculatorype::New();
  std::cout << rateCalculator << std::endl;
  return EXIT_SUCCESS;
}

int otbSamplingRateCalculator(int itkNotUsed(argc), char* argv[])
{
  std::string xmlPath(argv[1]);
  unsigned int nbSamples = atoi(argv[2]);
  std::string outputRatesTxt(argv[3]);

  typedef std::map<std::string, unsigned long>      ClassCountMapType;
  typedef itk::VariableLengthVector<float> MeasurementType;
  typedef otb::StatisticsXMLFileReader<MeasurementType> ReaderType;
  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName(xmlPath.c_str());
  ClassCountMapType classCount = reader->GetStatisticMapByName<ClassCountMapType>("classCounts");

  typedef otb::SamplingRateCalculator RateCalculatorype;
  RateCalculatorype::Pointer rateCalculator = RateCalculatorype::New();
  rateCalculator->SetNbOfSamplesAllClasses(nbSamples);
  rateCalculator->Write(outputRatesTxt);
  rateCalculator->Print(std::cout);

  // Read back
  RateCalculatorype::Pointer rateCalculatorCheck = RateCalculatorype::New();
  rateCalculatorCheck->Read(outputRatesTxt);
  if ( rateCalculator->GetRatesByClass() != rateCalculatorCheck->GetRatesByClass() )
    {
    std::cout << "Imported rates by class are different from exported ones!" << std::endl;
    return EXIT_FAILURE;
    }

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*---------------------------------------------------------------------------*\
 *                                OpenSG                                     *
 *                                                                           *
 *                                                                           *
 *               Copyright (C) 2000-2006 by the OpenSG Forum                 *
 *                                                                           *
 *                            www.opensg.org                                 *
 *                                                                           *
 *   contact: dirk@opensg.org, gerrit.voss@vossg.org, jbehr@zgdv.de          *
 *                                                                           *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
 *                                License                                    *
 *                                                                           *
 * This library is free software; you can redistribute it and/or modify it   *
 * under the terms of the GNU Library General Public License as published    *
 * by the Free Software Foundation, version 2.                               *
 *                                                                           *
 * This library is distributed in the hope that it will be useful, but       *
 * WITHOUT ANY WARRANTY; without even the implied warranty of                *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU         *
 * Library General Public License for more details.                          *
 *                                                                           *
 * You should have received a copy of the GNU Library General Public         *
 * License along with this library; if not, write to the Free Software       *
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.                 *
 *                                                                           *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
 *                                Changes                                    *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
\*---------------------------------------------------------------------------*/

//---------------------------------------------------------------------------
//  Includes
//---------------------------------------------------------------------------

#include <cstdlib>
#include <cstdio>

#include <OSGConfig.h>

#include "OSGSkeletonSkinningAlgorithm.h"
#include "OSGPrimeMaterial.h"

#include <boost/cast.hpp>

// #define OSG_SKELETON_SKINNING_ALGO_DRAW_AXIS

OSG_BEGIN_NAMESPACE

// Documentation for this class is emitted in the
// OSGSkeletonSkinningAlgorithmBase.cpp file.
// To modify it, please change the .fcd file (OSGSkeletonSkinningAlgorithm.fcd) and
// regenerate the base file.

/***************************************************************************\
 *                           Class variables                               *
\***************************************************************************/

/***************************************************************************\
 *                           Class methods                                 *
\***************************************************************************/

void SkeletonSkinningAlgorithm::initMethod(InitPhase ePhase)
{
    Inherited::initMethod(ePhase);

    if(ePhase == TypeObject::SystemPost)
    {
    }
}

/***************************************************************************\
 *                           Instance methods                              *
\***************************************************************************/

/*-------------------------------------------------------------------------*\
 -  private                                                                 -
\*-------------------------------------------------------------------------*/

/*----------------------- constructors & destructors ----------------------*/

SkeletonSkinningAlgorithm::SkeletonSkinningAlgorithm(void) :
    Inherited()
{
}

SkeletonSkinningAlgorithm::SkeletonSkinningAlgorithm(const SkeletonSkinningAlgorithm &source) :
    Inherited(source)
{
}

SkeletonSkinningAlgorithm::~SkeletonSkinningAlgorithm(void)
{
}

/*----------------------------- class specific ----------------------------*/

void
SkeletonSkinningAlgorithm::adjustVolume(Volume &volume)
{
    if(_sfSkeleton.getValue() != NULL)
        _sfSkeleton.getValue()->adjustVolume(volume);
}

ActionBase::ResultE
SkeletonSkinningAlgorithm::renderEnter(Action *action)
{
    Action::ResultE  res  = Action::Continue;
    RenderAction    *ract =
        boost::polymorphic_downcast<RenderAction *>(action);

    SkinnedGeometry *skinGeo = getSkin();
    Skeleton        *skel    = skinGeo->getSkeleton();

    skel->renderEnter(action, skinGeo);

    const Skeleton::MFJointsType        *joints       = skel->getMFJoints();
    const Skeleton::MFParentJointsType  *parentJoints =
        skel->getMFParentJoints();
    const Skeleton::MFJointMatricesType *jointMats    =
        skel->getMFJointMatrices();

//    Real32 axisLen   = 1.f;
    UInt32 numJoints = joints->size();

#ifndef OSG_SKELETON_SKINNING_ALGO_DRAW_AXIS
    _mfDrawPositions.resize(numJoints);
    _mfDrawIndex    .clear (         );

    for(UInt32 i = 0; i < numJoints; ++i)
    {
        (*jointMats)[i].mult(Pnt3f(0.f, 0.f, 0.f),
                             _mfDrawPositions[i]  );

        if((*parentJoints)[i] != NULL)
        {
            _mfDrawIndex.push_back(i                               );
            _mfDrawIndex.push_back((*parentJoints)[i]->getJointId());
        }
    }

#else
    _mfDrawPositions.resize(4 * numJoints);
    _mfDrawIndex    .clear (             );

    for(UInt32 i = 0; i < numJoints; ++i)
    {
        (*jointMats)[i].mult(Pnt3f(0.f, 0.f, 0.f),
                             _mfDrawPositions[4 * i + 0]);

        if((*parentJoints)[i] != NULL)
        {
            _mfDrawIndex.push_back(4 * i                                + 0);
            _mfDrawIndex.push_back(4 * (*parentJoints)[i]->getJointId() + 0);

            Vec3f vec =
                _mfDrawPositions[4 * i                                + 0] -
                _mfDrawPositions[4 * (*parentJoints)[i]->getJointId() + 0];

            axisLen = 0.2f * vec.length();
        }
        else
        {
            axisLen = 1.f;
        }

        (*jointMats)[i].mult(
            Pnt3f(axisLen, 0.f,     0.f    ), _mfDrawPositions[4 * i + 1]);
        (*jointMats)[i].mult(
            Pnt3f(0.f,     axisLen, 0.f    ), _mfDrawPositions[4 * i + 2]);
        (*jointMats)[i].mult(
            Pnt3f(0.f,     0.f,     axisLen), _mfDrawPositions[4 * i + 3]);

        _mfDrawIndex.push_back(4 * i + 0);
        _mfDrawIndex.push_back(4 * i + 1);
        _mfDrawIndex.push_back(4 * i + 0);
        _mfDrawIndex.push_back(4 * i + 2);
        _mfDrawIndex.push_back(4 * i + 0);
        _mfDrawIndex.push_back(4 * i + 3);
    }
#endif // #ifndef OSG_SKELETON_SKINNING_ALGO_DRAW_AXIS

    Material::DrawFunctor  drawFunc =
        boost::bind(&SkeletonSkinningAlgorithm::drawFunc, this, _1);
    PrimeMaterial         *skelMat  = getDefaultUnlitMaterial();
    State                 *state    = skelMat->getState      ();

    ract->dropFunctor(drawFunc, state, skelMat->getSortKey());

    return res;
}

ActionBase::ResultE
SkeletonSkinningAlgorithm::renderLeave(Action *action)
{
    SkinnedGeometry *skinGeo = getSkin();
    Skeleton        *skel    = getSkeleton();

    skel->renderLeave(action, skinGeo);

    return Action::Continue;
}

ActionBase::ResultE
SkeletonSkinningAlgorithm::drawFunc(DrawEnv *drawEnv)
{
    glEnableClientState(GL_VERTEX_ARRAY);
    {
        glVertexPointer(3, GL_FLOAT, 0, &(_mfDrawPositions.front()));
        glDrawElements (GL_LINES, _mfDrawIndex.size(), GL_UNSIGNED_INT,
                        &(_mfDrawIndex.front()));
    }
    glDisableClientState(GL_VERTEX_ARRAY);

    return Action::Continue;
}

void SkeletonSkinningAlgorithm::changed(ConstFieldMaskArg whichField,
                            UInt32            origin,
                            BitVector         details)
{
    Inherited::changed(whichField, origin, details);
}

void SkeletonSkinningAlgorithm::dump(      UInt32    ,
                         const BitVector ) const
{
    SLOG << "Dump SkeletonSkinningAlgorithm NI" << std::endl;
}

OSG_END_NAMESPACE
<commit_msg>fixed:   compile problems<commit_after>/*---------------------------------------------------------------------------*\
 *                                OpenSG                                     *
 *                                                                           *
 *                                                                           *
 *               Copyright (C) 2000-2006 by the OpenSG Forum                 *
 *                                                                           *
 *                            www.opensg.org                                 *
 *                                                                           *
 *   contact: dirk@opensg.org, gerrit.voss@vossg.org, jbehr@zgdv.de          *
 *                                                                           *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
 *                                License                                    *
 *                                                                           *
 * This library is free software; you can redistribute it and/or modify it   *
 * under the terms of the GNU Library General Public License as published    *
 * by the Free Software Foundation, version 2.                               *
 *                                                                           *
 * This library is distributed in the hope that it will be useful, but       *
 * WITHOUT ANY WARRANTY; without even the implied warranty of                *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU         *
 * Library General Public License for more details.                          *
 *                                                                           *
 * You should have received a copy of the GNU Library General Public         *
 * License along with this library; if not, write to the Free Software       *
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.                 *
 *                                                                           *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
 *                                Changes                                    *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
\*---------------------------------------------------------------------------*/

//---------------------------------------------------------------------------
//  Includes
//---------------------------------------------------------------------------

#include <cstdlib>
#include <cstdio>

#include <OSGConfig.h>

#include "OSGSkeletonSkinningAlgorithm.h"
#include "OSGPrimeMaterial.h"

#include <boost/cast.hpp>

// #define OSG_SKELETON_SKINNING_ALGO_DRAW_AXIS

OSG_BEGIN_NAMESPACE

// Documentation for this class is emitted in the
// OSGSkeletonSkinningAlgorithmBase.cpp file.
// To modify it, please change the .fcd file (OSGSkeletonSkinningAlgorithm.fcd) and
// regenerate the base file.

/***************************************************************************\
 *                           Class variables                               *
\***************************************************************************/

/***************************************************************************\
 *                           Class methods                                 *
\***************************************************************************/

void SkeletonSkinningAlgorithm::initMethod(InitPhase ePhase)
{
    Inherited::initMethod(ePhase);

    if(ePhase == TypeObject::SystemPost)
    {
    }
}

/***************************************************************************\
 *                           Instance methods                              *
\***************************************************************************/

/*-------------------------------------------------------------------------*\
 -  private                                                                 -
\*-------------------------------------------------------------------------*/

/*----------------------- constructors & destructors ----------------------*/

SkeletonSkinningAlgorithm::SkeletonSkinningAlgorithm(void) :
    Inherited()
{
}

SkeletonSkinningAlgorithm::SkeletonSkinningAlgorithm(const SkeletonSkinningAlgorithm &source) :
    Inherited(source)
{
}

SkeletonSkinningAlgorithm::~SkeletonSkinningAlgorithm(void)
{
}

/*----------------------------- class specific ----------------------------*/

void
SkeletonSkinningAlgorithm::adjustVolume(Volume &volume)
{
    if(_sfSkeleton.getValue() != NULL)
        _sfSkeleton.getValue()->adjustVolume(volume);
}

ActionBase::ResultE
SkeletonSkinningAlgorithm::renderEnter(Action *action)
{
    Action::ResultE  res  = Action::Continue;
    RenderAction    *ract =
        boost::polymorphic_downcast<RenderAction *>(action);

    SkinnedGeometry *skinGeo = getSkin();
    Skeleton        *skel    = skinGeo->getSkeleton();

    skel->renderEnter(action, skinGeo);

    const Skeleton::MFJointsType        *joints       = skel->getMFJoints();
    const Skeleton::MFParentJointsType  *parentJoints =
        skel->getMFParentJoints();
    const Skeleton::MFJointMatricesType *jointMats    =
        skel->getMFJointMatrices();

//    Real32 axisLen   = 1.f;
    UInt32 numJoints = joints->size();

#ifndef OSG_SKELETON_SKINNING_ALGO_DRAW_AXIS
    _mfDrawPositions.resize(numJoints);
    _mfDrawIndex    .clear (         );

    for(UInt32 i = 0; i < numJoints; ++i)
    {
        (*jointMats)[i].mult(Pnt3f(0.f, 0.f, 0.f),
                             _mfDrawPositions[i]  );

        if((*parentJoints)[i] != NULL)
        {
            _mfDrawIndex.push_back(i                               );
            _mfDrawIndex.push_back((*parentJoints)[i]->getJointId());
        }
    }

#else
    _mfDrawPositions.resize(4 * numJoints);
    _mfDrawIndex    .clear (             );

    for(UInt32 i = 0; i < numJoints; ++i)
    {
        (*jointMats)[i].mult(Pnt3f(0.f, 0.f, 0.f),
                             _mfDrawPositions[4 * i + 0]);

        if((*parentJoints)[i] != NULL)
        {
            _mfDrawIndex.push_back(4 * i                                + 0);
            _mfDrawIndex.push_back(4 * (*parentJoints)[i]->getJointId() + 0);

            Vec3f vec =
                _mfDrawPositions[4 * i                                + 0] -
                _mfDrawPositions[4 * (*parentJoints)[i]->getJointId() + 0];

            axisLen = 0.2f * vec.length();
        }
        else
        {
            axisLen = 1.f;
        }

        (*jointMats)[i].mult(
            Pnt3f(axisLen, 0.f,     0.f    ), _mfDrawPositions[4 * i + 1]);
        (*jointMats)[i].mult(
            Pnt3f(0.f,     axisLen, 0.f    ), _mfDrawPositions[4 * i + 2]);
        (*jointMats)[i].mult(
            Pnt3f(0.f,     0.f,     axisLen), _mfDrawPositions[4 * i + 3]);

        _mfDrawIndex.push_back(4 * i + 0);
        _mfDrawIndex.push_back(4 * i + 1);
        _mfDrawIndex.push_back(4 * i + 0);
        _mfDrawIndex.push_back(4 * i + 2);
        _mfDrawIndex.push_back(4 * i + 0);
        _mfDrawIndex.push_back(4 * i + 3);
    }
#endif // #ifndef OSG_SKELETON_SKINNING_ALGO_DRAW_AXIS

    DrawEnv::DrawFunctor  drawFunc =
        boost::bind(&SkeletonSkinningAlgorithm::drawFunc, this, _1);
    PrimeMaterial         *skelMat  = getDefaultUnlitMaterial();
    State                 *state    = skelMat->getState      ();

    ract->dropFunctor(drawFunc, state, skelMat->getSortKey());

    return res;
}

ActionBase::ResultE
SkeletonSkinningAlgorithm::renderLeave(Action *action)
{
    SkinnedGeometry *skinGeo = getSkin();
    Skeleton        *skel    = getSkeleton();

    skel->renderLeave(action, skinGeo);

    return Action::Continue;
}

ActionBase::ResultE
SkeletonSkinningAlgorithm::drawFunc(DrawEnv *drawEnv)
{
    glEnableClientState(GL_VERTEX_ARRAY);
    {
        glVertexPointer(3, GL_FLOAT, 0, &(_mfDrawPositions.front()));
        glDrawElements (GL_LINES, _mfDrawIndex.size(), GL_UNSIGNED_INT,
                        &(_mfDrawIndex.front()));
    }
    glDisableClientState(GL_VERTEX_ARRAY);

    return Action::Continue;
}

void SkeletonSkinningAlgorithm::changed(ConstFieldMaskArg whichField,
                            UInt32            origin,
                            BitVector         details)
{
    Inherited::changed(whichField, origin, details);
}

void SkeletonSkinningAlgorithm::dump(      UInt32    ,
                         const BitVector ) const
{
    SLOG << "Dump SkeletonSkinningAlgorithm NI" << std::endl;
}

OSG_END_NAMESPACE
<|endoftext|>