libRocket        

A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z | 0-9


content here

{WIKIPEDIA()/}
A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z | 0-9


This is an OgreGallery featured project

libRocket

libRocket

  • License MIT
  • Status Stable
  • Dependencies freetype, Ogre 1.7+ (optional), lua 5.1+ (optional), python (optional)
  • Latest Version 1.3.0
  • Instructions
  • Support GitHub page
  • Lead Developer
  • Start Date 7-October-2014

libRocket is an open source C++ interface for 3D applications. It is based on HTML and CSS specifications and covers most features of modern web browsers. A full set of widgets for simple GUI design is also provided. The HTML specification is extended by features of the object orientated programming (e. g. Templates). A scripting support of lua or python is also provided.

Building the libRocket

libRocket is distributed only as source code. You have to compile it by yourself - but it's very simple.

  1. Clone the source code from github
  2. Configure your build environment by running CMake in Build subfolder
  3. Build binaries


Attention!
Only use dynamic libraries for dependencies if you like to compile libRocket with python or lua support.

Example

This example is for Ogre 1.9/1.10 and 2.0 but you can find an 1.7 example in the source code directory https://github.com/libRocket/libRocket/tree/master/Samples/basic/ogre3d/src.

Read Setting up an Application to learn how to create the initial project and source files of the Ogre Wiki Tutorial Framework for your particular IDE and environment. Also you have to add the libRocket include and library directories to the specified options of your project.

Before you can initialize libRocket, you'll need to set the interfaces that the library uses to interact with your application. You have to create two classes for the integration:

  • Rocket::Core::SystemInterface
  • Rocket::Core::RenderInterface

System interface

The system interfaces controls the timing of libRocket. Also you could use it for localization to translate strings and output logging messages generated from the library to Ogre’s main log. A custom system interface is always required! The only required function is GetElapsedTime(), all other functions are optional.

The Ogre specific system interface declaration looks like this:

class SystemInterface : public Rocket::Core::SystemInterface
{
    public:
        SystemInterface();
        virtual ~SystemInterface();

        /**
        Get the number of seconds elapsed since the start of the application.
        @return Elapsed time, in seconds.
        */
        virtual float GetElapsedTime();

        /**
        Log the specified message.
        @param[in] type Type of log message, \c ERROR, \c WARNING, etc.
        @param[in] message Message to log.
        @return \c True to continue execution, \c false to break into the debugger.
        */
        virtual bool LogMessage(Rocket::Core::Log::Type type, const Rocket::Core::String& message);

    private:
        Ogre::Timer mTimer;
};

The corresponding source code:

SystemInterface::SystemInterface()
{
}

SystemInterface::~SystemInterface()
{
}

float SystemInterface::GetElapsedTime()
{
    return mTimer.getMilliseconds() * 0.001f;
}

bool SystemInterface::LogMessage(Rocket::Core::Log::Type type, const Rocket::Core::String& message)
{
    switch (type)
    {
        case Rocket::Core::Log::LT_ALWAYS:
        case Rocket::Core::Log::LT_ERROR:
        case Rocket::Core::Log::LT_ASSERT:
        case Rocket::Core::Log::LT_WARNING:
            Ogre::LogManager::getSingleton().logMessage(message.CString(), Ogre::LML_CRITICAL);
            break;

        default:
            Ogre::LogManager::getSingleton().logMessage(message.CString(), Ogre::LML_NORMAL);
            break;
    }
    return true;
}

GetElapsedTime returns the time of the application and the main requirement of the system interface. Also, LogMessage is implemented to send log messages of libRocket to the main Ogre log.

Render interface

The render interface is how libRocket sends its generated geometry to the application render system. Also the interface is used to load textures from files and create new textures from internally generated pixel data (for font textures). We’ll use Ogre’s resource management for this. Applications must install a render interface instance before initializing libRocket.

class RenderInterface : public Rocket::Core::RenderInterface
{
    public:
        /**
        Constructor
        @param[in] window_width Width of the render window.
        @param[in] window_height Height of the render window.
        */
        RenderInterface(unsigned int window_width, unsigned int window_height);

        /**
        Destructor
        */
        virtual ~RenderInterface();

        /**
        Called by Rocket when it wants to render geometry that the application does not wish to optimise. Note that Rocket renders everything as triangles.
        @param[in] vertices The geometry's vertex data.
        @param[in] num_vertices The number of vertices passed to the function.
        @param[in] indices The geometry's index data.
        @param[in] num_indices The number of indices passed to the function. This will always be a multiple of three.
        @param[in] texture The texture to be applied to the geometry. This may be NULL, in which case the geometry is untextured.
        @param[in] translation The translation to apply to the geometry.
        */
        virtual void RenderGeometry(Rocket::Core::Vertex* vertices, int num_vertices, int* indices, int num_indices, Rocket::Core::TextureHandle texture, const Rocket::Core::Vector2f& translation);

        /**
        Called by Rocket when it wants to compile geometry it believes will be static for the forseeable future.
        If supported, this should be return a pointer to an optimised, application-specific version of the data. If
        not, do not override the function or return \c NULL; the simpler \ref RenderGeometry() will be called instead.
        @param[in] vertices The geometry's vertex data.
        @param[in] num_vertices The number of vertices passed to the function.
        @param[in] indices The geometry's index data.
        @param[in] num_indices The number of indices passed to the function. This will always be a multiple of three.
        @param[in] texture The texture to be applied to the geometry. This may be NULL, in which case the geometry is untextured.
        @return The application-specific compiled geometry. Compiled geometry will be stored and rendered using \c RenderCompiledGeometry() in future calls, and released with \c ReleaseCompiledGeometry() when it is no longer needed.
        */
        virtual Rocket::Core::CompiledGeometryHandle CompileGeometry(Rocket::Core::Vertex* vertices, int num_vertices, int* indices, int num_indices, Rocket::Core::TextureHandle texture);

        /**
        Called by Rocket when it wants to render application-compiled geometry.
        @param[in] geometry The application-specific compiled geometry to render.
        @param[in] translation The translation to apply to the geometry.
        */
        virtual void RenderCompiledGeometry(Rocket::Core::CompiledGeometryHandle geometry, const Rocket::Core::Vector2f& translation);

        /**
        Called by Rocket when it wants to release application-compiled geometry.
        @param[in] geometry The application-specific compiled geometry to release.
        */
        virtual void ReleaseCompiledGeometry(Rocket::Core::CompiledGeometryHandle geometry);

        /**
        Called by Rocket when it wants to enable or disable scissoring to clip content.
        @param[in] enable True if scissoring is to enabled, false if it is to be disabled.
        */
        virtual void EnableScissorRegion(bool enable);

        /**
        Called by Rocket when it wants to change the scissor region.
        @param[in] x The left-most pixel to be rendered. All pixels to the left of this should be clipped.
        @param[in] y The top-most pixel to be rendered. All pixels to the top of this should be clipped.
        @param[in] width The width of the scissored region. All pixels to the right of (x + width) should be clipped.
        @param[in] height The height of the scissored region. All pixels to below (y + height) should be clipped.
        */
        virtual void SetScissorRegion(int x, int y, int width, int height);

        /**
        Called by Rocket when a texture is required by the library.
        @param[out] texture_handle The handle to write the texture handle for the loaded texture to.
        @param[out] texture_dimensions The variable to write the dimensions of the loaded texture.
        @param[in] source The application-defined image source, joined with the path of the referencing document.
        @return \c True if the load attempt succeeded and the handle and dimensions are valid, \c false if not.
        */
        virtual bool LoadTexture(Rocket::Core::TextureHandle& texture_handle, Rocket::Core::Vector2i& texture_dimensions, const Rocket::Core::String& source);

        /**
        Called by Rocket when a texture is required to be built from an internally-generated sequence of pixels.
        @param[out] texture_handle The handle to write the texture handle for the generated texture to.
        @param[in] source The raw 8-bit texture data. Each pixel is made up of four 8-bit values, indicating red, green, blue and alpha in that order.
        @param[in] source_dimensions The dimensions, in pixels, of the source data.
        @return \c True if the texture generation succeeded and the handle is valid, \c false if not.
        */
        virtual bool GenerateTexture(Rocket::Core::TextureHandle& texture_handle, const Rocket::Core::byte* source, const Rocket::Core::Vector2i& source_dimensions);

        /**
        Called by Rocket when a loaded texture is no longer required.
        @param[in] texture The texture handle to release.
        */
        virtual void ReleaseTexture(Rocket::Core::TextureHandle texture);

