In this tutorial you will learn how to initialize Mogre from scratch. By the end of the tutorial you will will know the steps requied and objects involved in itializing Mogre/Ogre before entering the rendering loop. |
If you find any errors in this tutorial please send a private message to amirabiri.
Prerequisites
- This tutorial assumes you have knowledge of C# programming and are able to setup and compile a Mogre application.
- This tutorial also assumes that you have created a project using the Mogre Wiki Tutorial Framework.
- This tutorial builds on the previous tutorials, and it assumes you have already worked through them.
Table of contents
Getting Started
In previous tutorials we used the Tutorial Framework's base class to base our code on. In this tutorial we will be creating things from scratch. However, we'll still use the tutorial framework pre-made projects because they give us a simple starting point in terms of project set up, directory structure, resources, DLLs configuration and so on. This tutorial does not cover manually setting up a Mogre project in terms of files, folders, etc. There is some discussion of that in the First Tutorial, and we will soon also dedicate a more detailed section for it as well. This tutorial instead focuses on the code needed and the objects involved in bootstrapping Mogre/Ogre and rendering a scene.
Replace the code in your tutorial.cs or tutorial.vb file with the following:
class Tutorial { public static void Main() { } }
As you can see, this is just an empty application. Be sure you can compile this code before continuing. The code will do nothing at all - it will exit immediately after it's run. This is OK - after having walked through this tutorial, we will arrive at a full featured Mogre application.
Overview of The Mogre Startup Process
Once you understand what's going on under the hood, getting Mogre/Ogre running is actually very easy to do. The tutorials framework might look daunting at first since it tries to do a lot of things that may or may not be needed for your application. After finishing this tutorial, you will be able to pick and choose what exactly is needed for your application. Before we dive into this, we'll first take a quick look at how the startup process works at a high level.
The basic Mogre/Ogre life cycle looks like this:
- Create the Root object.
- Define the resources that the application will use.
- Choose and set up the render system (that is, DirectX, OpenGL, etc).
- Create the render window (the window which Ogre will render onto).
- Initialize the resources that you are going to use.
- Create a scene using those resources.
- Set up any third party libraries and plugins.
- Create frame listeners.
- Start the render loop.
We will be going through each one of these in-depth in this tutorial.
Note that while you really should do steps 1-4 in order, steps 5 and 6 (initializing resources and creating the scene) can come much later in your startup process if you like. You could initialize third party plugins and create frame listeners before steps 5 and 6 if you so choose, but you really shouldn't do them before finishing step 4. Also, the frame listeners/third party libraries cannot access any game related resources (such as your cameras, entities, etc) until the resources are initialized and the scene has been created.
In short, you can do some of these steps out of order if you feel it will be better for your application, but we do not recommend doing so unless you are sure you understand the consequences of what you are doing.
Creating the Root Object
The Root object is the core of the Mogre/Ogre library, and must be created before you can do almost anything with the engine.
Add a member variable to your Tutorial class to hold a global reference to the Root object:
protected static Root mRoot;
Now add the following code to your application that creates a Root object:
protected static void CreateRoot() { mRoot = new Root(); }
And finally add a call to the new CreateRoot method from Main:
public static void Main() { CreateRoot(); }
The Root constructor can accept 3 optional parameters:
parameter | default value | description |
pluginFileName | "plugins.cfg" | the name and location of the plugins config file |
configFileName | "ogre.cfg" | the name and location of the ogre config file (which tells ogre things like the Video card, visual settings, etc) |
logFileName | "Ogre.log" | name and location of the log file that Ogre will write log messages to |
We can leave these at their default values.
Go ahead and compile and run your application. It still looks like it does nothing, but if you open 'Ogre.log' you'll see that Ogre was fired up, initialised and then shut down. You should also see that it parsed and installed the Ogre plugins listed in 'plugins.cfg'.
The tutorials project zip files contain identical 'plugin.cfg' files in both the Debug and Release bin folders. A typical plugins configuration file might look like this:
# Define plugin folder PluginFolder=. # Load these plugins Plugin=RenderSystem_Direct3D9 Plugin=RenderSystem_GL Plugin=Plugin_OctreeSceneManager
This means that Mogre/Ogre will attempt to load RenderSystem_Direct3D9.dll, RenderSystem_GL.dll and Plugin_OctreeSceneManager.dll and it will expect to find them in the working directory.
You can also load plugins from code instead of using a configuration file. Here is an example of how you could do so (don't add this code):
mRoot = new Root(""); mRoot.LoadPlugin("RenderSystem_Direct3D9"); mRoot.LoadPlugin("RenderSystem_GL"); mRoot.LoadPlugin("Plugin_OctreeSceneManager");
By passing an empty string as the plugins configuration filename parameter to the Root constructor we prevent Ogre from looking for any plugins configuration file. Then we load the plugins we are interested in programatically. This might be useful if you want to load plugins based on some internal logic more complicated than what a simple configuration file provides.
Defining Resources
The next thing we have to do is define the resources that the application uses. This includes the textures, models, scripts, and so on. We will not be going over all there is to know about resources in this tutorial. For now, just keep in mind that you must first define all the resources that you might use during the application, then you must initialize the specific resources you need before Ogre can use them. In this step we are defining all resources that our application will possibly use.
The resource config file is handled slightly differently than the plugins one. Mogre/Ogre doesn't take care of it automatically for us. Instead they supply us with a simple way of parsing the file, but we then have to iterate over the result and perform calls to the ResourceGroupManager object ourselves. The reason for this is that Mogre/Ogre doesn't make any assumptions about how you might want to organize your resources. You could store the config in your own XML format for example. The basic resource config is just a simple starting point that Mogre/Ogre provides you with.
Adding a resource location is done with a simple call to the ResourceGroupManager class:
ResourceGroupManager.Singleton.AddResourceLocation(location, type, group);
The first parameter of this method is the location of the resource on disk (file/directory name). The second parameter is the type of resource which is generally either "FileSystem" (for a directory) or "Zip" (for a zip file). The last paramter is the resource group to add the resource to.
A typical Ogre resource configuration file might look like this:
[Bootstrap] Zip = Media/packs/OgreCore.zip [General] FileSystem = Media FileSystem = Media/fonts FileSystem = Media/materials/programs FileSystem = Media/materials/scripts FileSystem = Media/materials/textures FileSystem = Media/models Zip = Media/packs/cubemap.zip Zip = Media/packs/skybox.zip
In this example there are two resource groups: "Bootstrap" and "General". The left-hand side of each line (before the "=" sign) is the type of the resource, and the part after the equals sign is the location. You might have wondered where the models we've used in the tutorials come from and how they are loaded? Well the tutorial pre-made projects contain a Media folder with all the resources used in the tutorials. They also contain a resources.cfg file similar to the one above which the tutorials framework parses and loads for us.
We can easily parse a resources configuration file given in Ogre's default format above by using the ConfigFile class. Add the following code to your application:
protected static void DefineResources() { ConfigFile cf = new ConfigFile(); cf.Load("resources.cfg", "\t:=", true); var section = cf.GetSectionIterator(); while (section.MoveNext()) { foreach (var line in section.Current) { ResourceGroupManager.Singleton.AddResourceLocation( line.Value, line.Key, section.CurrentKey); } } }
And add a call to DefineResources from to your Main method:
public static void Main() { CreateRoot(); DefineResources(); }
If you compile and run the application now, you should see in the .log file that Ogre created the resource groups and added the resource locations, but not parsed the resources yet.
Creating a Render System
Next we need to choose the RenderSystem (usually either DirectX or OpenGL on a Windows machine) and then configure it. Ogre offers a configuration dialog to set the graphics settings for your application. You can trigger it in Mogre with a simple call:
mRoot.ShowConfigDialog();
The ShowConfigDialog method returns false if the user pressed the cancel button, which implies that they want to exit the program rather than continue. So let's respect this choice by throwing an OperationCanceledException to stop the start up process if ShowConfigDialog returned false. Add the following code to your application:
protected static void CreateRenderSystem() { if (!mRoot.ShowConfigDialog()) throw new OperationCanceledException(); }
We need to call CreateRenderSystem from our Main, but we also want to gracefully exit the application if the user clicks the cancel button. So let's wrap our Main method in an appropriate try/catch block. Modify your Main method as follows:
public static void Main() { try { CreateRoot(); DefineResources(); CreateRenderSystem(); } catch (OperationCanceledException) { } }
This code will allow other exception types to propagate so we can see them. No other part of Mogre will throw an OperationCanceledException exception so we can safely assume it's ours.
An additional advantage of the config dialog is that it saves the last choice of the user (assuming they press the "OK" button) in a file called 'ogre.cfg'. This file is then read again each time the configuration dialog pops up, so in effect it "remembers" the user's choices between invocations of the application. You have probably already noticed this as you went through the previous tutorials.
Eventhough the config dialog is a powerful tool, we may still want to choose or configure the render system ourselves. We can do this easily. Here is an example (don't add this code):
RenderSystem renderSystem = mRoot.GetRenderSystemByName("Direct3D9 Rendering Subsystem"); renderSystem.SetConfigOption("Full Screen", "No"); renderSystem.SetConfigOption("Video Mode", "800 x 600 @ 32-bit colour"); mRoot.RenderSystem = renderSystem;
You can use the Root's GetAvailableRenderers method to find out which render systems are available for your application to use. Once you have retrieved a RenderSystem object, you can use its GetConfigOptions method to see what options are available for the user. By combining these two methods, you can create your own configuration dialog for your application.
Creating a Render Window
Now that we have chosen the RenderSystem, we need a window to render Mogre/Ogre in. There are actually a lot of options for how to do this, but we will really only cover a couple.
The simplest option is to let Mogre/Ogre create a render window for you. This is very easy to do.
We need to keep a reference to the RenderWindow object since we'll use it later. So let's add an appropriate member variable to the Tutorial class. Add the following code after your Root member variable:
protected static Root mRoot; protected static RenderWindow mRenderWindow;
Add the following code to your application to create the render window:
protected static void CreateRenderWindow() { mRenderWindow = mRoot.Initialise(true, "Main Ogre Window"); }
And finally, we need to add a call to CreateRenderWindow from our Main method:
public static void Main() { try { CreateRoot(); DefineResources(); CreateRenderSystem(); CreateRenderWindow(); } catch (OperationCanceledException) { } }
The Initialise method of the Root object initializes the RenderSystem we set in the previous section. The first parameter is whether or not Ogre should create a render window for you. If it is set to true, the method will return a RenderWindow object.
Alternatively, we could have created a window ourselves which we then want to tell Mogre to use. Here is a quick example of how this might be done using Windows.Forms (don't add this code):
mRoot.Initialise(false, "Main Ogre Window"); var win = new System.Windows.Forms.Form(); NameValuePairList misc = new NameValuePairList(); misc["externalWindowHandle"] = win.Handle.ToString(); mRenderWindow = mRoot.CreateRenderWindow("Main RenderWindow", 800, 600, false, misc);
Note that you still have to call Initialise, but the first parameter is set to false. Then you must get the handle of the window you want to render in. Acquiring this will depend on the GUI toolkit that you use. Once you have this handle, you place it in the "externalWindowHandle" key of a NameValuePairList object, and you pass that object to CreateRenderWindow. Ogre then creates a RenderWindow object based on your window and returns it to you.
This also illustrates an important distinction: RenderWindows are not the same thing as the window objects of GUI toolkits. RenderWindow objects are simple Ogre objects that contain a reference to an actual window. The RenderWindow does not implement any windowing functionality by itself.
Initializing Resources
Now that we have our Root, RenderSystem and RenderWindow objects created and ready to go, we are very close to being ready to create our scene.
The only thing left to do is to initialize the resources we are about to use. In a very large game or application, we may have hundreds or even thousands of resources that our game uses - everything from meshes to textures to scripts. At any given time though, we probably will only be using a small subset of these resources. To keep down memory requirements, we can load only the resources that our application is using. We do this by dividing the resources into sections and only initializing them as we go. We will not be covering that in this tutorial, however. See Resources and ResourceManagers for a full tutorial devoted to resources. Note that when you initialize a resource group, it parses and loads scripts, but does not actually load the resources (such as models and textures) into memory until the program actually needs to use it.
Before we initialize the resources, we should also set the default number of mipmaps that textures use. We must set that before we initialize the resources for it to have any effect.
Add the following code to your application:
protected static void InitializeResources() { TextureManager.Singleton.DefaultNumMipmaps = 5; ResourceGroupManager.Singleton.InitialiseAllResourceGroups(); }
And add a call to InitializeResources from Main:
public static void Main() { try { CreateRoot(); DefineResources(); CreateRenderSystem(); CreateRenderWindow(); InitializeResources(); } catch (OperationCanceledException) { } }
The application now has all resource groups initialized and ready to be used.
Creating a Scene
Next we will create the scene. There are 3 things that must happen before you start adding things to a scene:
- Creating the SceneManager.
- Creating a Camera.
- Creating a Viewport.
Add the following code to your application:
protected static void CreateScene() { SceneManager sceneMgr = mRoot.CreateSceneManager(SceneType.ST_GENERIC); Camera camera = sceneMgr.CreateCamera("Camera"); camera.Position = new Vector3(0, 0, 150); camera.LookAt(Vector3.ZERO); mRenderWindow.AddViewport(camera); }
And add a call to CreateScene from Main:
public static void Main() { try { CreateRoot(); DefineResources(); CreateRenderSystem(); CreateRenderWindow(); InitializeResources(); CreateScene(); } catch (OperationCanceledException) { } }
Let's add something to our scene, now that we've taken care of the basics. Add the following code to your CreateScene method:
Entity ogreHead = sceneMgr.CreateEntity("Head", "ogrehead.mesh"); SceneNode headNode = sceneMgr.RootSceneNode.CreateChildSceneNode(); headNode.AttachObject(ogreHead); sceneMgr.AmbientLight = new ColourValue(0.5f, 0.5f, 0.5f); Light l = sceneMgr.CreateLight("MainLight"); l.Position = new Vector3(20, 80, 50);
Creating Frame Listeners
Before we can kick off the main render loop, we should register a frame listener to implement the main logic of the application. For this demonstration we will simply show the scene and exit the application after 5 seconds.
Add a simple float member variable to your Tutorial class to act as a timer:
protected static Root mRoot; protected static RenderWindow mRenderWindow; protected static float mTimer = 5;
Add the following code to your application to register a simple frame listener that exits after 5 seconds:
protected static void CreateFrameListeners() { mRoot.FrameRenderingQueued += new FrameListener.FrameRenderingQueuedHandler(OnFrameRenderingQueued); } static bool OnFrameRenderingQueued(FrameEvent evt) { mTimer -= evt.timeSinceLastFrame; return (mTimer > 0); }
And finally, add a call to CreateFrameListeners from Main:
public static void Main() { try { CreateRoot(); DefineResources(); CreateRenderSystem(); CreateRenderWindow(); InitializeResources(); CreateScene(); CreateFrameListeners(); } catch (OperationCanceledException) { } }
The Render Loop
We are now ready to enter the main render loop and render our scene. There are several ways to implement a render loop. But the simplest option is to use Ogre's built-in one. Remember that Ogre's default render loop calls all the frame listeners at the appropriate time and exits if any of them returns false.
Add the following code to your application:
protected static void EnterRenderLoop() { mRoot.StartRendering(); }
And add a call to EnterRenderLoop at the end of Main:
public static void Main() { try { CreateRoot(); DefineResources(); CreateRenderSystem(); CreateRenderWindow(); InitializeResources(); CreateScene(); CreateFrameListeners(); EnterRenderLoop(); } catch (OperationCanceledException) { } }
Alternatively, we could implement our own rendering loop using the Root's RenderOneFrame method. If we do that we have to take care of exiting the loop ourselves. Here is an example (don't add this code):
while (mRoot.RenderOneFrame()) { // Do other stuff here... }
This gives you more control over the render loop and allows you to perform other incremental actions not dependant on frame listeners.
Compile and run the application. You should see the Ogre face staring at you for about 5 seconds before the application terminates on its own.
Conclusion
In this tutorial we have gone over the basics of getting Mogre/Ogre started from scratch. By this point you should be able to write your own Mogre application which no longer uses the Mogre tutorials framework (we will be continuing to use in following tutorials however). You should now understand exactly the steps required and the objects involved to get to a rendered scene from scratch.
In the next tutorial we will learn how to to create an in-game GUI system.
Proceed to Mogre Tutorial - Embedding Mogre in Windows.Forms In-Game GUI