Game Design, Programming and running a one-man games business…

Normal mapping question (it’s my day OFF)

EDIT: I’ve fixed it. It’s my own dumbassness. I was setting the sprite_angle variable in the shader AFTER the shader had started, and it was presumably never being set, and populated with garbage (or the ship beforehand) it works a charm now :D

Right so, despite being good at AI coding and optimisation, i suck at this clever stuff you people call ‘3D math’. I was in the pub that day of school. So I enlist you, the all-knowing internet to explain to me like a child what I am doing wrong. Here are 3 images:

normalmapstuff

The left is just the ship, the middle is a normal map thingy (thanks to charles!) and the right is what it looks like on screen given a single light source. The end result is exactly what I wanted, and there is much rejoicing… BUT. It’s screwed up, the position of the light source is wrong, and seemingly random, and sometimes jumps and cycles all over the place. I reckon I have everything sorted except the shader, which is an fx file as follows:

sampler2D g_samSrcColor : register( s0);
sampler2D g_samNormalMapColor: register( s1);
float sprite_angle : register(C0); 

float4 NormalMap( float2 texCoord : TEXCOORD0 ) : COLOR0
{  
    //get the value of the normal at this texturecoord
     float3 normalcolor = tex2D(g_samNormalMapColor, texCoord);

     //convert it to +/- 1.0 range
     normalcolor *= 2.0f;
     normalcolor -= 1.0f;

     float3 LightDirection;
     LightDirection.x = sin(sprite_angle);
     LightDirection.y = cos(sprite_angle);
     LightDirection.z = 0;

     float dot_prod = dot(LightDirection, normalcolor);

     //apply as a tint to the final pixel
       float4 original = tex2D(g_samSrcColor, texCoord); 
       float4 final = original;
       final.r *= dot_prod;
       final.b *= dot_prod;
       final.g *= dot_prod;

       return final;
}

As an idiot, I’m not really sure what I am doing here. What I *think* I’m doing is this: I am drawing a sprite which has a separate normal map (g_samNormalMapColor) I also pass in the current angle of the sprite. I sample the color of the normal map, and convert it into the required range. I then convert the sprites angle into a light direction vector (probably wrongly) and I then do some magic which kids call ‘dot’ which I’m guessing gives me the brightness of the pixel given the angle and the default light direction. I then multiply the original texture color by this brightness to tint my final rendered sprite. Yay.

it’s something clever to do with angles and vectors and stuff isn’t it? explain it to me like I’m an idiot :D

 

And yeah…I’m playing about with Gratuitous Space Battles. It’s a Sunday morning, don’t read too much into it :D

Some optimization tips for game programmers

I’m enjoying myself with some optimizing today (yeah I’m weird like that). So I thought I’d jot down some of my tips for making your game faster. These are general, not language-specific tips.

Never run code you don’t have to run

Seems obvious but few people actually do this. For example, in democracy 3, the simulation calculates the popularity of each policy by asking every voter if they benefit from it. That question is complex, and there are a few hundred policies and 2,000 voters. This takes time. Solution: I only ask them about a policy if I need the answer right now. Some policies can go a dozen turns without the player ever checking their popularity, so why keep calculating it?

Batch Stuff

If you have a dozen icons that are always drawn one after another on the same screen, stick them in a texture atlas. If you are 100% they will never overlap, then draw them in a single draw call. the less texture swaps and draw calls, the faster your code. This is trivial to do in 3D, an absolute nightmare to do properly in 2D, but it’s worth it.

Cache Stuff

If you have a variable that is complex to evaluate, evaluate it once, then cache it until it changes (we tend to call that setting it ‘dirty’). If there is some data that is going to be accessed a LOT, then make a local copy of it. And if you have a lot of stuff to write to disk, to the same file, buffer it. Writing to or reading from a file is slow, especially if you are going to do it a lot. Reading in a single file is much quicker than opening 200 of them one after another.

Don’t use sqrt()

Do you ever use sqrt()? never realised how scarily slow it was? Most of the time you can keep the squared result and use some clever tricks to not actually need the sqrt() result. If you were going to get the sqrt() and compare it against a value, just multiply the comparison value by itself and check it that way instead. it’s amazingly faster.

Use the right container class

Sometimes you will use a list where a vector will do. The vector is MUCH faster. And you know what is faster still. I mean REALLY fast? An array. If you really need speed, and the array size won’t change that often, allocating an array of items is much faster and is worth the overhead.

Re-use objects