        /**
        Returns the native horizontal texel offset for the renderer.
        @return The renderer's horizontal texel offset. The default implementation returns \c 0.
        */
        float GetHorizontalTexelOffset();

        /**
        Returns the native vertical texel offset for the renderer.
        @return The renderer's vertical texel offset. The default implementation returns \c 0.
        */
        float GetVerticalTexelOffset();

        /**
        Set a resource group for generated textures.
        @param[in] group The resource group to add generated textures.
        */
        void setGroup(Ogre::String group = Ogre::ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME);

    private:
        Ogre::RenderSystem*     mRenderSystem;      //!< used render system
        Ogre::LayerBlendModeEx  mColourBlendMode;   //!< settings of the render system
        Ogre::LayerBlendModeEx  mAlphaBlendMode;    //!< settings of the render system
        bool                    mScissorEnable;     //!< enable/disable scissors
        size_t                  mScissorRect[4];    //!< scissor rectangle (left, top, right, bottom)
        Ogre::String            mGroup;             //!< resource group name to store generated textures
};

Now let's have a look at the implementation.

RenderInterface::RenderInterface(unsigned int window_width, unsigned int window_height)
{
    mRenderSystem = Ogre::Root::getSingletonPtr()->getRenderSystem();

    mColourBlendMode.blendType = Ogre::LBT_COLOUR;
    mColourBlendMode.source1   = Ogre::LBS_DIFFUSE;
    mColourBlendMode.source2   = Ogre::LBS_TEXTURE;
    mColourBlendMode.operation = Ogre::LBX_MODULATE;

    mAlphaBlendMode.blendType = Ogre::LBT_ALPHA;
    mAlphaBlendMode.source1   = Ogre::LBS_DIFFUSE;
    mAlphaBlendMode.source2   = Ogre::LBS_TEXTURE;
    mAlphaBlendMode.operation = Ogre::LBX_MODULATE;

    mScissorEnable = false;

    mScissorRect[0] = 0;
    mScissorRect[1] = 0;
    mScissorRect[2] = window_width;
    mScissorRect[3] = window_height;

    mGroup = Ogre::ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME;
}
    
RenderInterface::~RenderInterface()
{
}
    
void RenderInterface::RenderGeometry(Rocket::Core::Vertex* vertices, int num_vertices, int* indices, int num_indices, Rocket::Core::TextureHandle texture, const Rocket::Core::Vector2f& translation)
{
}

The constructor is used to initialize all member variables. The scissor size is set to the full size of the rendering window. It is required to implement RenderGeometry, but we leave it empty because using CompileGeometry, RenderCompiledGeometry and ReleaseCompiledGeometry is skipping calls to this function.

struct RocketVertex
{
    Ogre::Real x, y, z;
    Ogre::uint32 diffuse;
    Ogre::Real u, v;
};

struct RocketTexture
{
    RocketTexture(Ogre::TexturePtr texture)
        : mTexture(texture)
    {
    }
        
    Ogre::TexturePtr mTexture;
};

struct RocketCompiledGeometry
{
    Ogre::RenderOperation mRenderOperation;
    RocketTexture* mTexture;
};

These structs are required to store geometries and textures.

Rocket::Core::CompiledGeometryHandle RenderInterface::CompileGeometry(Rocket::Core::Vertex* vertices, int num_vertices, int* indices, int num_indices, Rocket::Core::TextureHandle texture)
{
    RocketCompiledGeometry* geometry = new RocketCompiledGeometry();
    geometry->mTexture = (texture == NULL) ? NULL : (RocketTexture*)texture;

    // Add vertex buffer
    geometry->mRenderOperation.vertexData = new Ogre::VertexData();
    geometry->mRenderOperation.vertexData->vertexStart = 0;
    geometry->mRenderOperation.vertexData->vertexCount = num_vertices;

    // Add index buffer
    geometry->mRenderOperation.indexData = new Ogre::IndexData();
    geometry->mRenderOperation.indexData->indexStart = 0;
    geometry->mRenderOperation.indexData->indexCount = num_indices;

    geometry->mRenderOperation.operationType = Ogre::RenderOperation::OT_TRIANGLE_LIST;

    // Set up the vertex declaration.
    Ogre::VertexDeclaration* vertex_declaration = geometry->mRenderOperation.vertexData->vertexDeclaration;
    size_t element_offset = 0;
    vertex_declaration->addElement(0, element_offset, Ogre::VET_FLOAT3, Ogre::VES_POSITION);
    element_offset += Ogre::VertexElement::getTypeSize(Ogre::VET_FLOAT3);
    vertex_declaration->addElement(0, element_offset, Ogre::VET_COLOUR, Ogre::VES_DIFFUSE);
    element_offset += Ogre::VertexElement::getTypeSize(Ogre::VET_COLOUR);
    vertex_declaration->addElement(0, element_offset, Ogre::VET_FLOAT2, Ogre::VES_TEXTURE_COORDINATES);

    // Create the vertex buffer.
    Ogre::HardwareVertexBufferSharedPtr vertex_buffer = Ogre::HardwareBufferManager::getSingleton().createVertexBuffer(vertex_declaration->getVertexSize(0), num_vertices, Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY);
    geometry->mRenderOperation.vertexData->vertexBufferBinding->setBinding(0, vertex_buffer);

    // Fill the vertex buffer.
    RocketVertex* ogre_vertices = (RocketVertex*)vertex_buffer->lock(0, vertex_buffer->getSizeInBytes(), Ogre::HardwareBuffer::HBL_NORMAL);
    for (int i = 0; i < num_vertices; ++i)
    {
        ogre_vertices[i].x = vertices[i].position.x;
        ogre_vertices[i].y = vertices[i].position.y;
        ogre_vertices[i].z = 0;

        Ogre::ColourValue diffuse(vertices[i].colour.red / 255.0f, vertices[i].colour.green / 255.0f, vertices[i].colour.blue / 255.0f, vertices[i].colour.alpha / 255.0f);
        mRenderSystem->convertColourValue(diffuse, &ogre_vertices[i].diffuse);

        ogre_vertices[i].u = vertices[i].tex_coord[0];
        ogre_vertices[i].v = vertices[i].tex_coord[1];
    }
    vertex_buffer->unlock();

    // Create the index buffer.
    Ogre::HardwareIndexBufferSharedPtr index_buffer = Ogre::HardwareBufferManager::getSingleton().createIndexBuffer(Ogre::HardwareIndexBuffer::IT_32BIT, num_indices, Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY);
    geometry->mRenderOperation.indexData->indexBuffer = index_buffer;
    geometry->mRenderOperation.useIndexes = true;

    // Fill the index buffer.
    void* ogre_indices = index_buffer->lock(0, index_buffer->getSizeInBytes(), Ogre::HardwareBuffer::HBL_NORMAL);
    memcpy(ogre_indices, indices, sizeof(unsigned int) * num_indices);
    index_buffer->unlock();

    return reinterpret_cast<Rocket::Core::CompiledGeometryHandle>(geometry);
}

void RenderInterface::RenderCompiledGeometry(Rocket::Core::CompiledGeometryHandle geometry, const Rocket::Core::Vector2f& translation)
{
    Ogre::Matrix4 transform;
    transform.makeTrans(translation.x, translation.y, 0);
    mRenderSystem->_setWorldMatrix(transform);
    RocketCompiledGeometry* ogre3d_geometry = (RocketCompiledGeometry*)geometry;

    if (ogre3d_geometry->mTexture != NULL)
    {
        mRenderSystem->_setTexture(0, true, ogre3d_geometry->mTexture->mTexture);
        mRenderSystem->_setTextureBlendMode(0, mColourBlendMode);
        mRenderSystem->_setTextureBlendMode(0, mAlphaBlendMode);
    }
    else
        mRenderSystem->_disableTextureUnit(0);

    mRenderSystem->_render(ogre3d_geometry->mRenderOperation);
}
    
void RenderInterface::ReleaseCompiledGeometry(Rocket::Core::CompiledGeometryHandle geometry)
{
    RocketCompiledGeometry* ogre3d_geometry = reinterpret_cast<RocketCompiledGeometry*>(geometry);
    delete ogre3d_geometry->mRenderOperation.vertexData;
    delete ogre3d_geometry->mRenderOperation.indexData;
    delete ogre3d_geometry;
}

The first function creates and store a geometry for gui drawing. If you debug into this function you'll see that the result is always a rectangle. The second function is called to render the geometry with the given texture (which contains the gui drawings). The last function destroys the created geometry. Of course, this not the most efficient way to render a GUI.

