Introduction to game programming in Silverlight
Even with an initial release less than two years ago, a thriving community of game developers write games for the Silverlight platform. Still, the Flash platform probably employs the largest game developer community, so in order to help eager Silverlight game developers enter the fray, I will convert Kongregate’s Flash game programming tutorials to Silverlight. Like the rest of my Silverlight tutorials, these tutorials will not require you to install Visual Studio. And, while informative, the Kongregate tutorials (necessarily) don’t address the more advanced concepts in game programming ( i.e. multi-threaded game loops, 3D rendering, etc). I will attempt to address these topics and more in future Silverlight game programming tutorials.
The first Kongregate tutorial hardly shows any code, choosing instead to walk the developer through setting up their development environment. I’ve covered these basics in previous Silverlight tutorials, so in this tutorial I will discuss some the capabilities and limitations of Silverlight as a gaming platform. That said, before continuing on to the next tutorial, you will want to at least skim the tutorials below:
- 10 Minute Tutorial - Silverlight: Hello World
- 10 Minute Tutorial - Silverlight: Application Framework
- 10 Minute Tutorial - Silverlight: Building a Silverlight application with MSBuild (C#)
Game Programming in Silverlight
So, with the advent of numerous native OS, multi-platform game engines and game programming references on the web, why programming games in Silverlight? Below, I list some of the reasons you might find Silverlight a compelling game platform:
- Easy access to platform resources. Silveright contains well-documented, object-oriented methods for getting input from the mouse and keyboard, drawing graphics, playing audio and video files, sending data over the network and saving data to disk. It’s literally all right there waiting for you to use it. And, to test your application, you need only hit Refresh in your browser.
- Built-in game programming concepts Back when I wrote games for Windows, during my hardcore C++ programming days (we’re talking Borland C++ 4 and Visual C++ 6, here), developers got nothing for free. Even after getting a window to display and integrating my game loop into the typical Windows message loop, I still needed to develop a decent timer class, create some sort of clipping drawing surface, implement a rudimentary animation system, etc. It was an exercise in pain. With Silverlight, you get timers and drawing canvases for free. It all comes as part of the distribution, allowing developers to prototype quickly and focus on the actual game code. Speaking of distribution…
- Near painless distribution.Writing game installers…easily the most boring part of the job, and thankfully, totally unnecessary in Silverlight. If your users already have Silverlight installed, they can jump right into playing your game. Even if they don’t, the 4MB download of Silverlight takes only minutes and it installs in seconds. Being all web-based, your game assets will download to the user on-demand, and done correctly they won’t even notice it happening.
Of course, these same reasons hold true for writing games for the Flash platform. I have written games for Flash before, and will write more, however, as of now, I prefer Silverlight for a couple of personal reasons:
- Language selection. Using the DLR, on the Silverlight platform, I could write my whole game in Python or Ruby or a combination of Python and C#. And, speaking of languages, while I have nothing against ActionScript, I still prefer the strong typing and advanced features of C#.
- Better tools for programmers. Unlike many others, I am not in love with the .NET versions of Visual Studio, however having used the Adobe tools, I like the code editing experience in Visual Studio better. As a matter of fact, for Flash development I typically use open source tools like FlashDevelop, which work better for me. However, I have not used the latest version of Adobes tools, so I may change my mind once I do.
With that out of the way, let’s dig deeper into the functionality and limitations of Silverlight as a game platform in these areas:
- Game loop
- Audio & Video
The game loop
Easily the most important part of your game (and sometimes the hardest part to get right), the game loop literally acts as the brain of the game, coordinating the flow of events between each part of the game engine. In its simplest, pseudo-code form, a game loop might look something like this:
while( gameRunning )
In this example, updateGame function takes care of moving game objects on the screen, computing AI, etc. while the renderGame function actually draws the game on the screen. While this loop works conceptually, it will not work in practice because you do not want to monopolize the UI thread in Silverlight with an infinite loop and the execution of the game would wildly fluctuate depending on speed of the computer it runs on. So, typically Silverlight game developers use one of these methods:
- A frame-based loop using the CompositionTarget.Rendering event. This event fires once every frame, similar to Flash’s onEnterFrame function. Silverlight game developers typically handle this event by updating different game objects, and then Silverlight will render those objects at the new position after the event handler returns. Note this method makes the game logic dependent on the framerate, much may be different between each users computer, thus making the game execute slower or faster depending on the computer, which is an undesirable effect.
- A timer-based loop using a DispatchTimer, Storyboard or System.Thread.Timer. Rather than tie the game speed to a potentially unpredictable frame rate, many Silverlight game developers want to update the game based on a fixed time step. Silverlight provides three options for creating a Timer:
- The DispatchTimer. As Mike Snow mentions, most developers should avoid this timer since, in addition to being low resolution, it executes on the UI thread, meaning it could block the UI thread from updating or the UI thread could prevent events from firing. This sounds very similar to the WM_TIMER event that Windows programs can receive and which all Windows game programmers universally pan.
- The StoryBoard. True to their name, StoryBoards help you animate objects in Silverlight. As noted by Mike Snow StoryBoards get their own execution thread and timer. So, many developers high-jack this timer and use it for fixed time step animations. Not the cleanest, but it works very well.
- The System.Threading.Timer. Probably the most powerful and flexible method, using a System.Threading.Timer creates a separate thread and executes a callback at a provided interval. In contrast with the StoryBoard whose completed method executes on the UI thread, the callback function of a System.Threading.Timer executes on the timer thread itself. This makes it difficult, but not impossible to update UI elements inside the game logic running in this thread. While this complexity steers many developers away, developers with the most demanding requirements should definitely give it a second look.
So, all this begs the question: which one do you use? Well, it depends on your requirements. Most developers will probably use a StoryBoard since it provides a low friction method of getting frame rate independent game updates. However, some developers may want to at least prototype their games with the CompositionTarget.Rendering event since it provides the quickest way to get up and running.
Silverlight supports 2-D graphics very well. Objects like Points, Rectangles, Images (JPG and PNG) come readily defined. Functionality like hit testing, 2-D primitive drawing and transforms already exist, ready to be used. Silverlight can even go full screen, so you games don’t have to execute within the confines of a little canvas on a web page.
All that sounds great, but now for the bad news: unfortunately, Silverlight does not support accelerated 3-D rendering. But, as you may have guessed, some enterprising developers with more spare time than me, have already developed 3-D libraries for Silverlight. I’ve listed two of them below:
Audio & Video
The System.Windows.Controls.MediaElement class provides support for playing audio and video. In terms of audio, of course Silverlight supports all of Microsoft’s own audio formats as well as the MP3 format. However, you do not have direct access to the sound device, and thus, can not mix dynamic sounds on the fly. Still, preloading MP3s and playing them when needed should work for most games.
Video has a similar story with all of Microsoft’s own video formats supported out of the box, but lacking the ability to apply any real video filters to them. For completeness, I should also mention that Silverlight provides excellent support for streaming both audio and video.
For input, Silverlight will send you both key press events and mouse move and click events. Silverlight also allows you to “capture” the mouse or keyboard, giving one element singular focus to all events. I demonstrate this in my Silverlight mouse events tutorial.
Silverlight provides developers with something called Isolated Storage. Basically, Silverlight allows an application to request from the user a certain quota of space, and at the consent of the user, that application and only that application can use that requested space. This gives game developers a place to store save games and possibly make certain game assets available off-line. I have a links to working with Isolated Storage on my Silverlight Portal page
With a focus on enabling rich Internet applications, of course, Silverlight allows developers to leverage Windows Communication Foundation to call Web Services and REST APIs. However, thankfully, with a few caveats, Microsoft also allows Silverlight applications to create raw socket connections through the System.Net.Sockets namespace. This opens up a whole new realm of possibilities for playing multi-player games in the browser.
While not being the perfect gaming platform, Silverlight does give developers plenty of functionality to create compelling browser-based games. Over the course of the next few months, I will write several Silverlight game programming tutorials, starting with converting Kongregate’s Flash tutorials, that will hopefully give you a solid base for developing games in Silverlight.