Archive for 'XNA'
A useful code snippit
cubed2D
November 10th, 2007.
Whenever i start a new codefile, alot of the time i find myself haveing to add all the xna refrences at the top, so i realised this would make an exilent snippit
save the following xml as UsingXNA.snippet
- <CodeSnippets xmlns=”http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet“>
- <CodeSnippet Format=”1.0.0“>
- <Header>
 <Title>XNA Using statments</Title>
 <Author>NekoCake Industries</Author>
 <Description>Inserts all the using statments needed for good xna useage</Description>
 <HelpUrl>www.nekocake.com</HelpUrl>
- <SnippetTypes>
 <SnippetType>Expansion</SnippetType>
 </SnippetTypes>
 <Shortcut>UsingXNA</Shortcut>
 </Header>
- <Snippet>
- <Code Language=”CSharp“>
<![CDATA[
#region Using Statements using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Storage; #endregion
 ]]>
 </Code>
 </Snippet>
 </CodeSnippet>
 </CodeSnippets>
Then start up GSE, click tools -> code snippet manager -> add then find where you saved the xml, and load it in. whenever you need the xna refences, just type UsingXNA and press tab twice when intelesence picks it up!
Im still alive
cubed2D
November 06th, 2007.
Still alive, still makeing progress! i started a rewite on Crimson Engine last month. Wanted to reimplement my object system and other things i thought wernt flexible enough. Just finished re implementing animated sprites last night, so its high time for an ‘im still alive’ post. I plan to write up some new tutorials and engine design posts over the next few weeks, and clean up the site abit!
The current state of crimson
cubed2D
July 23rd, 2007.
Two months ago i last posted about my progress with my game engine, Crimson. Things have changed since then. As I’ve previously mentioned, not done much coding has been done on the engine since because of real life and hardware problems (t minus 10 days till laptop returns!). Because of that, most of the progress has been in design. Here is what my class layout looked like back at that last update (all these classes were coded up when i posted this originally)
Well, as you can see, I’ve crossed off everything that doesn’t exist in my current design. That’s not to say this old functionality is being removed, just that its being moved around and redesigned to be a lot more powerful that it ever was before. I’m also trying to decouple the game simulation from the world view, a trick that i learned from reading Game Coding Complete by Mike McShaffry. (This is a great book not only on the technical side of game development, but also things like how to manage the project, testing, folder layout…. the sheer amount of information in this book is mind-blowing! My personal favorite thing about it is the little ‘tales from the pixel mines’ inserts, where Mike shares stories for the development on games he did at origin (Ultima!) and Microsoft. You can learn so much from reading about the choices and problems in these sections! Do yourself a favor, and get this book)
 So, “how does it look now!?!” i hear you shout, well like this.
Each icon represents a different core area of the engine. Authority is the game rules, its where the simulation takes place. This will include a physics engine, the information on the current level, the data structures containing all the current entities in the world and things like that. You could almost think of it as a server (infact, this architecture is very good for extending your game to be multi-player). It also contains the command interpreter, which is very important! (shall all become clear soon)
The view is not a single piece of code like the authority, There is actually loads of em. Im implementing a base view which can be extended for more specialized purposes. They are basically filters on the game state(held in the authority). The most obvious example on one would be the player view. It has all the code in it for drawing the world to the screen, converting button presses in to commands, making music play and stuff like that. You could also make one to command a team of A.I players. It wouldn’t need any drawing code, but it would need to be able to sense whats happening in the area of world-space it can see (filtering everything it cant out)and then sending commands to the authority for the next step in simulation.
That’s where it comes exciting for me. The game I’m designing this engine to build will rely alot on A.I… good A.I that doesnt cheat. This system lets the A.I only get the same information a human player would, and use the exact same methods to interact with the game world a human is. For me, that’s big!
 So whats that last bit all about? have a closer look!
