A game running at 60FPS needs to render every 16 milliseconds, meaning that all the logic for collision detection, animation, obstacle avoidance, physics, etc. must happen in that very short time. You also need to prepare for rendering and then send the instructions to the GPU. Multithreading seems like a most reasonable option if you have more than one core available (and who doesn’t these days).
One of the ways to do multithreading rendering in games is using a double buffer. At a high level the concept is simple: given two threads update and render, use one to fill a buffer with commands that have enough info to render(we’ll call them RenderCommands), once completed switch buffers while the other thread renders the RenderCommands in the original buffer.
Graph and possibly a better explanation of double buffer from http://bit.ly/110JuB3
You might be wondering what is a render command, well it’s the smallest amount of information we need to send to the GPU so that it can render what we want it to render. A Render command for a cube only engine (ie our engine can only draw cubes) can be as simple as:
public class RenderCommand
{
public float Radius { get; set; }
public Color Color { get; set; }
public Matrix World { get; set; }
}
There are many ways to implement this double buffer technique. The implementation we are going to see in this example is based on Quake 3 source code using modern C# to implement it. Questions, comments and optimizations welcome
. By the way, a really in-depth review of the code is available here.
The idea
The update thread is the red one and the render thread is the blue one.
The diagram above describes the flow of the update thread(red) and rendering thread(blue), the hatched squares represent blocking.
At the initial stage, the render thread will be waiting for the render commands to become available, it will be signalled from the update thread. Once that happens, the render thread will swap the buffers, signal to the update thread that the commands have swapped and that the render thread is ready to start drawing and start drawing.
This signalling process works well also for the situation when the update frame takes longer to update and the render thread needs to wait for the render commands to become available.
Finally the situation where rendering takes longer is also covered, as we see in the the update thread is waiting until rendering is finished
The implementation
For the purposes of this example we will be using XNA. To have something to show and compare against, I’m starting off with the 3d primitives sample from XNA Creators code club.
I am going to skip the details about how to draw vertices, there are many other blog posts that cover that and focus on the threading and concurrency issues.
So, for a start we need to create the update thread. To that effect we will instantiate a class called UpdateLoop in a Task that will simply loop on executing Update as follows.
Task.Factory.StartNew(() =>
{
var gl = new UpdateLoop(_renderer);
gl.Loop();
});
The loop in UpdateLoop: (Note: the loop is not time stepped, ie you should not use a while(true) like this in production).
public void Loop()
{
_stopwatch.Start();
while (true)
{
Update();
}
}
The code for the loop is (i think) pretty self explanatory, when calling Update in line 5 it will follow the sequence as described in diagram below.
It is probably interesting to see what AddCube() looks like :
public void AddCube(Cube primitive)
{
var translation = Matrix.CreateFromYawPitchRoll(
primitive.Rotation.X,
primitive.Rotation.Y,
primitive.Rotation.Z) *
Matrix.CreateTranslation(primitive.Position);
_updatingRenderCommands.Add(
new RenderCommand
{
Color = primitive.Color,
Radius = primitive.Radius,
World = translation
});
}
As you can see from the sequence diagram, after looping on renderer.AddCube() there is a call to renderer.EndFrame(), here is where we need to signal that the render commands are ready and the update thread will be now waiting for the render buffers to be swapped.
public void EndFrame()
{
_renderCompleted.WaitOne();
_renderComandsReady.Set();
_renderActive.WaitOne();
}
From the render thread point of view, this is what the sequence diagram looks like:
In my game class (the main class that inherits from XNA’s game class) , in Draw(), we call _renderer.Draw():
public void Draw(GraphicsDevice device, Matrix view, Matrix projection)
{
_renderActive.Reset();
_renderCompleted.Set();
_renderComandsReady.WaitOne();
_renderCompleted.Reset();
_renderComandsReady.Reset();
SwapBuffers();
_renderActive.Set();
_cubePrimitive = _cubePrimitive ?? new CubePrimitive(device);
foreach (var renderingRenderCommand in _renderingRenderCommands)
{
_cubePrimitive.Draw(renderingRenderCommand.World,
view,
projection,
renderingRenderCommand.Color
);
}
}
This is probably the most complex method in the whole example. The _renderActive is reset because at this point we want the update thread to block when on wait, this was set to wait from _renderer.EndFrame(). We set _renderCompleted here to unblock the update thread and then we wait for _renderCommandsReady to be signalled, effectively putting the renderer to sleep until there are more commands to render.
Before calling SwapBuffers() _renderCompleted is reset so that if the update thread reaches the end of a frame, it will sleep until the render thread has finished swapping the buffers.
Immediately after, a call to reset _renderCommandsReady ensures that the render thread will go to sleep on the next Draw call until there are some commands to render.
I am not terribly sure the explanation above is clearer than the actual code to be honest, but after 4 6 attempts I’m giving up.
private void SwapBuffers()
{
if (_updatingRenderCommands == _bufferedRenderCommandsA)
{
_updatingRenderCommands = _bufferedRenderCommandsB;
_renderingRenderCommands = _bufferedRenderCommandsA;
}
else if (_updatingRenderCommands == _bufferedRenderCommandsB)
{
_updatingRenderCommands = _bufferedRenderCommandsA;
_renderingRenderCommands = _bufferedRenderCommandsB;
}
_updatingRenderCommands.Clear();
}
Finally SwapBuffers(). There’s no synchronization happening here so, we are just switching buffers. Before calling this method the _renderComandsReady was blocked
And that is pretty much all, the complete sample is available from github .
References and interesting related articles
Most excellent Quake 3 code review http://fabiensanglard.net/quake3/index.php
Threading your game loop http://www.altdevblogaday.com/2011/07/03/threading-and-your-game-loop/
For the craic http://en.wikipedia.org/wiki/Multiple_buffering
Filed under: .net, gamedev, mono | 2 Comments
Tags: game engines, gamedev
The dying platform: .Net
For the last few years I have been writing code in C#. I think C# and .net are great tools to write software. I find that C# is exactly where I need it to be, I can do low level when I need to work with pretty high level abstraction (ish). However the world (unfortunately) doesn’t do what I want and it feels like the momentum .net had is certainty fading.
These are some reasons why I think this is happening (not all related directly to programing)
- Inherent hatred for Microsoft and anything it does, even if it is good. I think is pretty sad since I see this attitude from people that should be objective from a technical standpoint, licensing can’t always be an issue.
- Windows 8 and WinRT with it’s confusing .net support. It doesn’t help when it comes to .net developers either. It seems like their intention was to bring in the “cool kids(?)” but with that they alienated the people that supported them.
- All the windows phones, and particularly the WP7 fail (no update path for win 8). It is fail from a commercial standpoint and from developer support, how can you spend any significant amount of time with a platform that you don’t know is going to be there in a year or if there is any support for it.
- Half arsed open sourcing, by this I mean, you can read the code but no thanks, we don’t take pull requests
.Also, the very common not invented here that MS keeps doing (Monorail vs MVC, Nunit vs MStest, NHibernate vs EF, and many others ). - Tablets and the fact that MS doesn’t have a significant share on any of this, so for many the digital experience is via apple or android.
- For me, killing XNA. A great SDK, suddenly abandoned. Why? no one ever gave a reason I can remember (can you?)
- XBOX vnext rumoured online only putting a nail on the XBOX coffin.
What could save it (maybe)
- Strangely, Xamarin because of their amazing mobile tools based on mono . Unity helps too, but I do wonder about what they have in mind for the future
- Aliens?
Filed under: .net | 22 Comments
Tags: .net, android, xamarin
Mono for android or Xamarin.Android little tips:
- If you turn on GPU emulation, sometimes GPU emulation doesn’t actually start, it downgrades to software rendering, this makes the emulator slower and it doesn’t actually uses OpenGL(if you are using monogame, this means your game would probably not work).
- If you are looking for a grid like component that stretches with a fix number of grids, I couldn’t find one. Had to write my own and the code is ugly
. - You can use ScreenOrientation = ScreenOrientation.Portrait as an attribute in your activity and ConfigurationChanges = ConfigChanges.Orientation is also an activity attribute that prevents the activity from restarting when orientation changes.
Xamarin just announced support for C# 5 features in the mobiles suites, very exciting news… more details here.
Tomorrow, post about monogame stuff.
Filed under: mobile dev, mono for android, UI | 2 Comments
Tags: mono for android, xamarin for android
I did a few presentations about Monogame in Gaming Reimagined (at what used to
be the Landsdowne Road Stadium) and in Games Fleadh, if you were there I would really appreciate your feedback (good and bad, please just leave a comment here).
The slides are available here. I will make the code available soon and update this post. There is a video for it here
During both events there was some pretty cool talks. About both the industry and making games.
During Games Fleadh I Particularly enjoyed listening to Steve Ewart from Havok showcase his many cool demos and the guys from DemonWare talk about their experiences in their company and it some of the big games studios.
Kudos to the organizers of both events and Congratulations to all the award winners of Games Fleadh awards: bitsmith got Best Games and an awesome tank.