bool RenderInterface::LoadTexture(Rocket::Core::TextureHandle& texture_handle, Rocket::Core::Vector2i& texture_dimensions, const Rocket::Core::String& source)
{
    Ogre::TextureManager* texture_manager = Ogre::TextureManager::getSingletonPtr();

    // Get the file name
    Rocket::Core::String::size_type lc = source.RFind("/");
    Rocket::Core::String::size_type lc_win = source.RFind("\\");
    if (lc_win != Rocket::Core::String::npos && (lc == Rocket::Core::String::npos || lc < lc_win))
        lc = lc_win;
    Ogre::String file = (lc != Rocket::Core::String::npos) ? source.Substring(lc + 1).CString() : source.CString();
    
    // Try to find resource group
    Ogre::String group = Ogre::ResourceGroupManager::getSingletonPtr()->findGroupContainingResource(file);

    // If mGroup is set to autodetect use the resource group of the given texture as default group
    if(mGroup == Ogre::ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME && !group.empty()) mGroup = group;

    // Try to get loaded texture
    Ogre::TexturePtr ogre_texture = texture_manager->getByName(file);

    // Try to load texture if necessary
    if (ogre_texture.isNull())
        ogre_texture = texture_manager->load(file, group, Ogre::TEX_TYPE_2D, 0);

    // Error
    if (ogre_texture.isNull())
        return false;

    // Texture size
    texture_dimensions.x = ogre_texture->getWidth();
    texture_dimensions.y = ogre_texture->getHeight();

    // Create handle for the texture
    texture_handle = reinterpret_cast<Rocket::Core::TextureHandle>(new RocketTexture(ogre_texture));

    return true;
}

bool RenderInterface::GenerateTexture(Rocket::Core::TextureHandle& texture_handle, const Rocket::Core::byte* source, const Rocket::Core::Vector2i& source_dimensions)
{
    static int texture_id = 1;

    // Create a memory file
    Ogre::DataStreamPtr dataStream(new Ogre::MemoryDataStream((void*) source, source_dimensions.x * source_dimensions.y * sizeof(unsigned int)));

    // Try to create texture from memory
    Ogre::TexturePtr ogre_texture = Ogre::TextureManager::getSingleton().loadRawData(Rocket::Core::String(16, "%d", texture_id++).CString(),
                                                                                        mGroup,
                                                                                        dataStream,
                                                                                        source_dimensions.x,
                                                                                        source_dimensions.y,
                                                                                        Ogre::PF_A8B8G8R8,
                                                                                        Ogre::TEX_TYPE_2D,
                                                                                        0);

    // Error
    if (ogre_texture.isNull())
        return false;

    // Create handle for the texture
    texture_handle = reinterpret_cast<Rocket::Core::TextureHandle>(new RocketTexture(ogre_texture));
    return true;
}

void RenderInterface::ReleaseTexture(Rocket::Core::TextureHandle texture)
{
    delete ((RocketTexture*)texture);
}

These functions are used for texture handling. The first one get the file name and try to load the texture from Ogre's resource system. The GUI is a raw image, the second function is used to create an Ogre texture of it. Be careful, this functions requires a resource group. The last function is for cleaning up.

void RenderInterface::EnableScissorRegion(bool enable)
{
    mScissorEnable = enable;

    if (!mScissorEnable)
        mRenderSystem->setScissorTest(false);
    else
        mRenderSystem->setScissorTest(true, mScissorRect[0], mScissorRect[1], mScissorRect[2], mScissorRect[3]);
}
    
void RenderInterface::SetScissorRegion(int x, int y, int width, int height)
{
    mScissorRect[0] = std::max<int>(0, x);
    mScissorRect[1] = std::max<int>(0, y);
    mScissorRect[2] = x + width;
    mScissorRect[3] = y + height;

    if (mScissorEnable)
        mRenderSystem->setScissorTest(true, mScissorRect[0], mScissorRect[1], mScissorRect[2], mScissorRect[3]);
}

float RenderInterface::GetHorizontalTexelOffset()
{
    return -mRenderSystem->getHorizontalTexelOffset();
}

float RenderInterface::GetVerticalTexelOffset()
{
    return -mRenderSystem->getVerticalTexelOffset();
}

void RenderInterface::setGroup(Ogre::String group)
{
    if(group == Ogre::ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME)
    {
        group = Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME;
        Ogre::StringVector groupNameList = Ogre::ResourceGroupManager::getSingleton().getResourceGroups();
        Ogre::StringVector::iterator resGroupIter = groupNameList.begin();
        for(;resGroupIter < groupNameList.end();resGroupIter++)
        { 
            Ogre::String resGroupName = (*resGroupIter); 
            if(resGroupName == "Rocket" || resGroupName == "rocket" || resGroupName == "gui" || resGroupName == "GUI" || resGroupName == "Overlay" || resGroupName == "overlay")
            {
                group = resGroupName;
                break;
            } 
        }
    }
    mGroup = group;
}

The rest of the class are functions to enable/disable and set the scissor rectangle, getting offsets and setting the default group for GenerateTexture.

Tutorial framework modifications

To run this example, download the resources from https://github.com/libRocket/libRocket/tree/master/Samples/assets to a resource folder of the application.
BaseApplication.h

/*
-----------------------------------------------------------------------------
Filename:    BaseApplication.h
-----------------------------------------------------------------------------

This source file is part of the
   ___                 __    __ _ _    _
  /___\__ _ _ __ ___  / / /\ \ (_) | _(_)
 //  // _` | '__/ _ \ \ \/  \/ / | |/ / |
/ \_// (_| | | |  __/  \  /\  /| |   <| |
\___/ \__, |_|  \___|   \/  \/ |_|_|\_\_|
      |___/
Tutorial Framework (for Ogre 1.10)
http://www.ogre3d.org/wiki/
-----------------------------------------------------------------------------
*/

#ifndef __BaseApplication_h_
#define __BaseApplication_h_

#include <OgreCamera.h>
#include <OgreEntity.h>
#include <OgreLogManager.h>
#include <OgreRoot.h>
#include <OgreViewport.h>
#include <OgreSceneManager.h>
#include <OgreRenderWindow.h>
#include <OgreConfigFile.h>
#include <OgreMaterialManager.h>
#include <OgreTextureManager.h>
#include <OgreWindowEventUtilities.h>

#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
#  include <OIS/OISEvents.h>
#  include <OIS/OISInputManager.h>
#  include <OIS/OISKeyboard.h>
#  include <OIS/OISMouse.h>

#  include <OGRE/SdkCameraMan.h>
#else
#  include <OISEvents.h>
#  include <OISInputManager.h>
#  include <OISKeyboard.h>
#  include <OISMouse.h>

#  include <SdkCameraMan.h>
#endif

#include "RocketSystemInterface.h"
#include "RocketRenderInterface.h"

#ifdef OGRE_STATIC_LIB
#  define OGRE_STATIC_GL
#  if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
#    define OGRE_STATIC_Direct3D9
// D3D10 will only work on vista, so be careful about statically linking
#    if OGRE_USE_D3D10
#      define OGRE_STATIC_Direct3D10
#    endif
#  endif
#  define OGRE_STATIC_BSPSceneManager
#  define OGRE_STATIC_ParticleFX
#  define OGRE_STATIC_CgProgramManager
#  ifdef OGRE_USE_PCZ
#    define OGRE_STATIC_PCZSceneManager
#    define OGRE_STATIC_OctreeZone
#  else
#    define OGRE_STATIC_OctreeSceneManager
#  endif
#  include "OgreStaticPluginLoader.h"
#endif

//---------------------------------------------------------------------------

class BaseApplication : public Ogre::FrameListener, public Ogre::WindowEventListener, public OIS::KeyListener, public OIS::MouseListener, public Ogre::RenderQueueListener
{
public:
    BaseApplication(void);
    virtual ~BaseApplication(void);

    virtual void go(void);

protected:
    virtual bool setup();
    virtual bool configure(void);
    virtual void chooseSceneManager(void);
    virtual void createCamera(void);
    virtual void createFrameListener(void);
    virtual void createScene(void) = 0; // Override me!
    virtual void destroyScene(void);
#if OGRE_VERSION < ((2 << 16) | (0 << 8) | 0)
    virtual void createViewports(void);
#else
    virtual void createCompositor(void);
#endif
    virtual void setupResources(void);
    virtual void createResourceListener(void);
    virtual void loadResources(void);
    virtual bool frameRenderingQueued(const Ogre::FrameEvent& evt);