Please remember this is still far from done, its in a kind of half way state between class layout and program flow diagram! Whats important is that the class CrimsonEng is the engines entry point, create an instance and throw it a start-up script and the game shall load! Its basically a massive collection on managers which will be available for the other systems to use (via the interfaces and core libs). My current plan is to not use the default game class that xna ships with, as it wont fit very well with my engines design (maby more on this next time). Some interesting things here are things like eventMan and MessengerMan. Messages are going to be from entity to entity, good for A.I characters or triggers. Events will be for wider reaching things, like state changes or button presses. I think its important to separate and specialises these kind of messaging functionalities. Well, Thats it for this installment! Cant wait to get my laptob back to start building this thing!
Re: Rotation along a Bezier Curve
cubed2D
July 17th, 2007.
A while ago i wrote an article for ziggyware on moving a sprite over a bezier curve. Well, i recently received an email (hi John!) asking a question, and i remembered a problem i discovered in my code after the article was published!
I included a method for calculating what angle the sprite should be rendered at to produce a cool looking animation. It used a mathematical function called arc tan to calculate this angle.
To tell you the truth, i cant really remember what the actual problem was, but I’m fairly sure that if the control points were not layed out in a perfect right angled triangle shape, the red lines imposed on the image wouldn’t meet at the bottom to form a right angle…. which my method relied on to produce a correct angle (going by memory, as i say, i might be remembering this wrong). it would produce slightly odd results with some quadratic curves, like the one pictured and would definitely screw up on higher order curves.
A much nicer way of doing it would be to store a heading. Every time you update the position of the sprite over the curve, if you normalise its position (presuming your useing a vector for its position) and the calculate the dot product of that heading with the previous heading, you should get the angle between them in radians…. you should beable to use that to create a better looking movement over a curve, of any order. (please note, i havent got xna installed and working at the moment because of my previously mentioned computer problems, so i cant test out this theory!)
Adventures in Pefromance 2: Profiling
cubed2D
June 05th, 2007.
Well, I’ve finished all my exams at uni now, so its back to playing around with XNA! Its high time for an article again, so I’m going to finish up my performance article I started weeks ago. During my first stab at performance monitering code, I wanted to include an in game profiler but I didn’t have enough time to try and implement one. Things are different now!
First of, whats a profiler? A profiler is a tool that can tell you what your code is actualy doing. It tells you how much time it spends in each piece of code. You can get external programs which can profile your .Net application. So why bother writing our own? because games are different to office applications! We want to know what our game is doing frame by frame. External profilers will sample your game application over a few seconds and tell you what happend over thoese seconds, we want to know what happend on a frame by frame basis.
So, what should the profiler be? The profiler component should collect every imaginable piece of data about how the game is currently running, it should include stuff we might want accessible in any game build (I always like to have FPS and Frame Time easily accessible in pc games) and stuff we might want to use in ‘profiling’ builds, like a print out of exactly which pieces of code are being called, how many times they get called and how they relate to another (execution hierarchy). Basically I want to be able to get code to compile into a build of my game which will print out what my game is doing.
How will the profiler know a piece of code is starting and stopping its execution? The constructor for the class registers all the counters to be used in that class and gets id numbers for each performance check, and then at the beginning and end of each method we want to measure we check in and out with the profiler. The code to do all this can be shoved inside a #IF statement so it only gets compiled in if we want a profile build. This means normal release and debug builds are not affected by the new code, and hopefully it will have a small enough footprint not to change the characteristics of the code too much when it is compled in. Is it just me or does this seem far too simple?
As it turns out, yes. Recently I’d been browsing Amazon for some game programming books to buy, and I remembered that some volumes of Game Programming Gems had articles on this very subject listed in their indeces. One quick check of the Durham University library website revelaed that they did in fact have all the books in the main library, on the 4th floor in the fine arts section for some odd reason, and the articles in the first two volumes of the books confirmed my suspicions. It really is that easy… if you have a good clock. The implementation I present to you implements some ideas from the articles mashed in with what I had been working on before I read them.
So first we tackle the problem of a clock. why not use XNAs gameTime I hear you ask? It’s not high res enough! That may sound silly, but gameTime only gives us millisecond resolution. We need a better clock. As discussed earlier, we need to draw every frame in about 16 miliseconds in order to get 60 fps. so we need a clock that can tell us the time in much smaller units than that in order to measure how long it takes each part of the update and drawing cycle to run. At the worst we want a clock that updates every 1 millisecond, better would be microsecond, jackpot would be nanoseconds (its not just how low it goes, but how quickly it updates, theres no point if it can tell us the time in nanoseconds if we can only read it every 4 milliseconds!).
Lucky for us System.Diagnostics.Stopwatch exists (it should work on the xbox as well but I haven’t tested it myself). This is a good and proper high res clock. I wrote a small test app to test it out, you can grab it here. from what I gather it is hardware dependant, so I built this test app and bullied a few people into running it, and the news is good: it doesn’t seem to differ much at all! Stopwatch has a base frequency, which is how many times the clock ticks a second. So the first test was to check if the frequency of the ticks was at all constant over different processors. I managed to test it on two different athlon 64, athlon 64 mobile, celeron m, PIII and an intel T2300. All of the had the same frequency of 3579545 ticks a second, which equates to about 1 tick every 279 nano seconds!
The second part of the test sees how quickly we can access the clock. I did this with a simple loop:
watch.Start();
for (int i = 0; i < 10000; i++)
{
 nano[i] = watch.ElapsedTicks;
}
watch.Stop();
 We just check the elapsed ticks 10,000 times and put the elapsed time into an array. I then found out the average time between the checks and it turned out to be about 5 ticks between every check, giving 1395 ns or 1.3 microsecond. Why did I do all this? Just to prove to myself that I was able to get a good reading from the clock. It’s unrealistic to presume we can check the clock every tick. Seeing as 1.3 microseconds is a good estimate for the smallest unit of time we can grab from the clock, and its allot smaller that 16 miliseconds, Stopwatch has passed the test and we can use it to time our game loop and hopefully I’ve proved to you that its quick enough for the task!
