A better normalize function for XNA
I was reminded of an incredibly annoying C# feature tonight that I had ran into before; the ability to divide floats and doubles by zero and end up with Infinity rather than an exception. After hunting down all the problem areas in my code, my velocity and position vectors were still being corrupted by this problem. Using the console I mentioned in the last post I started tracking the vectors at dozens of code points until I finally narrowed down the problem area.
velocity.Normalize();
This built in XNA call doesn't do any validation to make sure you aren't passing in Vector3.Zero. If you do pass in Vector3.Zero, you end up getting back a vector with all three components equal to NaN! In addition to this, sometimes it is helpful to get a copy of the vector length back while you normalize. With both of these in mind I coded this extension.
/// <summary>
/// Normalizes the vector and returns its length. Also checks for zero to save some time and avoid NaN or Infinity results.
/// </summary>
/// <param name="v">Vector to normalize</param>
/// <returns>Length of vector</returns>
public static float SafeNormalize(this Vector3 v)
{
// nothing to see here folks, move along
if (v.X == 0 && v.Y == 0 && v.Z == 0)
return 0;
float length = v.X * v.X + v.Y * v.Y + v.Z * v.Z;
if (length != 0)
{
float isqrt = 1.0f / (float)Math.Sqrt(length);
length *= isqrt;
v.X *= isqrt;
v.Y *= isqrt;
v.Z *= isqrt;
}
return length;
}
I did some basic testing, comparing several versions of this function to the built in offering. When passing Vector3.Zero, my function is staggeringly faster. In all other cases, it was a few MS slower than the built in. A few MS can also be gained by implementing a version that doesn't waste time returning length when you won't be using it. ANd when I say a few MS, this is spread across 2 million operations of the function.
Quake style console
I've been working on a Quake 3 style engine in C#/XNA for a few weeks now. I'm using only the file formats as my guide and so far resisted the urge to download the actual Q3 source. This weekend I added a fully functional console. The console implements drawable game component as a singleton so it is very self contained and easy to drop right into the game window. Quick rundown of the features so far:
- Write lines of colored text into the buffer from anywhere.
- Page through entire buffer with page up and page down.
- Xml serialized (loads/saves upon start and exit) dictionary of console variables, adjustable within the console and usable by any part of the code.
- Reflection based command execution (I use private static as my 'allowed for console use flag' when searching the class for methods). The cool thing here is I can use #if DEBUG to setup a block of my own powerful dev commands that wont be available to users, but any other commands are automatically available.
- Input history can be recalled doskey style and the input line is fully editable (move cursor, backspace, delete, full ascii map).
- Full console log dumped to text file on exit.
- Paste from clipboard