    virtual bool keyPressed(const OIS::KeyEvent &arg);
    virtual bool keyReleased(const OIS::KeyEvent &arg);
    virtual bool mouseMoved(const OIS::MouseEvent &arg);
    virtual bool mousePressed(const OIS::MouseEvent &arg, OIS::MouseButtonID id);
    virtual bool mouseReleased(const OIS::MouseEvent &arg, OIS::MouseButtonID id);

    // Adjust mouse clipping area
    virtual void windowResized(Ogre::RenderWindow* rw);
    // Unattach OIS before window shutdown (very important under Linux)
    virtual void windowClosed(Ogre::RenderWindow* rw);

#if OGRE_VERSION < ((2 << 16) | (0 << 8) | 0)
    virtual void renderQueueStarted(Ogre::uint8 queueGroupId, const Ogre::String& invocation, bool& skipThisInvocation);
#else
    virtual void renderQueueStarted(Ogre::RenderQueue *rq, Ogre::uint8 queueGroupId, const Ogre::String& invocation, bool& skipThisInvocation);
#endif

    Ogre::String getResourceFullPath(Ogre::String name, Ogre::String group = Ogre::ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME);
    int getKeyModifierState();

    Ogre::Root*                 mRoot;
    Ogre::Camera*               mCamera;
    Ogre::SceneManager*         mSceneMgr;
    Ogre::RenderWindow*         mWindow;
    Ogre::String                mResourcesCfg;
    Ogre::String                mPluginsCfg;

    typedef std::map<OIS::KeyCode, Rocket::Core::Input::KeyIdentifier> KeyIdentifierMap;
    KeyIdentifierMap mKeyIdentifiers;
    Rocket::Core::Context* mContext;
    OgreRocket::SystemInterface* mRocketSystemInterface;
    OgreRocket::RenderInterface* mRocketRenderInterface;

    OgreBites::SdkCameraMan*    mCameraMan;         // Basic camera controller
    bool                        mCursorWasVisible;    // Was cursor visible before dialog appeared?
    bool                        mShutDown;

    //OIS Input devices
    OIS::InputManager*          mInputManager;
    OIS::Mouse*                 mMouse;
    OIS::Keyboard*              mKeyboard;

    // Added for Mac compatibility
    Ogre::String                 m_ResourcePath;

#ifdef OGRE_STATIC_LIB
    Ogre::StaticPluginLoader m_StaticPluginLoader;
#endif
};

//---------------------------------------------------------------------------

#endif // #ifndef __BaseApplication_h_

//---------------------------------------------------------------------------

BaseApplication.cpp

/*
-----------------------------------------------------------------------------
Filename:    BaseApplication.cpp
-----------------------------------------------------------------------------

This source file is part of the
   ___                 __    __ _ _    _
  /___\__ _ _ __ ___  / / /\ \ (_) | _(_)
 //  // _` | '__/ _ \ \ \/  \/ / | |/ / |
/ \_// (_| | | |  __/  \  /\  /| |   <| |
\___/ \__, |_|  \___|   \/  \/ |_|_|\_\_|
      |___/
Tutorial Framework (for Ogre 1.10)
http://www.ogre3d.org/wiki/
-----------------------------------------------------------------------------
*/

#include "BaseApplication.h"
#include <Rocket/Controls.h>
#include <Rocket/Debugger.h>
#include <stdlib.h>

#if OGRE_VERSION >= ((2 << 16) | (0 << 8) | 0)
#include <Compositor/OgreCompositorManager2.h>
#endif

#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
#include <macUtils.h>
#endif

#if OGRE_PLATFORM == OGRE_PLATFORM_LINUX
#include <X11/Xlib.h>
#endif