Just to let you know now, I won’t release the code for this componet myself, as what I have at the moment was written very quickly and is not fit to be released, but if you ask I’ll redo it and post it. Instead im going to describe how to implement a profiler. I decided to use performanceMan as a base for this component. First I cleaned up the code, pulling out all the unnecessary things in it so it just handled gametime and fps and printed it to the screen, no more GUI. Next up was adding an instance of stopwatch to the class and instancing it in the constructor. Now, one of the problems we wanted to tackle is if were not running a profiling build, we don’t even want the profile code to compile in to the game, we don’t want it there at all! How do we manage this? All the code to do with profiler we put in a #if preprocessor block. for example, this is what I have in my constructor.
#if profile
              watch = new System.Diagnostics.Stopwatch();
              watch.Start();
               nanosecondsPerTick = 1000000000 /System.Diagnostics.Stopwatch.Frequency; //1 tick in nanoseconds
#endif
Now we need to tell Visual Studio how to build a profile build of our game. On the drop down box where you can select ‘debug’ or ‘release’ choose configuration manager. In here you can make a new configuration, call it profile and tell it to copy settings from release. This way we wont have the debug features in the profile build, but from my experience when you profile you game, you’re not checking for bugs, you’re finding out where it spends its time, so you want it to run as fast as possible. Next you have to open your project properties and go to the build tab and set the configuration to profile. In the ‘conditional compilation symbols’ box add ‘profile’. This lets us use profile as the switch in the preprocessor if’s.
Next we need an object to represent each counter. We can use a class because garbage should not be an problem here as we don’t allocate and deallocate loads of these every frame, we tend to keep our counters for the whole life cycle of the game. Now, what do we need to track in a counter? We definetly need to keep some identifiers, a string for the name of the counter and an integer to hold its id number. We also need some fields to hold the frame by frame action. Something like the following shall suffice.
public int calls; // number of times this counter has been used this frame
public bool open; // is this counter running
public long startTick; // the tick we started this counter on
public long accumulatedTicks; // ammount of ticks we have run this counter for this frame
So, the idea here is when we start a timer, we check if the counter is already open. If it is, throw an error or something. We only want each counter to be running once. If it’s free, we set open to false, increment calls and set startTick to ElapsedTicks (which we get from the stopwatch). When we finish the code and stop the counter, first we grab the current ElaspsedTicks and take away the start ticks, the remainder is the amount of ticks the code took to run. Add this to accumulatedTicks, oh and set open to close.
If we run a piece of code over and over, the calls stack up and the accumulatedTicks holds the combined time that the counter has been running, so we need some variables to handle some basic statistics. I decided to keep track of high and low points and the average running time over a frame. If we had 12 enemies in our game, there update code will run 12 times and obviously calls would be 12, so if we divide the accumulatedTicks by calls we get the amount of time (in ticks) it took on average for each update cycle to run, which is a good stat to print. We can also then test this against a variable holding the shortest and longest time it took to run, and update as appropriate. Remember before you draw them to multiply the number of tics by nanosecondsPerTick to get the amount of nanoseconds that passed. your probably then going to end up with some silly big times though, so you can divide you time in nanoseconds by 1000 to get it in microseconds or by 1000000 to get it in milliseconds. a simple if statement in your drawing code to decided which division to use and what unit to print will help, too. The last thing you should track in each counter is an integer to hold the id of a parent counter. In this we will store the id the counter that contains this counter.
 This allows us to print out counters in the correct order, as seen in this image (the nuber in the brackets is the id for each counter). I’ll describe how this works in a bit!