Pic from Bryan Duggan (https://www.facebook.com/media/set/?set=a.423888310976750.1073741831.113468182018766&type=1)
Filed under: talk | Leave a Comment
Tags: games fleadh, gaming reimagined, monogame, presentation
A few weeks ago I bit the bullet and bought Mono for Android. I also decided to update to all devices to Ice Cream Sandwich as the UI is just so much better. Should have done that ages ago, but I was just afraid Kies would brick my phone again.
Anyway, the new features that I m sure anyone interested in android development already know about: Services, fragments, new UI. Cool stuff, it also meant a lot to learn
.
Some things that you might want to try out if you are starting this out:
- Preferably have a device or two
, the emulator is slow. The x86 emulator is an interesting option, it didn’t work for me initially but then I tried a few different virtual devices and then you could really see the benefits… way faster. Still is good to deploy to the phone often enough. - Since android 3.0 there is a new way to do drag drop that works as a state machine. More info in the excellent Jeremie Laval’s blog. Check the other posts, they are really cool too.
- Fragments are trickier to deal with that I thought. Pretty sure I’m doing something wrong (as all times you start learning something new) but I wanted to replace a fragment (with UI elements on it) with another fragment (also with UI elements on it) however if the first fragment was placed there with the layout xml and the second one programmatically, It just didn’t work. It did work when both where placed programmatically. Any hints on this would be great.
- To use the Holo Theme across your app, simply add this snipet to your manifest to your manifest. More on styles here.
One to check out… there is an android unit test suite Andr.unit (github repo)a unit testing framework for android based on Touch.Unit.
Filed under: android, c#, mono for android | 1 Comment
Tags: emulator on x86, Ice Cream sandwich, mono for android, xamarin for andoird
A build system for games
As you might or might not know, I am one of the founders of BatCat Games, the important word about that sentence is games. The fact that we make games put a series of differences into our production that doesn’t generally affect non game software development cycles.
For a start art and animation are key in a game, so are visual effects. In build server terms, that generally means two things: It requires space(for content building) and quite probably a graphics card (for the visual effects). Our ideal solution would be to have a virtual machine per supported platform , but we found that none of the virtualization software (VirtualBox, VMWare, etc) virtualizes the graphics card reliably (if you found a way, please let me know) so we are running our server on a non virtual machine.
The objective is to build the whole game, tools, etc. at each commit. There are a series of tools available in the market at the moment that allows you to do just that. For example: TeamCity, Jenkins, CruiseControl, Hudson.. etc. There is a good comparison matrix here.
We chose TeamCity, mostly because we know it, we find it easy to use and it is free.
Our setup
Our code is based around XNA and monoGame (recently on version 3).
We have many projects: a game and engine project, a tool, a library and the content builder. This means we have a diverse project output. For example, in the case of the content, we are not interested in the actual build results (yet) however we are interested in knowing that it did build, and to report errors if it didn’t.
The game and engine project reside in one solution and have many unit tests. We need the build server to not only build the project and after that run the unit and integration tests. Initially I set this up using psake (a tool that does the build with PowerShell) this is a great solution if you want to have a one click build, so I gave it a try, I found that setting up the tests assemblies was a manual process and that to get psake to talk to TeamCity nicely it would take more time that I had. So I tried running the build directly from TeamCity, and it was easier and I didn’t loose to much flexibility so, I had to go for that solution (however is a decision I will revisit shortly).
Setting up each of the steps took me approximately 10~20 minutes if done this way. There are a few things that I want to improve on, however the end result is that in a very short time I can have a new project building and reporting.
Some of the disadvantages of the process as it is are:
- If I want to change the build type I need to do it manually, in this case, the target test assemblies will need to be updated
- At the moment we are using dropbox as our way to distribute the builds, it is a process some members of our team really like because they just get the new binaries and they can choose when to update (so that there is no friction). I would prefer if the tools would just auto-update, but this is working for the moment.
Summary
As you can see the server setup is not perfect, there is loads to improve on, but setting this up from early on has proven very helpful. It allows us to have a one click build and a functional way to deliver our tools and product to the people in our team.
Note: This post was cross posted to gamasutra, Thanks to Kris for her help.
Filed under: c#, gamedev, Uncategorized, unit-testing, xna | Leave a Comment
Tags: build server, gamedev, monogame, teamcity, xna

taller, install. It will install all prerequisites for you on your machine. Allegedly this failed the first time but worked the second time, I had a log to look at to give me some idea of the problem.