//---------------------------------------------------------------------------
BaseApplication::BaseApplication(void)
    : mRoot(0),
    mCamera(0),
    mSceneMgr(0),
    mWindow(0),
    mResourcesCfg(Ogre::BLANKSTRING), // pre v1.10, use Ogre::StringUtil::BLANK
    mPluginsCfg(Ogre::BLANKSTRING), // pre v1.10, use Ogre::StringUtil::BLANK
    mCameraMan(0),
    mCursorWasVisible(false),
    mShutDown(false),
    mInputManager(0),
    mMouse(0),
    mKeyboard(0),
    mContext(NULL),
    mRocketSystemInterface(NULL),
    mRocketRenderInterface(NULL)
{
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
    m_ResourcePath = Ogre::macBundlePath() + "/Contents/Resources/";
#else
    m_ResourcePath = "";
#endif
    mKeyIdentifiers[OIS::KC_UNASSIGNED] = Rocket::Core::Input::KI_UNKNOWN;
    mKeyIdentifiers[OIS::KC_ESCAPE] = Rocket::Core::Input::KI_ESCAPE;
    mKeyIdentifiers[OIS::KC_1] = Rocket::Core::Input::KI_1;
    mKeyIdentifiers[OIS::KC_2] = Rocket::Core::Input::KI_2;
    mKeyIdentifiers[OIS::KC_3] = Rocket::Core::Input::KI_3;
    mKeyIdentifiers[OIS::KC_4] = Rocket::Core::Input::KI_4;
    mKeyIdentifiers[OIS::KC_5] = Rocket::Core::Input::KI_5;
    mKeyIdentifiers[OIS::KC_6] = Rocket::Core::Input::KI_6;
    mKeyIdentifiers[OIS::KC_7] = Rocket::Core::Input::KI_7;
    mKeyIdentifiers[OIS::KC_8] = Rocket::Core::Input::KI_8;
    mKeyIdentifiers[OIS::KC_9] = Rocket::Core::Input::KI_9;
    mKeyIdentifiers[OIS::KC_0] = Rocket::Core::Input::KI_0;
    mKeyIdentifiers[OIS::KC_MINUS] = Rocket::Core::Input::KI_OEM_MINUS;
    mKeyIdentifiers[OIS::KC_EQUALS] = Rocket::Core::Input::KI_OEM_PLUS;
    mKeyIdentifiers[OIS::KC_BACK] = Rocket::Core::Input::KI_BACK;
    mKeyIdentifiers[OIS::KC_TAB] = Rocket::Core::Input::KI_TAB;
    mKeyIdentifiers[OIS::KC_Q] = Rocket::Core::Input::KI_Q;
    mKeyIdentifiers[OIS::KC_W] = Rocket::Core::Input::KI_W;
    mKeyIdentifiers[OIS::KC_E] = Rocket::Core::Input::KI_E;
    mKeyIdentifiers[OIS::KC_R] = Rocket::Core::Input::KI_R;
    mKeyIdentifiers[OIS::KC_T] = Rocket::Core::Input::KI_T;
    mKeyIdentifiers[OIS::KC_Y] = Rocket::Core::Input::KI_Y;
    mKeyIdentifiers[OIS::KC_U] = Rocket::Core::Input::KI_U;
    mKeyIdentifiers[OIS::KC_I] = Rocket::Core::Input::KI_I;
    mKeyIdentifiers[OIS::KC_O] = Rocket::Core::Input::KI_O;
    mKeyIdentifiers[OIS::KC_P] = Rocket::Core::Input::KI_P;
    mKeyIdentifiers[OIS::KC_LBRACKET] = Rocket::Core::Input::KI_OEM_4;
    mKeyIdentifiers[OIS::KC_RBRACKET] = Rocket::Core::Input::KI_OEM_6;
    mKeyIdentifiers[OIS::KC_RETURN] = Rocket::Core::Input::KI_RETURN;
    mKeyIdentifiers[OIS::KC_LCONTROL] = Rocket::Core::Input::KI_LCONTROL;
    mKeyIdentifiers[OIS::KC_A] = Rocket::Core::Input::KI_A;
    mKeyIdentifiers[OIS::KC_S] = Rocket::Core::Input::KI_S;
    mKeyIdentifiers[OIS::KC_D] = Rocket::Core::Input::KI_D;
    mKeyIdentifiers[OIS::KC_F] = Rocket::Core::Input::KI_F;
    mKeyIdentifiers[OIS::KC_G] = Rocket::Core::Input::KI_G;
    mKeyIdentifiers[OIS::KC_H] = Rocket::Core::Input::KI_H;
    mKeyIdentifiers[OIS::KC_J] = Rocket::Core::Input::KI_J;
    mKeyIdentifiers[OIS::KC_K] = Rocket::Core::Input::KI_K;
    mKeyIdentifiers[OIS::KC_L] = Rocket::Core::Input::KI_L;
    mKeyIdentifiers[OIS::KC_SEMICOLON] = Rocket::Core::Input::KI_OEM_1;
    mKeyIdentifiers[OIS::KC_APOSTROPHE] = Rocket::Core::Input::KI_OEM_7;
    mKeyIdentifiers[OIS::KC_GRAVE] = Rocket::Core::Input::KI_OEM_3;
    mKeyIdentifiers[OIS::KC_LSHIFT] = Rocket::Core::Input::KI_LSHIFT;
    mKeyIdentifiers[OIS::KC_BACKSLASH] = Rocket::Core::Input::KI_OEM_5;
    mKeyIdentifiers[OIS::KC_Z] = Rocket::Core::Input::KI_Z;
    mKeyIdentifiers[OIS::KC_X] = Rocket::Core::Input::KI_X;
    mKeyIdentifiers[OIS::KC_C] = Rocket::Core::Input::KI_C;
    mKeyIdentifiers[OIS::KC_V] = Rocket::Core::Input::KI_V;
    mKeyIdentifiers[OIS::KC_B] = Rocket::Core::Input::KI_B;
    mKeyIdentifiers[OIS::KC_N] = Rocket::Core::Input::KI_N;
    mKeyIdentifiers[OIS::KC_M] = Rocket::Core::Input::KI_M;
    mKeyIdentifiers[OIS::KC_COMMA] = Rocket::Core::Input::KI_OEM_COMMA;
    mKeyIdentifiers[OIS::KC_PERIOD] = Rocket::Core::Input::KI_OEM_PERIOD;
    mKeyIdentifiers[OIS::KC_SLASH] = Rocket::Core::Input::KI_OEM_2;
    mKeyIdentifiers[OIS::KC_RSHIFT] = Rocket::Core::Input::KI_RSHIFT;
    mKeyIdentifiers[OIS::KC_MULTIPLY] = Rocket::Core::Input::KI_MULTIPLY;
    mKeyIdentifiers[OIS::KC_LMENU] = Rocket::Core::Input::KI_LMENU;
    mKeyIdentifiers[OIS::KC_SPACE] = Rocket::Core::Input::KI_SPACE;
    mKeyIdentifiers[OIS::KC_CAPITAL] = Rocket::Core::Input::KI_CAPITAL;
    mKeyIdentifiers[OIS::KC_F1] = Rocket::Core::Input::KI_F1;
    mKeyIdentifiers[OIS::KC_F2] = Rocket::Core::Input::KI_F2;
    mKeyIdentifiers[OIS::KC_F3] = Rocket::Core::Input::KI_F3;
    mKeyIdentifiers[OIS::KC_F4] = Rocket::Core::Input::KI_F4;
    mKeyIdentifiers[OIS::KC_F5] = Rocket::Core::Input::KI_F5;
    mKeyIdentifiers[OIS::KC_F6] = Rocket::Core::Input::KI_F6;
    mKeyIdentifiers[OIS::KC_F7] = Rocket::Core::Input::KI_F7;
    mKeyIdentifiers[OIS::KC_F8] = Rocket::Core::Input::KI_F8;
    mKeyIdentifiers[OIS::KC_F9] = Rocket::Core::Input::KI_F9;
    mKeyIdentifiers[OIS::KC_F10] = Rocket::Core::Input::KI_F10;
    mKeyIdentifiers[OIS::KC_NUMLOCK] = Rocket::Core::Input::KI_NUMLOCK;
    mKeyIdentifiers[OIS::KC_SCROLL] = Rocket::Core::Input::KI_SCROLL;
    mKeyIdentifiers[OIS::KC_NUMPAD7] = Rocket::Core::Input::KI_7;
    mKeyIdentifiers[OIS::KC_NUMPAD8] = Rocket::Core::Input::KI_8;
    mKeyIdentifiers[OIS::KC_NUMPAD9] = Rocket::Core::Input::KI_9;
    mKeyIdentifiers[OIS::KC_SUBTRACT] = Rocket::Core::Input::KI_SUBTRACT;
    mKeyIdentifiers[OIS::KC_NUMPAD4] = Rocket::Core::Input::KI_4;
    mKeyIdentifiers[OIS::KC_NUMPAD5] = Rocket::Core::Input::KI_5;
    mKeyIdentifiers[OIS::KC_NUMPAD6] = Rocket::Core::Input::KI_6;
    mKeyIdentifiers[OIS::KC_ADD] = Rocket::Core::Input::KI_ADD;
    mKeyIdentifiers[OIS::KC_NUMPAD1] = Rocket::Core::Input::KI_1;
    mKeyIdentifiers[OIS::KC_NUMPAD2] = Rocket::Core::Input::KI_2;
    mKeyIdentifiers[OIS::KC_NUMPAD3] = Rocket::Core::Input::KI_3;
    mKeyIdentifiers[OIS::KC_NUMPAD0] = Rocket::Core::Input::KI_0;
    mKeyIdentifiers[OIS::KC_DECIMAL] = Rocket::Core::Input::KI_DECIMAL;
    mKeyIdentifiers[OIS::KC_OEM_102] = Rocket::Core::Input::KI_OEM_102;
    mKeyIdentifiers[OIS::KC_F11] = Rocket::Core::Input::KI_F11;
    mKeyIdentifiers[OIS::KC_F12] = Rocket::Core::Input::KI_F12;
    mKeyIdentifiers[OIS::KC_F13] = Rocket::Core::Input::KI_F13;
    mKeyIdentifiers[OIS::KC_F14] = Rocket::Core::Input::KI_F14;
    mKeyIdentifiers[OIS::KC_F15] = Rocket::Core::Input::KI_F15;
    mKeyIdentifiers[OIS::KC_KANA] = Rocket::Core::Input::KI_KANA;
    mKeyIdentifiers[OIS::KC_ABNT_C1] = Rocket::Core::Input::KI_UNKNOWN;
    mKeyIdentifiers[OIS::KC_CONVERT] = Rocket::Core::Input::KI_CONVERT;
    mKeyIdentifiers[OIS::KC_NOCONVERT] = Rocket::Core::Input::KI_NONCONVERT;
    mKeyIdentifiers[OIS::KC_YEN] = Rocket::Core::Input::KI_UNKNOWN;
    mKeyIdentifiers[OIS::KC_ABNT_C2] = Rocket::Core::Input::KI_UNKNOWN;
    mKeyIdentifiers[OIS::KC_NUMPADEQUALS] = Rocket::Core::Input::KI_OEM_NEC_EQUAL;
    mKeyIdentifiers[OIS::KC_PREVTRACK] = Rocket::Core::Input::KI_MEDIA_PREV_TRACK;
    mKeyIdentifiers[OIS::KC_AT] = Rocket::Core::Input::KI_UNKNOWN;
    mKeyIdentifiers[OIS::KC_COLON] = Rocket::Core::Input::KI_OEM_1;
    mKeyIdentifiers[OIS::KC_UNDERLINE] = Rocket::Core::Input::KI_OEM_MINUS;
    mKeyIdentifiers[OIS::KC_KANJI] = Rocket::Core::Input::KI_KANJI;
    mKeyIdentifiers[OIS::KC_STOP] = Rocket::Core::Input::KI_UNKNOWN;
    mKeyIdentifiers[OIS::KC_AX] = Rocket::Core::Input::KI_OEM_AX;
    mKeyIdentifiers[OIS::KC_UNLABELED] = Rocket::Core::Input::KI_UNKNOWN;
    mKeyIdentifiers[OIS::KC_NEXTTRACK] = Rocket::Core::Input::KI_MEDIA_NEXT_TRACK;
    mKeyIdentifiers[OIS::KC_NUMPADENTER] = Rocket::Core::Input::KI_NUMPADENTER;
    mKeyIdentifiers[OIS::KC_RCONTROL] = Rocket::Core::Input::KI_RCONTROL;
    mKeyIdentifiers[OIS::KC_MUTE] = Rocket::Core::Input::KI_VOLUME_MUTE;
    mKeyIdentifiers[OIS::KC_CALCULATOR] = Rocket::Core::Input::KI_UNKNOWN;
    mKeyIdentifiers[OIS::KC_PLAYPAUSE] = Rocket::Core::Input::KI_MEDIA_PLAY_PAUSE;
    mKeyIdentifiers[OIS::KC_MEDIASTOP] = Rocket::Core::Input::KI_MEDIA_STOP;
    mKeyIdentifiers[OIS::KC_VOLUMEDOWN] = Rocket::Core::Input::KI_VOLUME_DOWN;
    mKeyIdentifiers[OIS::KC_VOLUMEUP] = Rocket::Core::Input::KI_VOLUME_UP;
    mKeyIdentifiers[OIS::KC_WEBHOME] = Rocket::Core::Input::KI_BROWSER_HOME;
    mKeyIdentifiers[OIS::KC_NUMPADCOMMA] = Rocket::Core::Input::KI_SEPARATOR;
    mKeyIdentifiers[OIS::KC_DIVIDE] = Rocket::Core::Input::KI_DIVIDE;
    mKeyIdentifiers[OIS::KC_SYSRQ] = Rocket::Core::Input::KI_SNAPSHOT;
    mKeyIdentifiers[OIS::KC_RMENU] = Rocket::Core::Input::KI_RMENU;
    mKeyIdentifiers[OIS::KC_PAUSE] = Rocket::Core::Input::KI_PAUSE;
    mKeyIdentifiers[OIS::KC_HOME] = Rocket::Core::Input::KI_HOME;
    mKeyIdentifiers[OIS::KC_UP] = Rocket::Core::Input::KI_UP;
    mKeyIdentifiers[OIS::KC_PGUP] = Rocket::Core::Input::KI_PRIOR;
    mKeyIdentifiers[OIS::KC_LEFT] = Rocket::Core::Input::KI_LEFT;
    mKeyIdentifiers[OIS::KC_RIGHT] = Rocket::Core::Input::KI_RIGHT;
    mKeyIdentifiers[OIS::KC_END] = Rocket::Core::Input::KI_END;
    mKeyIdentifiers[OIS::KC_DOWN] = Rocket::Core::Input::KI_DOWN;
    mKeyIdentifiers[OIS::KC_PGDOWN] = Rocket::Core::Input::KI_NEXT;
    mKeyIdentifiers[OIS::KC_INSERT] = Rocket::Core::Input::KI_INSERT;
    mKeyIdentifiers[OIS::KC_DELETE] = Rocket::Core::Input::KI_DELETE;
    mKeyIdentifiers[OIS::KC_LWIN] = Rocket::Core::Input::KI_LWIN;
    mKeyIdentifiers[OIS::KC_RWIN] = Rocket::Core::Input::KI_RWIN;
    mKeyIdentifiers[OIS::KC_APPS] = Rocket::Core::Input::KI_APPS;
    mKeyIdentifiers[OIS::KC_POWER] = Rocket::Core::Input::KI_POWER;
    mKeyIdentifiers[OIS::KC_SLEEP] = Rocket::Core::Input::KI_SLEEP;
    mKeyIdentifiers[OIS::KC_WAKE] = Rocket::Core::Input::KI_WAKE;
    mKeyIdentifiers[OIS::KC_WEBSEARCH] = Rocket::Core::Input::KI_BROWSER_SEARCH;
    mKeyIdentifiers[OIS::KC_WEBFAVORITES] = Rocket::Core::Input::KI_BROWSER_FAVORITES;
    mKeyIdentifiers[OIS::KC_WEBREFRESH] = Rocket::Core::Input::KI_BROWSER_REFRESH;
    mKeyIdentifiers[OIS::KC_WEBSTOP] = Rocket::Core::Input::KI_BROWSER_STOP;
    mKeyIdentifiers[OIS::KC_WEBFORWARD] = Rocket::Core::Input::KI_BROWSER_FORWARD;
    mKeyIdentifiers[OIS::KC_WEBBACK] = Rocket::Core::Input::KI_BROWSER_BACK;
    mKeyIdentifiers[OIS::KC_MYCOMPUTER] = Rocket::Core::Input::KI_UNKNOWN;
    mKeyIdentifiers[OIS::KC_MAIL] = Rocket::Core::Input::KI_LAUNCH_MAIL;
    mKeyIdentifiers[OIS::KC_MEDIASELECT] = Rocket::Core::Input::KI_LAUNCH_MEDIA_SELECT;
}