Ok so far we have a profiler class that has a stopwatch and keeps track of the fps and frametime, and a class to represnt a counter. We need to add the profiler logic to our profiler class, and define a interface for it to use so we can use it as a global service. Let’s look at the interface first.
interface Iprofile
{
       int AddCounter(string counterName);
        int GetCounterID(string counterName);
        void DeleteCounter(int id);
        void UnDeleteCounter(int id);
        void StartCounting(int counter);
        void StopCounting(int counter);
        string EndOfFrame();
}Anything of note here? Not really, everything acts as expected. Ive already discussed what start and stop counting do, add and get counter act as you would imagine. DeleteCounter doesn’t delete a counter, rather moves it to a different list of counters. This allows you to change the behavior of the profiler as it runs. You can stop a counter from being updated (start and stop should fail silently) so you can change the depth of the profiling as you want. undelete simply puts the counter back in the active counters list. Now, back to the relationship thing! We need a third list of counters, every time startCouning is called a counter is added to the runningCounters list. If there are any other counters in the list, the one at the top is assigned the parent of the new counter. StopCounting removes a counter from the running list aswell. This allows EndOfFrame to do its job. The draw method for the profiler calls EndOfFrame to gather all the information from the counters and format it in to a string. We have allread discussed most of its job so I won’t reiterate it, the only thing left to tackle what it does with related counters. First it iterates through the list counters for one which doesn’t have a parent. It adds this to the string first, then it looks for one that has the current counter as a parent. It now adds this one to the string (spritebatch.DrawString will use \n to draw on a new line, so remember to add them!). it keeps running through the list of counters, finding the children, adding to the list, fining the next parent and so on till all the counters are in the string, at which point we return it. Doing it like this puts the counters in the correct order, so AI update in the previous example would sort under update. It’s a good idea to add an indent to the children so you can see they are children. Format the output string like a table and it should be fairly pleasing to the eye.
As you can see, IÂ have some work to do on the output. The units are currently mixed up (average is in microseconds, the min and max are in miliseconds) and the table doesn’t line up stably, but it does demonstrate what we’re after. It doesn’t seem to have any effect on performance either, so that’s all good!
Well, there you have it, a description of how to implement a Profiler into your game. As it stands some things could be tweaked here and there, I’ve hardly touched on error detection, it won’t work with recursive methods and there are probably hundreds of ways you can tweak it to work better with your game. Well, have fun adding one to your game engine, and tell me how it goes!
Crimson Update: Vasculitis (v0.0.2.24380)
cubed2D
May 10th, 2007.
 So heres the layout of my engine at the momentÂ
Without any diagrams, things get messy quickly. I had the thing planned out in my head, i had no paper in my room, my windows were too small to write on (at home i design programs on my windows with dry wipe markers) so i decided to go ahead anyway, and not so surprisingly it got messy. I then decided to use blue J (a java ide we use in university) to draw down what id written so far. Now i know how things connect and i can visualize it better. Id say a visual program designer is a good tool, you can pull things and its cool, but not as cool as using a window!
 Animated sprites have been a fun feature to add, my implementation hangs around the concept of an animation sheet. my orc test sprite has some animations in separate.png files and some bunched together on the same .png. So how do i handle them? every animation gets a animation sheet, which contains its start frame, end frame and a reference to its texture. these are held in a dictionary as a value, the key to that dictionary is a CompassDirection (north, NorthEast ect). I have a load of these in a list, and i keep there indexes in another dictionary with a AnimationState(move, idle, jump etc). To get the correct animation sheet you just need to know what direction and animation you currently in and pull em out. More difficult problems were finding out the current direction and grabbing the current frame from a texture. At the moment i only support the xbox controller, so i needed a way to turn the vector2 returned from the thumb stick in to a cardinal direction. I did this using the magic of dot product. The dot product between two vectors will give you the angle between them. All i needed to do was to have a list of all the directions i wanted to test, try the dot product between them all and then use the animation with the smallest dot product (which would be the closet to the angle of the stick) Heres some code for you!
public class DirectionSet // the 8 compass directions represented in vectors
 {
 public Dictionary
 public DirectionSet()
 {
 directions.Add(0, new Vector2(0f, 1f));
 directions.Add(1, new Vector2(0.5f, 0.5f));
 directions.Add(2, new Vector2(1f, 0f));
 directions.Add(3, new Vector2(0.5f, -0.5f));
 directions.Add(4, new Vector2(0f, -1f));
 directions.Add(5, new Vector2(-0.5f, -1f));
 directions.Add(6, new Vector2(-1f, 0f));
 directions.Add(7, new Vector2(-1f, 1f));
 }
 }
