Using SDL Input         Adding SDL to an OGRE project
IMPORTANT: This framework is meant to be used with old releases of Ogre. For Ogre 1.10+, rather use OgreBites::ApplicationContext.


The SDL Library has been around for several years and is an extremely mature library that covers all issues of a game range from audio, timing and input to video. In this article we are only going to be using SDL for its input part and if desired, timing functions.

This article is focused on adding SDL to an OGRE project. Yet, you first need to setup SDL libraries and includes files.

Accessing Our Events

To get at the SDL events we need to use one of the SDL input functions such as SDL_PollEvent. It will look something like this:

SDL_Event event;
while(SDL_PollEvent(&event))
    {
     switch(event.type)
     { 
        case SDL_KEYDOWN:         
         out<<"Oh! Key press\n";
        break;
        case SDL_MOUSEMOTION: 
         out<<"Mouse Motion\n";
        break;
        case SDL_QUIT:
            i=-1;
        break;
        default:
         out<<"I don't know what this event is!\n";
     }
}

Setting Up OGRE and SDL

There are two ways to do this, the "conventional" way and the "experimental" way. The conventional way works on all versions of OGRE, but (in my opinion) requires an uncomfortable level of hackery. The experimental way only works on OGRE 1.6 or later, but uses far less code and hackery. You decide.

The conventional way is quite old, from a time when OGRE had a SDL backend. Current versions of OGRE are totally separated from SDL, so there's no longer any need to check SDL_WasInit().

Conventional Way

Windows

On Windows, SDL wants to create its own window. With OGRE also creating its own window, you end up having 2 windows where you can choose to either see something or have input. To get both, we need SDL and OGRE in one window. You can put OGRE in a SDL window, but that doesn't work very well, so we tell SDL to use the OGRE window. This is done by setting an SDL_WINDOWID environment variable. In this example is also the code for grabbing input, which means the mouse cursor dissapears and is confined to the window rectangle.

You will also need a few includes, assuming you've also got the OGRE initialization code and SDL initialization code in seperate files here is what you need in each:

// OGRE initialization:
#ifdef WIN32
//Necessary to tell the mouse events to go to this window
#if (_WIN32_WINNT < 0x0501)
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0501
#endif
// Necessary to get the Window Handle of the window
// OGRE created, so SDL can grab its input.
#include "windows.h"
#include "SDL_getenv.h"
#endif

// SDL initialization:
#include "SDL/SDL.h"
#include "SDL/SDL_syswm.h"
// Initialise OGRE
   char tmp[64] = "OpenFRAG Window";
   mWindow = mRoot->initialise(true, tmp);

   // Initialise SDL
#ifdef WIN32
   // Allow SDL to use the window OGRE just created

   // Old method: do not use this, because it only works
   //  when there is 1 (one) window with this name!
   // HWND hWnd = FindWindow(NULL, tmp);

   // New method: As proposed by Sinbad.
   //  This method always works.
   HWND hWnd;
   mWindow->getCustomAttribute("WINDOW", &hWnd);

   // Set the SDL_WINDOWID environment variable
   //  Please note that later SDL converts the WINDOWID-string back into
   //  an unsigned long. So make sure you save a valid id by utilizing 
   //  %u instead of %d.
   sprintf(tmp, "SDL_WINDOWID=%u", (unsigned long)hWnd);
   _putenv(tmp);

   if (!mWindow->isFullScreen())
   {
      // This is necessary to allow the window to move
      //  on WIN32 systems. Without this, the window resets
      //  to the smallest possible size after moving.
      mSDL->initialise(mWindow->getWidth(), mWindow->getHeight());
   }
   else
   {
      mSDL->initialise(0, 0);
   }
#else
   mSDL->initialise();
#endif

And in SDLEngine (mSDL in the code above)

#ifdef WIN32
void SDLEngine::initialise(int width, int height)
#else
void SDLEngine::initialise()
#endif
{
   if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE) < 0)
    {
      mLog->writeLog("Couldn't initialize SDL:\n\t\t");
      mLog->writeLine(SDL_GetError());
    }