//---------------------------------------------------------------------------
BaseApplication::~BaseApplication(void)
{
    if(mContext) mContext->RemoveReference();
    Rocket::Core::Shutdown();

    if(mRocketSystemInterface) delete mRocketSystemInterface;
    if(mRocketRenderInterface) delete mRocketRenderInterface;

    if (mCameraMan) delete mCameraMan;

    // Remove ourself as a Window listener
    Ogre::WindowEventUtilities::removeWindowEventListener(mWindow, this);
    windowClosed(mWindow);
    delete mRoot;
}

//---------------------------------------------------------------------------
bool BaseApplication::configure(void)
{
    // Show the configuration dialog and initialise the system.
    // You can skip this and use root.restoreConfig() to load configuration
    // settings if you were sure there are valid ones saved in ogre.cfg.
    if(mRoot->showConfigDialog())
    {
        // If returned true, user clicked OK so initialise.
        // Here we choose to let the system create a default rendering window by passing 'true'.
        mWindow = mRoot->initialise(true, "TutorialApplication Render Window");

        return true;
    }
    else
    {
        return false;
    }
}
//---------------------------------------------------------------------------
void BaseApplication::chooseSceneManager(void)
{
#if OGRE_VERSION < ((2 << 16) | (0 << 8) | 0)
    // Get the SceneManager, in this case a generic one
    mSceneMgr = mRoot->createSceneManager(Ogre::ST_GENERIC);
#else
    const size_t numThreads = std::max<int>(1, Ogre::PlatformInformation::getNumLogicalCores());
    Ogre::InstancingTheadedCullingMethod threadedCullingMethod = (numThreads > 1) ? Ogre::INSTANCING_CULLING_THREADED : Ogre::INSTANCING_CULLING_SINGLETHREAD;
    mSceneMgr = mRoot->createSceneManager(Ogre::ST_GENERIC, numThreads, threadedCullingMethod);
#endif
}
//---------------------------------------------------------------------------
void BaseApplication::createCamera(void)
{
    // Create the camera
    mCamera = mSceneMgr->createCamera("PlayerCam");

    // Position it at 500 in Z direction
    mCamera->setPosition(Ogre::Vector3(0,0,80));
    // Look back along -Z
    mCamera->lookAt(Ogre::Vector3(0,0,-300));
    mCamera->setNearClipDistance(5);

    mCameraMan = new OgreBites::SdkCameraMan(mCamera);   // Create a default camera controller
}
//---------------------------------------------------------------------------
void BaseApplication::createFrameListener(void)
{
    Ogre::LogManager::getSingletonPtr()->logMessage("*** Initializing OIS ***");
    OIS::ParamList pl;
    size_t windowHnd = 0;
    std::ostringstream windowHndStr;

    mWindow->getCustomAttribute("WINDOW", &windowHnd);
    windowHndStr << windowHnd;
    pl.insert(std::make_pair(std::string("WINDOW"), windowHndStr.str()));

    mInputManager = OIS::InputManager::createInputSystem(pl);

    mKeyboard = static_cast<OIS::Keyboard*>(mInputManager->createInputObject(OIS::OISKeyboard, true));
    mMouse = static_cast<OIS::Mouse*>(mInputManager->createInputObject(OIS::OISMouse, true));

    mMouse->setEventCallback(this);
    mKeyboard->setEventCallback(this);

    // Set initial mouse clipping size
    windowResized(mWindow);

    //Register as a Window listener
    Ogre::WindowEventUtilities::addWindowEventListener(mWindow, this);
 
    // Init overlay
    mRocketRenderInterface = new OgreRocket::RenderInterface(mWindow->getWidth(), mWindow->getHeight());
    Rocket::Core::SetRenderInterface(mRocketRenderInterface);

    mRocketSystemInterface = new OgreRocket::SystemInterface();
    Rocket::Core::SetSystemInterface(mRocketSystemInterface);

    Rocket::Core::Initialise();
    Rocket::Controls::Initialise();
    mRocketRenderInterface->setGroup(Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);

    Rocket::Core::FontDatabase::LoadFontFace(getResourceFullPath("Delicious-Roman.otf").c_str());
    Rocket::Core::FontDatabase::LoadFontFace(getResourceFullPath("Delicious-Bold.otf").c_str());
    Rocket::Core::FontDatabase::LoadFontFace(getResourceFullPath("Delicious-Italic.otf").c_str());
    Rocket::Core::FontDatabase::LoadFontFace(getResourceFullPath("Delicious-BoldItalic.otf").c_str());

    mContext = Rocket::Core::CreateContext("main", Rocket::Core::Vector2i(mWindow->getWidth(), mWindow->getHeight()));
    Rocket::Debugger::Initialise(mContext);

    Rocket::Core::ElementDocument* cursor = mContext->LoadMouseCursor(getResourceFullPath("cursor.rml").c_str());
    if (cursor)
        cursor->RemoveReference();

    Rocket::Core::ElementDocument* document = mContext->LoadDocument(getResourceFullPath("demo.rml").c_str());
    if (document)
    {
        document->Show();
        document->RemoveReference();
    }
    
    //Register as a RenderQueueListener
    mSceneMgr->addRenderQueueListener(this);

    //Register as a FrameListener
    mRoot->addFrameListener(this);
}
//---------------------------------------------------------------------------
void BaseApplication::destroyScene(void)
{
}
//---------------------------------------------------------------------------
#if OGRE_VERSION < ((2 << 16) | (0 << 8) | 0)
void BaseApplication::createViewports(void)
{
    // Create one viewport, entire window
    Ogre::Viewport* vp = mWindow->addViewport(mCamera);
    vp->setBackgroundColour(Ogre::ColourValue(0,0,0));

    // Alter the camera aspect ratio to match the viewport
    mCamera->setAspectRatio(Ogre::Real(vp->getActualWidth()) / Ogre::Real(vp->getActualHeight()));
}
#else
void BaseApplication::createCompositor(void)
{
    mRoot->initialiseCompositor();
    Ogre::CompositorManager2* compMan = mRoot->getCompositorManager2();
    const Ogre::String workspaceName = "default scene workspace";
    const Ogre::IdString workspaceNameHash = workspaceName;
    compMan->createBasicWorkspaceDef(workspaceName, Ogre::ColourValue::Black);
    compMan->addWorkspace(mSceneMgr, mWindow, mCamera, workspaceNameHash, true);
}
#endif
//---------------------------------------------------------------------------
void BaseApplication::setupResources(void)
{
    // Load resource paths from config file
    Ogre::ConfigFile cf;
    cf.load(mResourcesCfg);

    // Go through all sections & settings in the file
    Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();

    Ogre::String secName, typeName, archName;
    while (seci.hasMoreElements())
    {
        secName = seci.peekNextKey();
        Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext();
        Ogre::ConfigFile::SettingsMultiMap::iterator i;
        for (i = settings->begin(); i != settings->end(); ++i)
        {
            typeName = i->first;
            archName = i->second;

#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
            // OS X does not set the working directory relative to the app.
            // In order to make things portable on OS X we need to provide
            // the loading with it's own bundle path location.
            if (!Ogre::StringUtil::startsWith(archName, "/", false)) // only adjust relative directories
                archName = Ogre::String(Ogre::macBundlePath() + "/" + archName);
#endif

            Ogre::ResourceGroupManager::getSingleton().addResourceLocation(
                archName, typeName, secName);
        }
    }
}
//---------------------------------------------------------------------------
void BaseApplication::createResourceListener(void)
{
}
//---------------------------------------------------------------------------
void BaseApplication::loadResources(void)
{
    Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
}
//---------------------------------------------------------------------------
void BaseApplication::go(void)
{
#ifdef _DEBUG
#ifndef OGRE_STATIC_LIB
    mResourcesCfg = m_ResourcePath + "resources_d.cfg";
    mPluginsCfg = m_ResourcePath + "plugins_d.cfg";
#else
    mResourcesCfg = "resources_d.cfg";
    mPluginsCfg = "plugins_d.cfg";
#endif
#else
#ifndef OGRE_STATIC_LIB
    mResourcesCfg = m_ResourcePath + "resources.cfg";
    mPluginsCfg = m_ResourcePath + "plugins.cfg";
#else
    mResourcesCfg = "resources.cfg";
    mPluginsCfg = "plugins.cfg";
#endif
#endif

    if (!setup())
        return;

    mRoot->startRendering();

    // Clean up
    destroyScene();
}
//---------------------------------------------------------------------------
bool BaseApplication::setup(void)
{
    mRoot = new Ogre::Root(mPluginsCfg);

    setupResources();

    bool carryOn = configure();
    if (!carryOn) return false;

    chooseSceneManager();
    createCamera();
#if OGRE_VERSION < ((2 << 16) | (0 << 8) | 0)
    createViewports();
#else
    createCompositor();
#endif

    // Set default mipmap level (NB some APIs ignore this)
    Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);

    // Create any resource listeners (for loading screens)
    createResourceListener();
    // Load resources
    loadResources();

    // Create the scene
    createScene();

    createFrameListener();

    return true;
};
//---------------------------------------------------------------------------
bool BaseApplication::frameRenderingQueued(const Ogre::FrameEvent& evt)
{
    if(mWindow->isClosed())
        return false;

    if(mShutDown)
        return false;

    // Need to capture/update each device
    mKeyboard->capture();
    mMouse->capture();

    return true;
}
//---------------------------------------------------------------------------
bool BaseApplication::keyPressed( const OIS::KeyEvent &arg )
{
    if(arg.key == OIS::KC_F5)   // refresh all textures
    {
        Ogre::TextureManager::getSingleton().reloadAll();
    }
    else if (arg.key == OIS::KC_SYSRQ)   // take a screenshot
    {
        mWindow->writeContentsToTimestampedFile("screenshot", ".jpg");
    }
    else if (arg.key == OIS::KC_ESCAPE)
    {
        mShutDown = true;
    }

    if(mContext != NULL)
    {
        Rocket::Core::Input::KeyIdentifier key_identifier = mKeyIdentifiers[arg.key];

        // Toggle the debugger on a shift-~ press.
        if (key_identifier == Rocket::Core::Input::KI_OEM_3 && (getKeyModifierState() & Rocket::Core::Input::KM_SHIFT))
        {
            Rocket::Debugger::SetVisible(!Rocket::Debugger::IsVisible());
            return true;
        }

        if (key_identifier != Rocket::Core::Input::KI_UNKNOWN)
            mContext->ProcessKeyDown(key_identifier, getKeyModifierState());

        // Send through the ASCII value as text input if it is printable.
        if (arg.text >= 32)
            mContext->ProcessTextInput((Rocket::Core::word) arg.text);
        else if (key_identifier == Rocket::Core::Input::KI_RETURN)
            mContext->ProcessTextInput((Rocket::Core::word) '\n');
    }
    mCameraMan->injectKeyDown(arg);
    return true;
}
//---------------------------------------------------------------------------
bool BaseApplication::keyReleased(const OIS::KeyEvent &arg)
{
    if(mContext != NULL)
    {
        Rocket::Core::Input::KeyIdentifier key_identifier = mKeyIdentifiers[arg.key];

        if (key_identifier != Rocket::Core::Input::KI_UNKNOWN)
            mContext->ProcessKeyUp(key_identifier, getKeyModifierState());
    }

    mCameraMan->injectKeyUp(arg);
    return true;
}
//---------------------------------------------------------------------------
bool BaseApplication::mouseMoved(const OIS::MouseEvent &arg)
{
    if(mContext != NULL)
    {
        int key_modifier_state = getKeyModifierState();

        mContext->ProcessMouseMove(arg.state.X.abs, arg.state.Y.abs, key_modifier_state);
        if (arg.state.Z.rel != 0)
            mContext->ProcessMouseWheel(arg.state.Z.rel / -120, key_modifier_state);
    }
    mCameraMan->injectMouseMove(arg);
    return true;
}
//---------------------------------------------------------------------------
bool BaseApplication::mousePressed(const OIS::MouseEvent &arg, OIS::MouseButtonID id)
{
    if(mContext != NULL) mContext->ProcessMouseButtonDown((int) id, getKeyModifierState());
    mCameraMan->injectMouseDown(arg, id);
    return true;
}
//---------------------------------------------------------------------------
bool BaseApplication::mouseReleased(const OIS::MouseEvent &arg, OIS::MouseButtonID id)
{
    if(mContext != NULL) mContext->ProcessMouseButtonUp((int) id, getKeyModifierState());
    mCameraMan->injectMouseUp(arg, id);
    return true;
}
//---------------------------------------------------------------------------
// Adjust mouse clipping area
void BaseApplication::windowResized(Ogre::RenderWindow* rw)
{
    unsigned int width, height, depth;
    int left, top;
    rw->getMetrics(width, height, depth, left, top);

    const OIS::MouseState &ms = mMouse->getMouseState();
    ms.width = width;
    ms.height = height;
}
//---------------------------------------------------------------------------
// Unattach OIS before window shutdown (very important under Linux)
void BaseApplication::windowClosed(Ogre::RenderWindow* rw)
{
    // Only close for window that created OIS (the main window in these demos)
    if(rw == mWindow)
    {
        if(mInputManager)
        {
            mInputManager->destroyInputObject(mMouse);
            mInputManager->destroyInputObject(mKeyboard);

            OIS::InputManager::destroyInputSystem(mInputManager);
            mInputManager = 0;
        }
    }
}
//---------------------------------------------------------------------------
#if OGRE_VERSION < ((2 << 16) | (0 << 8) | 0)
void BaseApplication::renderQueueStarted(Ogre::uint8 queueGroupId, const Ogre::String& invocation, bool& skipThisInvocation)
#else
void BaseApplication::renderQueueStarted(Ogre::RenderQueue *rq, Ogre::uint8 queueGroupId, const Ogre::String& invocation, bool& skipThisInvocation)
#endif
{
    if (queueGroupId == Ogre::RENDER_QUEUE_OVERLAY && Ogre::Root::getSingleton().getRenderSystem()->_getViewport()->getOverlaysEnabled())
    {
        Ogre::RenderSystem* render_system = mRoot->getRenderSystem();
        mContext->Update();

        // Set up the projection and view matrices.
        float z_near = -1;
        float z_far = 1;
        Ogre::Matrix4 projection_matrix = Ogre::Matrix4::ZERO;
        projection_matrix[0][0] = 2.0f / (Ogre::Real)mWindow->getWidth();
        projection_matrix[0][3]= -1.0000000f;
        projection_matrix[1][1]= -2.0f / (Ogre::Real)mWindow->getHeight();
        projection_matrix[1][3]= 1.0000000f;
        projection_matrix[2][2]= -2.0f / (z_far - z_near);
        projection_matrix[3][3]= 1.0000000f;
        render_system->_setProjectionMatrix(projection_matrix);
        render_system->_setViewMatrix(Ogre::Matrix4::IDENTITY);

        // Disable lighting, as all of Rocket's geometry is unlit.
        render_system->setLightingEnabled(false);
        // Disable depth-buffering; all of the geometry is already depth-sorted.
        render_system->_setDepthBufferParams(false, false);
        // Rocket generates anti-clockwise geometry, so enable clockwise-culling.
        render_system->_setCullingMode(Ogre::CULL_CLOCKWISE);
        // Disable fogging.
        render_system->_setFog(Ogre::FOG_NONE);
        // Enable writing to all four channels.
        render_system->_setColourBufferWriteEnabled(true, true, true, true);
        // Unbind any vertex or fragment programs bound previously by the application.
        render_system->unbindGpuProgram(Ogre::GPT_FRAGMENT_PROGRAM);
        render_system->unbindGpuProgram(Ogre::GPT_VERTEX_PROGRAM);

        // Set texture settings to clamp along both axes.
        Ogre::TextureUnitState::UVWAddressingMode addressing_mode;
        addressing_mode.u = Ogre::TextureUnitState::TAM_CLAMP;
        addressing_mode.v = Ogre::TextureUnitState::TAM_CLAMP;
        addressing_mode.w = Ogre::TextureUnitState::TAM_CLAMP;
        render_system->_setTextureAddressingMode(0, addressing_mode);

        // Set the texture coordinates for unit 0 to be read from unit 0.
        render_system->_setTextureCoordSet(0, 0);
        // Disable texture coordinate calculation.
        render_system->_setTextureCoordCalculation(0, Ogre::TEXCALC_NONE);
        // Enable linear filtering; images should be rendering 1 texel == 1 pixel, so point filtering could be used
        // except in the case of scaling tiled decorators.
        render_system->_setTextureUnitFiltering(0, Ogre::FO_LINEAR, Ogre::FO_LINEAR, Ogre::FO_POINT);
        // Disable texture coordinate transforms.
        render_system->_setTextureMatrix(0, Ogre::Matrix4::IDENTITY);
        // Reject pixels with an alpha of 0.
        render_system->_setAlphaRejectSettings(Ogre::CMPF_GREATER, 0, false);
        // Disable all texture units but the first.
        render_system->_disableTextureUnitsFrom(1);

        // Enable simple alpha blending.
        render_system->_setSceneBlending(Ogre::SBF_SOURCE_ALPHA, Ogre::SBF_ONE_MINUS_SOURCE_ALPHA);

        // Disable depth bias.
        render_system->_setDepthBias(0, 0);

        mContext->Render();
    }
}
//-------------------------------------------------------------------------------------
Ogre::String BaseApplication::getResourceFullPath(Ogre::String name, Ogre::String group)
{
    if(group.empty() || group == Ogre::ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME) group = Ogre::ResourceGroupManager::getSingletonPtr()->findGroupContainingResource(name);
    if(group.empty()) return "";
    Ogre::FileInfoListPtr fileInfoList(Ogre::ResourceGroupManager::getSingletonPtr()->findResourceFileInfo(group, name));
    for(Ogre::FileInfoList::iterator iter = fileInfoList->begin(); iter != fileInfoList->end(); iter++)
    {
        if(iter->filename.compare(name) == 0)
        {
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
            char* seperator = "\\";
            char wdPath[MAX_PATH];
            memset(wdPath, 0, MAX_PATH * sizeof(char));
            GetCurrentDirectoryA(MAX_PATH, wdPath);
            size_t len = strlen(wdPath);
            if(wdPath[len - 1] != seperator[0]) strcat_s(wdPath, MAX_PATH, seperator);
            strcat_s(wdPath, MAX_PATH, iter->archive->getName().c_str());
            len = strlen(wdPath);
            if(wdPath[len - 1] != seperator[0]) strcat_s(wdPath, MAX_PATH, seperator);
            strcat_s(wdPath, MAX_PATH, name.c_str());
            return Ogre::String(wdPath);
#else
            char wdPath[PATH_MAX];
            std::string fullpath(iter->archive->getName().c_str());
            fullpath.append("/");
            fullpath.append(name.c_str());
            return Ogre::String(realpath(fullpath.c_str(), wdPath));
#endif
        }
    }
    return "";
}
//---------------------------------------------------------------------------
int BaseApplication::getKeyModifierState()
{
    int modifier_state = 0;

    if(mKeyboard != NULL)
    {
        if (mKeyboard->isModifierDown(OIS::Keyboard::Ctrl))
            modifier_state |= Rocket::Core::Input::KM_CTRL;
        if (mKeyboard->isModifierDown(OIS::Keyboard::Shift))
            modifier_state |= Rocket::Core::Input::KM_SHIFT;
        if (mKeyboard->isModifierDown(OIS::Keyboard::Alt))
            modifier_state |= Rocket::Core::Input::KM_ALT;
    }

#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32

    if (GetKeyState(VK_CAPITAL) > 0)
        modifier_state |= Rocket::Core::Input::KM_CAPSLOCK;
    if (GetKeyState(VK_NUMLOCK) > 0)
        modifier_state |= Rocket::Core::Input::KM_NUMLOCK;
    if (GetKeyState(VK_SCROLL) > 0)
        modifier_state |= Rocket::Core::Input::KM_SCROLLLOCK;

#elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE

    UInt32 key_modifiers = GetCurrentEventKeyModifiers();
    if (key_modifiers & (1 << alphaLockBit))
        modifier_state |= Rocket::Core::Input::KM_CAPSLOCK;

#elif OGRE_PLATFORM == OGRE_PLATFORM_LINUX

    XKeyboardState keyboard_state;
    // Thank You lloydw on the librocket forum for this fix:
    Display * display;
    mWindow->getCustomAttribute("DISPLAY", & display);
    XGetKeyboardControl(display, &keyboard_state);

    if (keyboard_state.led_mask & (1 << 0))
        modifier_state |= Rocket::Core::Input::KM_CAPSLOCK;
    if (keyboard_state.led_mask & (1 << 1))
        modifier_state |= Rocket::Core::Input::KM_NUMLOCK;
    if (keyboard_state.led_mask & (1 << 2))
        modifier_state |= Rocket::Core::Input::KM_SCROLLLOCK;

#endif

    return modifier_state;
}
//---------------------------------------------------------------------------

Screenshots

This is what you should see if the example works correctly:
librocket_example.png


TODO:

  • Extends article