Use this function to get the sticks direction:
public int GrabAnimationDirection(Vector2 stick)
 {
 float bestDot = -100;
 int bestAnim = 0;
 for (int i = 0; i < 8; i++)
 {
 Vector2 normal = Vector2.Normalize(directionSet.directions[i]);//normalise the directions
 float dot = Vector2.Dot(velocity, normal); //find the angle
 if (dot >= bestDot) //if its smaller, save it
 {
 bestDot = dot;
 bestAnim = i;
 }
 }
 return besttAnim;
 }
Then i just cast the returned int to my CompassDirection enum for use!
The other problem is alot easier, how do we choose the tile? First, we need a frame counter to increment. I increment it every 33ms (30fps). we also need to know the number of columns in the sprite sheet and the height and width of each sprite. with this info we can find the top left corner of each frame
int x = (frame % column) * width;
int y = (frame / column) * height;
Its really simple when you think about it, just grab a sprite sheet, and try these for a frame in the middle, I’m sure your understand how it works straight away!
The other useful thing i learned is how to cast a string in to a enum. Which is really useful when reading info out of an xml file.
(CompassDirection)Enum.Parse(typeof(CompassDirection), “North”);
remember to test its going to work first!
Enum.IsDefined(typeof(CompassDirection),”apples”);
would return false, because apples just arn’t directions no matter how hard they try.
anyways, Crimson 0.0.2.24380 new features!
Features:
- Better, more flexible animation system, which supports:
- Idle animations
- Movement
- Shooting
- Death
- and flexible to add others!
- Loading XML files which describe an animation, and serializing them in to actual animation sprites.
- early prototype of the input manager.
- updates to my content manager
also, for anyone who is interested, heres a short demo. It only works with an xbox controller at the moment. left stick moves you around, B jumps and A kills you. If anyone can run it and tell me how it runs on there pc id be grateful!
Crimson Update: Vasculitis (v0.0.1.423)
cubed2D
May 08th, 2007.
And now for an update on my Crimson engine! I’ve been working on the fist minor milestone, codenamed Vasculitis over the passed few days. The plan is for Vasculitis path to take Crimson all the way up to v0.2, and by the end its lifespan to have all the basic features (apart from scripting) implemented.
So far, ive completely rebuilt the screen system. Ive looked through Microsoft’s game state management sample and i loved the way they implemented some things (especially the transitions!). After playing with it a bit, it was clear id have to do a bit of retooling on my screen system, which ended up with me ripping out the whole screen system and starting from scratch.
 After that, i added in basic support for menu screens, worlds and UI popups. Then built a basic entity system, that currently supports static and animated sprites! been a busy few days! still needs allot of work and clean up, but its cool so far!
My animated sprites support single or multiple animation sprite sheets, and multiple animations. Heres a short video of an orc running around my test level. He’ only using the running animation (small bug at the moment with switching through different animations) but does show that sprite sheet switching does work, as each direction is on its own sheet.
Crimson build name Vasculitis (v0.0.1.423)
Fun with Bézier Curves!
cubed2D
May 02nd, 2007.
Ive written a short tutorial for Ziggyware’s upcoming tutorial contest! Its about moving a sprite over a curve. Not the most exciting thing in the world, but then FPS monitoring and screen resolutions arnt really a bag of fun either.
 But someone has to write articles on the things nobody else even considers, so part 3 of the neckocake code dump is out! Check the code page for the code as always (this time you can grab yourself a lovely test exe too!) and the customary video is up as well.
Ohh, and these lovely looking equations!
 /Sarcasm off