#ifdef WIN32
   if (width && height)
   {
      // if width = 0 and height = 0, the window is fullscreen

      // This is necessary to allow the window to move
      //  on WIN32 systems. Without this, the window resets
      //  to the smallest possible size after moving.
      SDL_SetVideoMode(width, height, 0, 0); // first 0: BitPerPixel, 
                                             // second 0: flags (fullscreen/...)
                                             // neither are needed as Ogre sets these
   }

   static SDL_SysWMinfo pInfo;
   SDL_VERSION(&pInfo.version);
   SDL_GetWMInfo(&pInfo);

   // Also, SDL keeps an internal record of the window size
   //  and position. Because SDL does not own the window, it
   //  missed the WM_POSCHANGED message and has no record of
   //  either size or position. It defaults to {0, 0, 0, 0},
   //  which is then used to trap the mouse "inside the 
   //  window". We have to fake a window-move to allow SDL
   //  to catch up, after which we can safely grab input.
   RECT r;
   GetWindowRect(pInfo.window, &r);
   SetWindowPos(pInfo.window, 0, r.left, r.top, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
   RAWINPUTDEVICE Rid;
   /* we're telling the window, we want it to report raw input events from mice (needed for SDL-1.3) */
   Rid.usUsagePage = 0x01;
   Rid.usUsage = 0x02;
   Rid.dwFlags = RIDEV_INPUTSINK;
   Rid.hwndTarget = (HWND)pInfo.window;
   RegisterRawInputDevices(&Rid, 1, sizeof(Rid));
#endif

   // Grab means: lock the mouse inside our window!
   SDL_ShowCursor(SDL_DISABLE);   // SDL_ENABLE to show the mouse cursor (default)
   SDL_WM_GrabInput(SDL_GRAB_ON); // SDL_GRAB_OFF to not grab input (default)


The standard SDL DLLs do not work, you can download a set of DLLs (both Debug and Release) compiled on Microsoft Visual C++ .NET 2003. The catch is that these are compiled in "Multithreaded (Debug) DLL" mode, where the default is some other mode. In this other mode, the SDL DLL gets its own environment, which means the SDL_WINDOWID environment variable never reaches SDL. The DLLs are available here.

Some of this code comes straight from a project called Motorsport. All I really added was support for DirectX9, allowing the user to move the window and grabbing input. This does NOT work with OGREs DirectX7 plugin!

Update: It appears that the "SDL_WINDOWID" environment variable hack will only work if SDL and the OGRE application use the same runtime library flavour, i.e. they are both "Multithreaded DLL" or "Multithreaded Debug DLL". Compile the SDL source using a "Multithreaded DLL" setting, and change your OGRE app to use the same setting.

Update: If you are using VS 2005 to compile your application, you MUST recompile the SDL library with VS 2005. The DLLs you can download here are compiled with VS 2003 or another compiler and will not work with your VS 2005 application.

Update: If you are using Eihort, use "WINDOW" instead of "HWND" when calling getCustomAttribute().

Linux

On Linux, the situation is a little bit different and the above code won't work. Depending on how OGRE has been configured at compile time either SDL or GLX will be used as a "platform". With OGRE v.1.2+ GLX is selected by default, whereas earlier releases uses SDL as default. The "platform" can be chosen by using the configure directive "--with-platform=SDL|GLX".

This means that we need to detect the type of "platform". If SDL is used, everything will have already been set up. If however GLX is used, we need to do some magic. We can use the method SDL_WasInit to check whether SDL has been setup. The following code will demonstrate how (the method "parseWindowGeometry" helps with figuring out what config settings the user has selected).

/// On *NIX, OGRE can have either a SDL or an GLX backend (or "platform", it's selected at compile time by the --with-platform=[GLX|SDL] option). Ogre 1.2+ uses GLX by default. 
/// However, we use SDL for our input systems. If the SDL backend then is used, everything is already set up for us.
/// If on the other hand the GLX backend is used, we need to do some fiddling to get SDL to play nice with the GLX render system.

/// Check if SDL already has been initalized. If it has, we know that OGRE uses the SDL backend (the call to SDL_Init happens at mRoot->restoreConfig())
if(SDL_WasInit(SDL_INIT_VIDEO)==0) {
    /// SDL hasn't been initilized, we thus know that we're using the GLX platform, and need to initialize SDL ourselves
    
    /// we start by trying to figure out what kind of resolution the user has selected, and whether full screen should be used or not
    unsigned int height = 768, width = 1024;
    bool fullscreen;
    
    parseWindowGeometry(mRoot->getRenderSystem()->getConfigOptions(), width, height, fullscreen);
    
    /// initialise root, without creating a 
    mRoot->initialise(false);
    
    SDL_Init(SDL_INIT_VIDEO);
    /// set the window size
    SDL_SetVideoMode(width, height,0,0); // create an SDL window

    SDL_WM_SetCaption("YourAppName","yourappname");

    SDL_SysWMinfo info;
    SDL_VERSION(&info.version);

    SDL_GetWMInfo(&info);

    std::string dsp(&(DisplayString(info.info.x11.display)[1]));
    std::vector<Ogre::String> tokens = Ogre::StringUtil::split(dsp, ".");

    Ogre::NameValuePairList misc;
    std::string s = Ogre::StringConverter::toString((long)info.info.x11.display);
    s += ":" + tokens[1] +":";
    s += Ogre::StringConverter::toString((long)info.info.x11.window);
    misc["parentWindowHandle"] = s;
    mRenderWindow = mRoot->createRenderWindow("ogre", width, height, fullscreen, &misc);
    
    /// we need to set the window to be active by ourselves, since GLX by default sets it to false, but then activates it upon recieving some X event (which it will never recieve since we'll use SDL).
    /// see OgreGLXWindow.cpp
    mRenderWindow->setActive(true);
    mRenderWindow->setAutoUpdated(true);

} else {
    mRenderWindow = mRoot->initialise(true, "YourAppName");
}

void parseWindowGeometry(Ogre::ConfigOptionMap& config, unsigned int& width, unsigned int& height, bool& fullscreen)
{
    Ogre::ConfigOptionMap::iterator opt = config.find("Video Mode");
    if (opt != config.end()) {
        Ogre::String val = opt->second.currentValue;
        Ogre::String::size_type pos = val.find('x');
        if (pos != Ogre::String::npos) {
    
            width = Ogre::StringConverter::parseUnsignedInt(val.substr(0, pos));
            height = Ogre::StringConverter::parseUnsignedInt(val.substr(pos + 1));
        }
    }
    
    /// now on to whether we should use fullscreen
    opt = config.find("Full Screen");
    if (opt != config.end()) {
        fullscreen = (opt->second.currentValue == "Yes");
    }

}


Note that with the GLX platform, newly created windows will be disactivated. This differs from the SDL platform where newly created windows will be active by default. The reason is that the GLX window will then wait for a X event at which point they will activate themselves. With the above setup however SDL will preempt this event, resulting in a window that stays deactivated. If you use Root:startRendering() you will then have to make sure your windows really are activated.

New, Experimental Way (OGRE v1.6 and Later)

With the pre-release of OGRE v1.6, Felix Bellaby added a new, named parameter called currentGLContext (not to be confused with the other named parameter externalGLContext). Note that it is case-insensitive - like all named parameters seem to be. With this parameter set, OGRE will NOT create or setup an OpenGL context. It is left up to the programmer to set this up. OGRE will just blindly issue OpenGL commands.

This seems to be a perfect fit for SDL. Note that this method is experimental, but hopefully we can iron out the bugs after some wider usage exposes them. In this setup, we basically use SDL to create and manage the window and OpenGL rendering context (using SDL_Init and SDL_SetVideoMode). OGRE will then render to it.

I have tested this on Microsoft Windows Vista, Linux, and Apple OSX.

SDL and OGRE have clearly-defined responsibilities in this setup. There is less hackery involved here compared to previously.

First, we initialise SDL:

SDL_Init(SDL_INIT_VIDEO);

Then create the window. By passing in SDL_OPENGL, we are telling SDL to create an OpenGL context:

SDL_Surface *screen = SDL_SetVideoMode(640, 480, 0, SDL_OPENGL);

SDL is now setup. Now we setup OGRE. The first step is to create the OGRE Root object:

Root *root = new Root("plugins_cfg", "ogre.cfg", "ogre.log");

In your OGRE configuration files, make sure you are using the OpenGL renderer. This is my ogre.cfg, which tells OGRE to use OpenGL for rendering, to disable full-screen mode (feel free to remove) and that we are rendering in a 640x480 sized window:

Render System=OpenGL Rendering Subsystem
 [OpenGL Rendering Subsystem]
 Full Screen=No
 Video Mode=640 x 480

The OGRE OpenGL renderer requires the appropriate plugins to be loaded. Here is my plugins.cfg. Note that I have removed plugins I do not use here. You might not want something so minimal in your own plugins.cfg:

PluginFolder=ogre/lib
 Plugin=RenderSystem_GL.so
 Plugin=Plugin_OctreeSceneManager.so

With the Root object created, we proceed to initialise it. The 'false' we pass to initialise() tells OGREe to not auto-create a window (since we have already done this with SDL):

root->restoreConfig();
 root->initialise(false);

Nearly there! We now need to configure OGRE to blindly render to the current OpenGL context (which will be the one we have just created with SDL). To do this, we need to set some named parameters (OGRE's way of setting configuration properties).

Windows and Linux require a slightly different set of named parameters. Ideally, it would be cool if this part was portable too. But like I said, this is experimental - hopefully this will be cleaned up in future releases of OGRE!

Here's the code to setup the named parameters (named misc in the below code) for Linux and Windows (with the appropriate code under the appropriate #ifdef):

#ifdef WINDOWS
     SDL_SysWMinfo wmInfo;
     SDL_VERSION(&wmInfo.version);
     SDL_GetWMInfo(&wmInfo);
 
     size_t winHandle = reinterpret_cast<size_t>(wmInfo.window);
     size_t winGlContext = reinterpret_cast<size_t>(wmInfo.hglrc);
 
     misc["externalWindowHandle"] = StringConverter::toString(winHandle);
     misc["externalGLContext"] = StringConverter::toString(winGlContext);
 #else
     misc["currentGLContext"] = String("True");
 #endif

What we have done above is use the externalGLContext named parameter for Windows and the currentGLContext named parameter for Linux. They both do the same thing in the end - make OGRE issue OpenGL commands to the OpenGL context we have created with SDL.

I will elaborate a bit more. currentGLContext makes OGRE blindly issue OpenGL commands - it is assumed the OpenGL context has already been setup. This is ideally what we want for all platforms, but it seems the Windows OGRE OpenGL renderer does not support this. The Windows OpenGL renderer has something similar though - externalGLContext and externalWindowHandle. These named parameters require you to pass them two Windows-specific handles - namely the Windows-specific handle to the window and the Windows-specific handle to the OpenGL context. Thankfully, SDL provides us with this information!

Now that we have the named parameters setup, we pass it to the createRenderWindow() function, in the OGRE Root object. This will not actually create a render window. Instead, it will just "link" OGRE up with the window we created with SDL and make OGRE render to that:

RenderWindow *renderWindow = root->createRenderWindow("MainRenderWindow", 640, 480, false, &misc);
 renderWindow->setVisible(true);

And that's all the setup done!

To make OGRE render to your SDL window, you simply tell OGRE to render one frame and then tell SDL to swap the buffers or update the display (depending on whether you are using double buffering):

root->renderOneFrame();
 SDL_GL_SwapBuffers();

In my game, I call this at the end of every frame/update.

And that's it! We now have OGRE solely for rendering and SDL for collecting input and whatever else (i.e. audio and CD-ROM access).


Alias: Using_SDL_Input