If you have a collection of objects that keep getting created and destroyed, you want to wrap that up. Stick a factory object around them to handle their construction and destruction. That way, you can just set them inactive on destruction, and save yourself the hassle of the creation and destruction when it comes time to re-use them. Setting a single flag to say an object is ‘dead’ is way faster than calling a destructor, and resetting is way faster than a constructor.

Obviously there are lots more tips, and you should get a decent commercial profiler. That PC you develop on is a super-computing beast. if your game takes more than a few seconds to load, you are being sloppy.

 

Dumb multithreading question (how to safely quit a multithreaded app)

I’m not a multi-threading expert. my main process trundles along nicely then when loading the game it calls CreateThread() to do some loading stuff. Then, while the main thread is rendering my lovely loading screen, and the new thread is loading in data, some evil player hits the top right X button, or alt+F4s the game…

Instant crash!

Unless I add code which calls my thread manager and then calls TerminateThread(). This works…but then the app does not actually properly quit, so it can’t work right. Also… I now read that TerminateThread() is not the way to exit a thread anyway, and I’ve been using it all this time… arghhh!

How do you handle quitting a multithreaded app when the player arbitrarily exist it? Nobody seems to have a definitive answer…

Democracy 3 and rendering crisp text in directx

Democracy 3 is a text heavy game. Text and stats, and graphs. So it’s pretty important it is all legible. I’ve spent the best part of two days monkeying around with my text rendering code, which is part of my library (all written by yours truly), trying to get better results. My aim is obviously easy readability. here is some text from the current (Democracy 2) game: (excuse the bitmap format but obviously I don’t want to add artifacts here…)

oldtext

And here is the current implementation in Democracy 3 (different color scheme too).

newtext

I think the second example is marginally better, but frankly that’s just a better color scheme and bigger text. the actual *quality* of the text is certainly nothing special. What I want, clearly is something as good as the text I see windows drawing in webpages and text documents outside of games. Unfortunately, that isn’t as easy as it sounds.

Most LCD monitors are set up to use cleartype, information on wikipedia. This is a cunning system that effectively increases the screen resolution by using colored ‘sub-pixels’, You can see the effect by taking a screen grab of this page (for example) and then zooming in really close. You will notice this text isn’t really black, or indeed one color. Some sort of cool display/monitor-driver cleverness handles this when it displays text. The trouble is, you can’t just ‘enable’ that for a game drawn the way I do things, where each character is effectively a tiny sprite. It just can’t be done.

Now there ARE some clever solutions to get amazing text, I know valve have some clever system, but this all involves implementation of a bunch of third party code and shaders. That isn’t a big deal *as such*, but it means that I have to cannibalize my extensive current GUI library and font loading and text-wrapping/aligning/processing stuff to work with all new systems. This would be a ton of work, and increase the spaghettiness of my library, something I am keen not to do.

I have tried just doubling my bitmap font size and using mip-maps to scale it down, but if anything that looks worse, so I’m trying to keep to my current system, which uses a 1:1 pixel to texel mapping with point filters engaged to get exactly what I see in my font bitmap file.I have a horrible feeling that swapping to black text on white screens is just going to look far worse than white text on black, at least from a  text-crispness POV.

There is of course, also the issue of opportunity cost. Is more time spent on this a good idea when I could spend that time elsewhere in the GUI, or for that matter, the simulation or game balance. Democracy 2 never earned me anyone bemoaning it’s crappy text, maybe the new text is good enough? Developers – What system do you use for text-rendering in games?

edit: maybe this black version looks better?

blacktext

Saving and Loading

How I envy developers working on arcade games, or anything that has a very simple game ‘state’ that can be easily saved and loaded with no grief. For the game I am currently working on (announcement later this month), it’s a bit of a pain, because the actual game ‘state’ is horrendously involved, and every single byte of it has to be loaded and saved perfectly. The problem is mainly due to my tendency to code systems that have a huge number of objects that all have pointers to each other, in complex and arcane ways.

In theory, stitching everything back together after a load is fairly easy, but in practice, it’s a bit of a pain, and the REAL pain is to know that it has all worked perfectly. if 99% of the pointers are right, and 1 isn’t, then I have a horrible dangling bug somewhere…

My current process for preventing this is to have the game completely save out it’s state and load it’s state back in every turn (it’s a turn based game). At the moment, due to arcane debugging issues this is horribly slow, but eventually will be super fast. At least doing it this way means that during development I’ll spot any save/load inconsistencies really quickly.

I’m aching to get on with some GUI stuff to make it look nice, but I’ve learned the hard way that I have to put that off until the foundations work better. Better to have it stable now, rather than fix it later.