Hope Someone finds it useful! Read it on Ziggyware
FPS, Frame Time and you: adventures in performance.
cubed2D
April 28th, 2007.
Everyone knows what FPS is, so I won’t waste time explaining that it stands for Frames Per Second, and that 60 FPS is the level of performance your game should be targeting, and 30 FPS is acceptable but you shouldn’t drop below that, and all the common knowledge stuff, so don’t worry about that.
Instead I’ll look at what FPS values actually mean, how we count them in game and then why it’s a bad idea to profile your games performance using FPS as your only metric.
So as you no doubt are aware, 60 FPS is where it’s all at. I’m sure you already noticed that the default timing system in XNA locks the game loop at 60 FPS by default. Seeing as we want to make sure our games are running at 60 FPS, wouldn’t it be useful to actually see the frame rate? As XNA has not got a inbuilt way to find the FPS, its time to roll our own!
So how do we measure our FPS? Well, I’m sure if you think about it you can come up with a simple way to find it out. Stop reading now and have a little think!
You were probably thinking something along the lines of this:
public override void Update(GameTime gameTime){ frame++; //a frame counter, incremented every time update is called (and therefore, once a frame) // calculate current FPS time += gameTime.ElapsedGameTime.TotalMilliseconds; // add the amount of time since we last updated a frame to a time counter if (time >= 1000f) //after we have been running for 1 second { time = 0f; // reset the timer currentFPS = frame; //and copy the amount of frames drawn to a fps counter, ready to display frame = 0; //reset frames and begin counting all over again! } }
Yep, it seems simple enough. The problem is, this method can’t tell us the immediate frame rate (as in the fps for each frame), or the average frame rate without storing every seconds frame rate value, which would quickly become a massive collection! There must be a more elegant and useful way of doing it. Maths time!
How much time does the computer have to think about each frame if its going to draw 60 frames a second? Well, that would be….
1 second / 60 frames = 16.666..ms or 1 second / 60 FPS =0.0166666667 seconds
wow, not a lot of time! Well, basic maths lets us rearrange this as…
1/ 0.0166666667 = 60
and as simple as reciprocal division, we have a simple formula for calculating our FPS on a frame by frame basis!
currentFPS = 1 / gameTime.ElapsedGameTime.TotalSeconds; // remember, the elapsed time is the time thats passed since we last ran Update.
Using this new found knowledge, we can finally do fun things like know the frame rate for each frame and find out the average over the course of our games life! Stop! It’s coding time.
In your project create a new game component, call it performanceMon. As we’re going to want to draw the FPS to the screen so we can see it easily, change it from using GameComponent as a base to DrawableGameComponent. That will let us override draw and the content methods.
Get your code to look like this.
#region Using Statements using System; using System.Reflection; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; #endregionnamespace NekoCake { public class performanceMon: Microsoft.Xna.Framework.DrawableGameComponent { private ContentManager content; GraphicsDeviceManager graphics; private SpriteBatch batch; public performanceMon(Game game, GraphicsDeviceManager graphics) : base(game) { this.graphics = graphics; } public override void Initialize() { content = new ContentManager(base.Game.Services); base.Initialize(); } protected override void LoadGraphicsContent(bool loadAllContent) { if (loadAllContent) { batch = new SpriteBatch(graphics.GraphicsDevice); } } protected override void UnloadGraphicsContent(bool unloadAllContent) { if (unloadAllContent == true) { content.Unload(); } } public override void Update(GameTime gameTime) { base.Update(gameTime); } public override void Draw(GameTime gameTime) { } } }
Now that we have a layout to work in, lets get our FPS formula into code! First off, we need some new variables.
//FPS variables private int totalFrames; private double currentFPS; private double averageFPS; private double highestFPS; private double lowestFPS;Now lets add the FPS logic to the update override. public override void Update(GameTime gameTime) { // increment frame counter. totalFrames++; //fps calculations currentFPS = 1 / gameTime.ElapsedGameTime.TotalSeconds; averageFPS = totalFrames / gameTime.TotalGameTime.TotalSeconds; // highest fps if (currentFPS > highestFPS)) highestFPS = currentFPS; // lowest fps if (currentFPS < lowestFPS) lowestFPS = currentFPS; }
Yay, thats that done and dusted… oh wait a bug! If you run the code and keep an eye on the Highest FPS, you will see that it comes out as Infinity (you can just pause the game sometime and look it up in the immediate window or the local variables window). Turns out that on the first call, the game’s been running for 0 seconds, and therefore our FPS calculation says were running at an impressing speed of an infinite amount of frames a second! So, we have to check if current fps is infinity.
if (currentFPS > highestFPS && !double.IsInfinity(currentFPS)) highestFPS = currentFPS;
Yay, thats that done and dusted! We now know the performance of our game! Unfortunately, FPS isn’t a good metric for game performance, it’s just the most well known. Its problems stem from the fact that its completely non linear.
What does that mean for us? Well suppose your game was running using a variable game time loop (remember, XNA defaults to locking your game at 60FPS, you can unlock it and use variable frame time instead). Your game’s running at 500FPS. You change something and now it’s running at 330FPS. Thats a massive loss of 170FPS! Now, in a different situation (say, a much more busy level in the game) its running at 60FPS, you change something and now its running at 55FPS. Which change represents the more computationally expensive change to your game, the 170FPS drop in you test app or the 5FPS drop in your full level? If we look at the Frame Time, the amount of time it takes a frame to draw, we can tell easily! How do we calculate the frame time? We divide 1000ms(or 1second) by the frame rate.
1000 / 500 = 2ms per frame.
1000 / 330 = 3ms per frame (ok, I rounded up here a little)
1000 / 60 = 16.66 ms per frame
1000 / 55 = 18.18ms per frame
Surprisingly, the method that caused a 5FPS drop in the second example is twice as expensive as the one that caused a 170FPS drop in the first! As you can see, the different frame rate drops don’t give an accurate idea of the real impact, computationally speaking, a new drawing method has, on your game loop for example. A increased draw time of 1 ms per frame from 60FPS would give us a frame rate of 58.8something FPS, which is not the same kind of drop you get when you increase the draw time from 2ms to 3ms. Robert Dunlop made a brilliant graph showing this (infact, that’s the article I used when I first learned of Frame Time. LINK)
So, what does that mean for us? FPS is a good way to quickly judge performance. It’s a good number to glance at to get an idea of how well the game’s running, it’s not a good metric to use when trying to optimize your game engine to run as fast as possible, or when comparing the speed of different algorithms. Seeing as they both have merits, we should support both. Heres the new variables we will need.
//Frame Time variables private double lastFrameTime; private double averageFrameTime; private double bestFrameTime = 999; // see lowestFPS private double worstFrameTime; and add the following to the update method. //frame time calculations lastFrameTime = 1000 / currentFPS; averageFrameTime = gameTime.TotalGameTime.TotalMilliseconds / totalFrames; // best frame time if (lastFrameTime < bestFrameTime && lastFrameTime != 0) bestFrameTime = lastFrameTime; // worst if (lastFrameTime > worstFrameTime) worstFrameTime = lastFrameTime;
Notice the && lastFrameTime != 0 bit? This fixes the same issue as the check for infinity last time.
Ok, lets check what we have achieved so far. We can calculate the FPS, average FPS, and store the highest and lowest FPS achieved, and do the same for Frame Time. Good, that’s a start! So, what limits the usefulness of this class? At the moment, we have no way of reading out the FPS or Frame Time, apart from pausing the execution and checking manually. We do not have the ability to reset any data, no way to check the FPS/Frame Time in code (it would be usefully, for example if we had implemented two different path finding systems, and we ran each on the same data one after the other, we would want to know the frame time for each system so we could see which runs quicker).
Also, it might be nice to add in some logging abilities to the class, rolling all our debug systems in to one manager. Also, it might then be a good idea to get a printout of the games version number on screen.
Ok, so lets get these issues sorted one by one. First is output. We will start out with some basic text based output, and the add to that to get a cool console window for it. As a note XNA Game Studio Express 1 Refresh is needed as I’m going to use the new DrawString method, but you can of course use whatever output system you want.
First, we need us a string to write the text in to. Declare a new string at the top of the class called output. Next we need to add a font. Add a new font to your project. If you dont know how to do this yet, it’s easy. In the solution explorer, right click, add new item and chooses sprite font. The XML file it creates is self explaining, and you can look it up on the msdn if you need more help.
As for font, I’m going to use proggy small, my favourite programming font (http://www.proggyfonts.com) . Then we need to add the font to our variable list.
private SpriteFont font;
in the LoadGraphicsContent override, we need to load the font.
font = content.Load<SpriteFont>(“assets\\font\\console”);
now we need to build the output string in the Update override.
//build the output string. output = "FPS Stats (Higher is better)n CurrentFPS: " + currentFPS.ToString() + " n Average FPS: " + averageFPS.ToString() + "n Highest FPS: " + highestFPS.ToString() + "n Lowest FPS: " + lowestFPS.ToString() + "nFrame Time Stats (Lower is better) n Last Frame Time: " + lastFrameTime.ToString() + "n Average Frame Time: " + averageFrameTime.ToString() + " n Best Frame Time: " + bestFrameTime.ToString() + " n Worsts Frame Time: " + worstFrameTime.ToString();
last of all, we need to draw it to the screen. Add this to the draw override.
batch.Begin();
batch.DrawString(font,output,Vector2.Zero,Color.White);//draw the text
batch.End();
If you want to have a look at the complete code up to this point, you can download a copy here (http://www.nekocake.com/pad/code-samples/). So far we’re at performanceManager v1.
Next up was the ability to reset the high/low/average scores for FPS and Frame Time. This will work fine for high and low, but seeing as average is calculated using time we are going to need to keep track of how much time had passed when we asked for the reset, otherwise it wont work. Lets give ourselves two more variables
private double resetTimeMS; private double resetTimeS; //and a brand new method called Rest public void Reset(GameTime gameTime) { totalFrames = 0; averageFPS = 0; highestFPS = 0; lowestFPS = 999; averageFrameTime = 0; bestFrameTime = 999; worstFrameTime = 0; resetTimeMS += (gameTime.TotalGameTime.TotalMilliseconds - resetTimeMS); resetTimeS += (gameTime.TotalGameTime.TotalSeconds - resetTimeS); }
Storing the time elapsed since the reset will allow us to take that time away from the total time when calculating the average, thus giving us the correct average since the last reset.
Change the aveargeFPS calculation to
averageFPS = totalFrames / (gameTime.TotalGameTime.TotalSeconds – resetTimeS);
and the averageFrameTime calculation to
averageFrameTime = (gameTime.TotalGameTime.TotalMilliseconds - resetTimeMS) / totalFrames;
Now thats done, what’s left? Like I mentioned earlier, logging support and time comparisons might be a good addition to this class, but really you can use it as is. It could probably be improved, such as using the string builder system instead of normal strings. Have a look at version on my code page (http://www.nekocake.com/pad/code-samples/). I’ve added a few features to it, such as a performance indication light, loading of the assembly to get the game name and the version number, using a custom render target to render the games name on to the back of the console window texture. Ive also added a few more stats to the print out and added masks to the output to make it easier on the eye.
This is just a small example of how you might modify this component for your engine/game, so get to it, add it to your engine, if you make any cool mods please email me and pass on your experiences!
Heres a short video of v2 running in my balls test app.
ResChange Game Class
cubed2D
April 20th, 2007.
Ok, ill admit it might not seem like a big thing, but i personally hate it when games have crummy choice in screen resolutions! So, people of the XNA world, i present to you a class pulled from CrimsonEng, ResChange.
When i work with screen resolutions, i tend to use there silly standardisation names (things like QXGA), which are probably a mystery to most people! Never fear! Lets explore these strange acronyms!
Lets start with the easy letter, W stands for Wide surprisingly enough, (aspect ratio of 16:9 or 16:10 for those who care)
Q on the other hand, is a tad more difficult as it can stand for quarter or Quadruple. It depends on the size of the resolution, quarter means the resolution is a quarter the size of the base resolution (QVGA is a quarter of the size of VGA), where as a Quad resolution would be… you can see where this is going!
U and X are Ultra and eXtended, and H is for Hexadecatuple (or hex to you and me!)(and there’s a word you dont use every day!)
Now we can read the names, lets have a look at a list of resolutions that are provided by resChange. (well, we can learn them but it might be a better idea to print a small sheet out to attach to your moniter if you want to use this class… ohh the wonder of post it notes)
Normal
QQVGA 60×120
QVGA 320×240
VGA 640 × 480
SVGA 800×600
XGA 1024 × 768
SXGA 1280×1024
UXGA 1600×1200
QXGA 2048×1536
QSXGA 2560×2048
QUXGA 3200×2400
HXGA 4096×3072 (if your running at this res right now, i want you pc)
HSXGA 5120×4096
HUXGA 6400×4800 ( XD )
WideScreen
WXGA 1280×720
WSXGA 1440×900
WSXGA+ 1680×1050
WUXGA 1920×1200
WQXGA 2560×1600
WQSXGA 3200×2048
WQUXGA 3840×2400
WHXGA 5120×3200
WHSXGA 6400×4096
WHUXGA 7680×4800
TV
480i 640 x 480
720p 1280 x 720
1080p/i 1920 x 1080
whew! That’s a lot of resolutions! Bet your glad i wrote this for you now? (or not!). Just so you can get an idea of how these compare, have a look at this brilliant comparison image i found on Wikipedia.
![]()
How do we use resChange i hear you ask? Very simply! Add the name space to your using section, call SetGraphics(graphics); Then you can use any version of the resChange method you want to use. the main version uses a ScreenMode enum, wich basicly contains all the strandard names and maps them to there screen resolutions.
Again, ill admit that its a very simple class, but i find wrapping this kind of stuff in to a nice little package endlessly useful. I hope someone finds this useful!
Get The Code Here
note: some of the really really big resolutions (probably HXGA and silly bigger) may cause some odd error in xna, and thus your game wont run. This is because your graphics card cannot handle textures of that size! You can check your max texture size quite easily with tools like direct 3d caps


