The WordPress.com stats helper monkeys prepared a 2013 annual report for this blog.

Here’s an excerpt:

The concert hall at the Sydney Opera House holds 2,700 people. This blog was viewed about 31,000 times in 2013. If it were a concert at Sydney Opera House, it would take about 11 sold-out performances for that many people to see it.

I m moving the blog over to github, the transition involves more steps than I would like, but still I think it will be worth it. If you want to see how it’s going check here, this blog at roundcrisis.wordpress.com will stay live until the transition is complete. IF you are looking for the new rss feed this is it.

What happens if instead of using synchronization with reset events, we use one of the new concurrent collections? Lets find out.

Implementation with Concurrent Queue

So, while I was trying to implement the double buffer (previous post available here) I started thinking about perhaps a simpler implementation with one of the concurrent collections, so I tried with a ConcurrentQueue<T>.

The idea behind it is pretty simple. Instead of having the two collections of RenderCommand we have a ConcurrentQueue<RenderCommand[]> so we think of each of the elements of the queue as a frame, ready to be rendered.

As before, we are starting off with the primitives3DWindows sample. A bit obvious, but, we’ll need to initialize the queue on the constructor of the Renderer class(I just thought I’d mention that).

From the world We’ll add all necessary cubes to a renderCommand, using the AddCube() method. At the end, we’ll need to add that collection to the queue by calling EndFrame(). Like this

These methods are public because they are called from World, however, as you can see from the sequence diagram below we check if the renderer CanAcceptCommands(), the reason for this is that we don’t regulate how often we run world.Update() and in reality we only want to have one frame (or RenderCommand collection ready to render) when we call Draw so that there is no latency.

With the update done, we now need to render. At this point this is pretty trivial. Code below

I think what is happening here is pretty self explanatory, but I will do it anyway. If we call Draw() and we TryDequeue and we can’t we call return, there is no point in trying to Draw and empty array of RenderCommands (I believe that would be the result). Alternatively if we successfully dequeue, we will let the CubePrimitive draw each of the commands.

Analysis

It seems to me that this implementation is easier to follow and implement that the previous one, however I took some performance data and this is the result:

Double buffer:

ConcurrentQueue:

Green means execution time, and red means synchronization time.

I think what these graphs tell is that double buffer is more efficient because concurrentqueue uses spin waits to synchronize, so it shows up in the thread analysis as execution time, where the previous double buffer implementation shows up as synchronization time, meaning the threads are just asleep.

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.

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:

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 :D. 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.

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.

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.

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

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.

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.

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.