Blocks
Finally got around to completing my first game. It is a basic Tetris clone written in C#, using the XNA 4.0 framework, that runs on both Windows and Xbox 360. The pieces are controlled with either the arrow keys on the PC, or the D-Pad on the Xbox. Pressing space or start will pause the game and pressing F1 or Y will start a new game. To exit you can press escape or back. The level is driven by the number of lines completed and scales along the powers of two. However, the only thing level is relevant to is calculating the points earned for completing a row.
One aspect I had a lot of fun working out was creating the text effect for Pause and Game Over. To achieve the 3D effect I simply used a font with two layers (upper-case is flat and lower-case is the body). Then I used the sin function with an angle that slowly changes over time to update the position of one letter per frame, resulting in a wave animation. There is obviously a lot more I could do to spice this game up, but I'm happy stopping here so I can move on to the next project.
You can download the executable here if you'd like to check it out. To run the game you will need to have .NET 4.0 Framework installed as well as XNA 4.0 Framework.
Remove unused local variables in VB.NET
I work with a very large ASP.NET solution that has its roots in an old VB6 Access database application so not only is the code a mess, but it is written in VB. I've been searching for a good clean-up addon for VS for a while now but all of the good functionality is always reserved for C#. Last night I finally got tired of seeing all the unused variable warnings and realized that I could pull off a quick and dirty solution.
Locating the variables
Obviously the first thing I had to figure out was how to track down all these unused variables. This is where the quick/dirty part comes in that greatly reduced the amount of work on my plate. I have an automated build script that I had used in the past and this script dumps the build log to a text file. I realized that I could take that text file and parse it for warnings and the whole thing would just be simple file I/O.
The build.bat file:
@echo off C:\WINDOWS\Microsoft.NET\Framework64\v3.5\msbuild.exe c:\code\cleanup\build1.msbuild > c:\code\cleanup\result.txt
- The first part of the path is the location of msbuild on your system.
- The second part of the path is the location of a file that tells msbuild what to do exactly.
- The final part of the path is where we want to write the output log to.
My msbuild file:
<Project DefaultTargets="Main" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<WebsiteName>mysite</WebsiteName>
<PrecompiledAssembliesPath>c:\temp\mysite\</PrecompiledAssembliesPath>
<BuildDirectory>C:\inetpub\wwwroot\mysite</BuildDirectory>
</PropertyGroup>
<Target Name="Main">
<AspNetCompiler
VirtualPath="/$(WebsiteName)"
PhysicalPath="$(BuildDirectory)"
TargetPath="$(PrecompiledAssembliesPath)"
Force="true"
Debug="true"
Updateable="true"
/>
</Target>
</Project>
Removing the variables
The code for the application to actually remove the variables from the source files is pretty basic and should be straightforward enough. I chose to replace the unused variables with an empty line but you could just as easily comment out the lines by making a couple small tweaks to my code.
using System;
using System.IO;
namespace cleanup
{
class Program
{
static void Main(string[] args)
{
string openfile = "";
string[] openlines = null;
using (StreamReader r = File.OpenText("result.txt"))
{
string line = "";
while (true) {
line = r.ReadLine();
if (line == null)
break;
// look for unused variables
if (line.Contains("BC42024"))
{
int pos = line.IndexOf('(');
string file = line.Substring(0, pos);
pos++;
string linenum = line.Substring(pos, line.IndexOf(')') - pos);
if (openfile != file)
{
if (openlines != null)
{
SaveFile(openfile, openlines);
}
openlines = OpenFile(file);
openfile = file;
}
int index = int.Parse(linenum) - 1;
openlines[index] = "~";
}
}
}
}
static void SaveFile(string file, string[] lines)
{
File.WriteAllText(file, string.Empty);
using (StreamWriter w = new StreamWriter(File.Open(file, FileMode.Open, FileAccess.Write)))
{
for (int i = 0; i < lines.Length; i++)
{
if (lines[i] != "~")
{
w.WriteLine(lines[i]);
}
else
{
w.WriteLine();
}
}
}
}
static string[] OpenFile(string file)
{
using (StreamReader r = File.OpenText(file))
{
string lines = r.ReadToEnd();
return lines.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
}
}
}
}
And that is all there is to it! It's sloppy but I'm happy with the results I got for the amount of effort put in. I may be extending this code at some point to address some of our other warnings that are very common. I would LOVE to track down all the unreferenced functions, classes, and members in our code.
SurfaceFormat.Single in XNA 4.0
Another problem I came across setting up a deferred renderer in XNA 4.0 has to do with using a SurfaceFormat.Single render target.
Additional information: XNA Framework HiDef profile does not support alpha blending or ColorWriteChannels when using rendertarget format Single.
In my example below, you can see that all this takes to fix is simply setting BlendState.Opaque.
public void Clear()
{
Game.GraphicsDevice.BlendState = BlendState.Opaque;
clearBufferEffect.Techniques[0].Passes[0].Apply();
QuadRenderer.Render(Vector2.One * -1, Vector2.One);
}
After that fix, you're faced with a new error:
Additional information: XNA Framework HiDef profile requires TextureFilter to be Point when using texture format Single.
To resolve this you have to update any shaders (i.e. lights) that use this texture to use Point filters.
texture depthMap;
sampler depthSampler = sampler_state
{
Texture = <depthMap>;
MagFilter = Point;
MinFilter = Point;
MipFilter = Point;
AddressU = Clamp;
AddressV = Clamp;
};
Additive blending in XNA 4.0
I've been working to add deferred rendering to my XNA project and I came across something that Google wasn't very helpful with. I assume you're already familiar with the state changes on the render device but in this specific scenario the baked in Additive BlendState doesn't work at all.
In 3.1:
GraphicsDevice.RenderState.AlphaBlendEnable = true; GraphicsDevice.RenderState.AlphaBlendOperation = BlendFunction.Add; GraphicsDevice.RenderState.SourceBlend = Blend.One; GraphicsDevice.RenderState.DestinationBlend = Blend.One; GraphicsDevice.RenderState.SeparateAlphaBlendEnabled = false;
In 4.0:
additiveBlend = new BlendState(); additiveBlend.AlphaBlendFunction = BlendFunction.Add; additiveBlend.AlphaSourceBlend = Blend.One; additiveBlend.AlphaDestinationBlend = Blend.One; additiveBlend.ColorBlendFunction = BlendFunction.Add; additiveBlend.ColorSourceBlend = Blend.One; additiveBlend.ColorDestinationBlend = Blend.One;


