text:
How does one multiply by a constant in a VS1.1 assembly vertex shader?
I'd like to multiply a vector by -1
e.g.
mul    r0,    r0,    -1

When I try this, I get this error message:
SimpleShaderA.vsh(20,17): error X2000: syntax error : unexpected integer '1l'

How can I specify -1 in my (first) shader program?

Why are you writing assembly shaders? Modern shader models (4+) do not allow you to do this, and unless you have a very compelling need to achieve a clever effect on a very low-end card you'll probably learn more writing in HLSL.

i've been set an assignment that uses assembly shaders to teach us the math more than anything else ;)

The mul assembly instruction takes registers as inputs, not constants. You can do this instead
def c0, -1, -1, -1, -1
mul r0, r0, c0

which uses the def instruction to define a constant vector in register c0 and uses that as the second multiplicand to mul.
You could also use swizzling on the c0 register, so you could put different constants you may need to multiply by in c0's components. You can also just write the multiplication in terms of c0 and assign it values via the Set***ShaderConstant* APIs.


text:
XNA Easy Storage XBOX 360 High Scores
To followup from a previous query - I need some help with the implementation of easystorage high scores, which is bringing up some errors on the xbox.
I get the prompt screen, a savedevice is selected and a file are all created! However the file remains empty, (I've tried prepopulating but still get errors).
The full portions of the scoring code can be found here: http://pastebin.com/74v897Yt
The current issue in particular is in LoadHighScores() - "There is an error in XML document (0, 0)." under line data = (HighScoreData)serializer.Deserialize(stream);
I'm not sure whether this line is correct either: HighScoreData data = new HighScoreData();
public static HighScoreData LoadHighScores(string container, string filename)
        {
            HighScoreData data = new HighScoreData();
        if (Global.SaveDevice.FileExists(container, filename))
                {
                    Global.SaveDevice.Load(container, filename, stream =>
                            {
                                File.Open(Global.fileName_options, FileMode.OpenOrCreate,
                                         FileAccess.Read);
                                try
                            {
                                            // Read the data from the file
                                        XmlSerializer serializer = new XmlSerializer(typeof(HighScoreData));
                                        data = (HighScoreData)serializer.Deserialize(stream);
                            }
                              finally
                             {
                                    // Close the file

                                stream.Close();
                             //   stream.Dispose();

                             }

                            });

                }

        return (data);
    }

I call: PromptMe(); when the Start button is pressed at the beginning.
I call: if (Global.SaveDevice.IsReady){entries = LoadHighScores(HighScoresContainer, HighScoresFilename);} during the menu screen to try and display the highscore screen.
I call: SaveHighScore(); when game ends.
I've tried altering the struct code to a class but still no luck.
Any help greatly appreciated.

Anyone any ideas?

You have modified the SaveHighScores from the original source to open or create the XML file instead of always overwriting it, which leads to interesting errors when loading.
Say you play your game, save high scores, and the resulting XML file is 100 bytes in length. You then play again and overwrite the high scores, but this time the XML content is only 99 bytes in length (for whatever reason the data is shorter, smaller score, etc). Using open or create the serializer will write out 99 bytes, leaving that 1 last junk byte from the first save at the end of the XML file. This leads to XML parse errors the next time you try and load the scores, just like you are seeing. If you manually inspect the file contents when debugging my guess is you will see junk trailing your XML from this exact scenario.
You will have to delete the file and change the SaveHighScores method back to always create instead of open or create. This will ensure that the old file is always deleted prior to saving, avoiding this issue.

dadoo Games hit the nail right on the head.  Your problem is that you may be saving a smaller file into a larger one, causing many problems and headaches as you do so.
I second deleting your current save before you make a new one, so that you always have a fresh file.  Doing so will save you many, many headaches and, while not the best method, it is certainly the easiest.
If you're worried about ending up with corrupted saves, you could always make a copy of your current save before deleting it.  That way if it gets corrupted in any way, you can fall back on the older one.
So, the long and short of it when saving:

(Optional) Back up your current save.
Delete current save.
Create a new save with your current data.
(Optional) Check what saved against what you have on hand, to check if it saved correctly.

Doing so will ensure that the data you save will A.) Never crash due to having junk bytes and B.) You always correctly save your data.  A bit of extra work with my optional steps, but it helps in keeping users happier if it corrupts (as they don't lose everything) and it helps prevent corruption by checking if it saved correctly immediately afterwards.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
How do games like Minecraft generate entire worlds from a seed number?
I want to generate a completely unique world with biomes (like what Minecraft and similar games do). I don't understand how they generate these entire worlds from a single "seed" number. Can someone provide a basic overview of the technique?

Notch actually wrote a blog post about terrain generation, which is now completely obsolete since the new code's got biomes and FRACTALS and other such wizardry. There never was a part 2, either.

How do you generate random X from a seed?  a seed value is the initial state of a random number generator. In most programming languages, you can set this seed. For example, C uses srand(). If you don't specify a specific seed to start with, usually a timestamp value is used as the seed. That way, each time you run, the random numbers are different.
// C example
srand(1);
for(i=0; i<3; i++)
    printf("%d\n", rand());
srand(1);
for(i=0; i<3; i++)
    printf("%d\n", rand());

1270216262
1085377743
1481765933
1270216262
1085377743
1481765933

As you can see, whenever you seed with a certain value (I used 1 as a seed), the resulting random numbers are the same.
How do you create a minecraft-life world based on random numbers? Notch has a post about this.  Also, you can check out other people's tutorials on "minecraft-like worlds". I enjoyed this one, for example: Minecraft-like rendering in OpenGL 4. The basic idea is to use Perlin noise (or simplex noise). Here is a good question about noise functions: Understanding Perlin Noise

Actually, you wont be able to use Perlin Noise I'm afraid minecraft has over-hanging cliffs, caves and so on, and PN cannot into that.

Perlin noise is just a noise system which you can use as part of a larger terrain generation method. eg. You can use 3D perlin noise with an altitude-dependent threshold value to generate cliffs, caves, etc. (Edit - in fact, I see from the link in the answer that is exactly what Notch was doing at one point.)

+1 Kylotan. Here's the quote from Notch's blog: "Specifically, there’s no way for [2D Perlin heightmap] to generate any overhangs.
So I switched the system over into a similar system based off 3D Perlin noise. Instead of sampling the “ground height”, I treated the noise value as the “density”, where anything lower than 0 would be air, and anything higher than or equal to 0 would be ground. "

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
What are some good game programming short courses?
I'm from Brazil, and I want to take a short course on game programming, 2 months at most, in a country that lectures are given in english. I'm almost a BSc in Computer Science alredy.
Can you tell me what you think about this courses?
What are some good courses in that format?

@Bane isn't this site the internet too? confused...

Can you tell me what you think about this courses? What are some good courses in that format?

You haven't told us much about, what is this this course you are talking about. So, really there is not much room for us to suggest you the right and/or wrong. Like everybody else I am going to take the generic route.
Another thing I want to point out is, you haven't told us about your skill level. Let me assume that you are a good programmer with a fair knowledge on algorithm.
1st Scenario
Ok, now I am going to chunk up my answer on different stages. And first I am going to assume you are the main programmer and programmers art is gonna flood in. Most of the time you will be busy in reading/writing code and some sample asset will be ok for your game.
When you start developing game you will notice how different it is form solving individual problem found on ACM, TopCoder or CodeChef. As I have already assumed you are no guru level programmer, I am taking this as a granted that you are going to work with different modules(for graphics, for physics, for audio for etc) and gonna marge them in a single framework that suits your need.
Here is the catch, most of the time you will be going to good/bad documented/commented code to figure out how they work and or how to make them work. So, here the skill you will be needed is the patience and the necessary skill to going through others code and of course the mathematical knowledge to understand the implementation.(With a good debugging skill.)
So, now you answer me, does this 2 month course is going to help you to have any of these skills? If you are a good/moderate programmer already, then you already know this and of course wont be needing any extra guideline(Even if you need, you will be able to pick it up along the way). These are the bread and butter of any programmers life.
Give yourself a checkride, Making anything simple using any of the following engines :

OGRE : As the name says its a open graphics rendering engine. Its not a complete solution for game development. Its just provided the rendering module and all other modules, like physics and networking, have to marge by you.Which is not a trivial task. Its based on C++.

jMonkeyEngine : This is a complete solution for game development. Its based on java. I guess you are more inclined to learn the game development terminologies, so starting with this one will pay off. Its shader based, with  little fixed function rendering support. So, when you are wroking with this engine, you will learn all the high end thingies that will come in handy in the long run, on any engine that you end up with. Its easy to start with.

Try to make something, using any of this 2 engines. Upon successful completion you will find out your skill level and demand of any training by yourself.
2nd Scenario
Now, let me assume that you are the only programmer and want to make games instead of messing around with lots of libraries. High quality asset is not a low priority here. You want an magic box that does all the boring stuff for you so concentrate on the game logic itself.
Here are the options,

Unreal Development Kit
Unity
CryEngine

Unreal development is notorious for its learning curve. But I've found it not that hard once you understand the underlying structure. Here you have top notch editor for world building, cinematic editor, particle editor, visual game logic constructor etc etc. All you need to make a game. Unlike OGRE or jMonkeyEngine, here you only have to code when you want to specify a veery specific behaviour to a particular entity. Other then that, most of the things are just drag and drop, point and click. Its fun, but takes away the pleasure of programming.
Roughly speaking Unity is like UDK. Most of these are a high level game development kit that just requires some fundamental understand current tech jargon.CryEngine is similar to above 2 mentioned. You have to try out all of them(dont worry, you will feel right at home after a few hour spending with them)
Ok, now these game development toolkit are a complete package with different use restrictions. And all of these tools have EXTENSIVE documentation hooked up in their website. Massive Community. Regular Update. Just about almost everything any game developer could ask for. (of course I am talking about beginners)
Make anything using these toolkit. Give a checkride. See how fast/easy/comfortable you feel with these. Then  ask yourself again, do you need to have a training to get used to with some tools? If you can't even teach yourself a simple tool where everything is almost ready, then I would suggest you to back off from the whole game development thingy.
Now ask yourself again
After doing any of these 2 tests you will automatically understand your strength and weakness as a game programmer/developer. Along the way you will learn all the necessarily technical knowledge required. At first things might look hard, yes as beginners its always a bit steep to step into the game programming/developing realm. But, trust me it very rewarding when you get a hold onto something that you did't knew half an hour ago. But, if you get yourself enroll into a training(of 2 month only), yes those jargon will sound familiar to you when you read the doc, but that's not a good way to start.
Do you need a 2 month training?
Not necessarily. Just start with something. Make something. On that way you will find out what you know and what don't. Always keep pushing the limit. And if you really want to learn form ABCD...well, what can I say...Google a bit. Read whatever you find.
Just a foot note, don't waste you time reading OpenGL 1 tutorials. :)

If you're almost a B.Sc., then take that knowledge today, get a couple good books, and start leveraging the vast resources across the web to learn the basics of game development. (Welcome to the industry.) If you haven't learnt enough about technical programming during your bachelors studies to do that, then short courses aren't going to help you very much anyway.
The point is, from where you stand now, you should already have the most important knowledge you need to get going -- without paying someone else to teach you things you can easily learn yourself.
You get out what you put in, and that applies to short, cheap courses as much as anything else.

Other than the technical part of the course, I have networking in mind, because you know, here in Brazil we don't have too much opportunities to meet people that are really interested in game development. What do you think about this?

Networking, and the experience of game development within a team, that's something else. If that's one of your goals right now, then maybe you should go for a course, because it's not something you'll get from a book. Although the internet does offer opportunities to work in teams as a game developer. Gamedev.net is one such place to join a team; there are many others. Just a thought.

I wrote and presented a short crash course on the world of game programming; you can find the slides here: http://iki.fi/sol/gpc/
..and the practical stuff here: http://iki.fi/sol/gp/
Apart from that, I wholeheartedly agree with Nick, there. It's also best not to do this alone; find same-minded people and start a local game programming club! =)

Agreed; OP should take that money that would have have been spent on travel and courses, and spend it on renting out a place to hold the club, or snacks if done in the garage/basement!

That's indeed a good way to spend this money.

Your slides are so useful!

Let me start by saying, I can not answer your question.  I do not know any courses in the two month range that would influence me (as someone with decision making authority) to hire you which I assume is ultimately your goal.
There are educational programs that provide concentrated programs related to game development.  These types of concentrated programs can provide canidates that have a useful base exposure to the problems of game programming...they are not a guarantee that you personally will finish the program as an person desirable to the game industry.
As your subsequent responses indicate, networking is a consideration...but honestly any company that is hiring is going to consider a good candiate.  So...what makes a good candidate?
Someone who...

is interested in solving problems
solves problems outside of class and finds it to be "fun" (sample programs you personally developed are a plus, even if they do not work show me the code and you might impress me)
is curious
learns on their own (sorry, school only teaches you a fraction of what you need to know and how you need to approach problems).  READ STUFF!!!  EXPERIMENT!!!  There are numerous articles on this site of books and basic concepts of which you should be at least aware.
understand after gradutation you really know nothing.   A degree (even a PhD) does not mean you know how to program for a environment requiring a networked, asynchronous application development involving high performance networking, persistence and graphical (client) layers in a mid-large sized team.  Programming for Massive Multiplayer Online games combines all of the really hard computer science problems you have studied (and a bunch of others you have never heard of...) in spades.  No shame here, after decades in the industry we are still learning stuff too!
I want to know that you can THINK.  I will ask you oddball questions in an interview and listen to your response.  I do not care if you are "technically" correct...how do YOU solve problems is what matters.  You get good at this...by solving problems.
Game programming tends to be a meritorcacy, I (we) do not believe we know everything.  Show me I am wrong, and I'll listen (but you better be able to prove it with stats...and I'll rebut with other companies trying to do X and the problems they encountered).
Be humble, but stand your ground when you strongly believe in something.  No matter what you think you know, someone will always know more...but sometimes you might be right too.  At the end of the day, accept sometimes your manager might have other considerations that affect the ultimate decision.
We do not care if you have an idea for a game design...ideas are pennies per dozen.  Execution of the idea is what matters.

As an unknown, what YOU KNOW and CAN DO is much more imporant to me than who you know.  At my company we have a standarized test which we hope a slightly trained C++ monkey (most of whom fail...which I fear reflects badly on the educational establishment) could pass and the multiple levels of interviews that test the extents of a candidate's personal knowledge.  We do not care if the candidate knows exactly how C++ templates work or all of the stupid edge conditions that some (dumb) interview "tests" ask.  Know what you do not know, and know how you could expand your knowledge to cover that weakness.
There are a variety of articles on the over reliance on "riddles" and obscure language trivial being examples of lazy/poor Human Resources filtering mechanisms...you really do not want to work there anyway.
Know what you want to become...work towards that goal...and prove you know what you know.  I do not care if you do not know everything (I know you do not...so do not try to lie about it), prove you know how to ask (relevant) questions and know how to take feedback and learn.


text:
Minecraft-style player-gound collision detection
The title pretty much says it all... (Minecraft is a game consisting of evenly-spaced cubes for terrain, like voxels)
Note: I am using C# XNA.
I am pretty sure AABB is the way to go, yet I don't know how to implement it. I admit, I'm almost looking for code, but theories/ideas are very welcome.
Important capabilities of my code: I have a function that can get a block anywhere in the world, and get a BoundingBox for that cube. Hence, I have created a BoundingBox for the player to collide with those cubes. My idea was to get the blocks around the player (maybe 4x6x4) and test against those.
The problems I have been having: Say the world is a flat plane. If I use the method of go the shortest distance out, then if the player is slightly clipped into the ground (from gravity), but even slighter into the next block over, then the player will be pushed sideways (and so cannot walk along ground). Of course, this is assuming I react to every block intersected. Another problem is knowing which direction to go (aka negative x or positive). That takes me to my final problem- Getting the amount of intersection, in the correct direction (+ or -) has been tough for me.
I hope I haven't been too hard to understand, I'm not too good at explaining things... And if this question has already been asked, I'm sorry, I looked for it... for 3 days straight.
One last thing, if someone knows exactly how minecraft does it, or has source (I know MC modders have the source, how else would they mod), please point me to it.

If you have mc, get mcp and see for yourself. :)

This is my 2D AABB approach to the solution. It should translate easily into 3D, simply by adding the Z axis. Replace "Left" and "Right" with "West" and "East", add "North" and "South", and keep "Up" and "Down". "West" and "East" would be X, "North" and "South" would be Y, and "Up" and "Down" should then be Z.
What I do is pick all the tiles that intersect with the entity based on size, and then keep it as tile start and end positions. After that, I construct two lists of tiles based on direction, holding only solid tiles. The corner is kept separate, to avoid the list having the same point twice which would be the corner.
I then iterate the list of solid tiles, and then fix velocity according if we intersect with the tile in the next position.
The corner is a special case in my engine, rather than increase the steps, I just rule you always land on top.
Feel free to ask questions, though I'd encourage you to try and rewrite it for your own engine, to get a better grasp on what the function is doing.
...
    private Vector2 ApplyTileCollision(Vector2 velocity)
    {
        Vector2 nextPosition = this.position + velocity;

        Int32 startx = (Int32)(((Single)position.X) / Tile.SIZE) - 1;
        Int32 endx = (Int32)(((Single)position.X + this.Width - 0.0001f) / Tile.SIZE) + 1; // because of float imprecision, we subtract 0.0001f.
        Int32 starty = (Int32)(((Single)position.Y) / Tile.SIZE) - 1;
        Int32 endy = (Int32)(((Single)position.Y + this.Height - 0.0001f) / Tile.SIZE) + 1; // because of float imprecision, we subtract 0.0001f.

        // these variables are filled with only solid tiles
        List<Point> horizontalWall = new List<Point>();
        List<Point> verticalWall = new List<Point>();
        Point ?corner = null;

        if (this.IsMovingRight)
        {
            // we use starty + 1 to remove the corner
            for (Int32 y = starty + 1; y < endy; y += 1)
                if (realm.GetTile(endx, y).IsSolid)
                    verticalWall.Add(new Point(endx, y));
        }
        else if (this.IsMovingLeft)
        {
            // we use starty + 1 to remove the corner
            for (Int32 y = starty + 1; y < endy; y += 1)
                if (realm.GetTile(startx, y).IsSolid)
                    verticalWall.Add(new Point(startx, y));
        }

        if (this.IsMovingDown)
        {
            // we use startx + 1 to remove the corner
            for (Int32 x = startx + 1; x < endx; x += 1)
                if (realm.GetTile(x, endy).IsSolid)
                    horizontalWall.Add(new Point(x, endy));
        }
        else if (this.IsMovingUp)
        {
            // we use startx + 1 to remove the corner
            for (Int32 x = startx + 1; x < endx; x += 1)
                if (realm.GetTile(x, starty).IsSolid)
                    horizontalWall.Add(new Point(x, starty));
        }

        if (this.IsMovingLeft && this.IsMovingUp)
        {
            if (realm.GetTile(startx, starty).IsSolid)
                corner = new Point(startx, starty);
        }
        else if (this.IsMovingRight && this.IsMovingUp)
        {
            if (realm.GetTile(endx, starty).IsSolid)
                corner = new Point(endx, starty);
        }
        else if (this.IsMovingLeft && this.IsMovingDown)
        {
            if (realm.GetTile(startx, endy).IsSolid)
                corner = new Point(startx, endy);
        }
        else if (this.IsMovingRight && this.IsMovingDown)
        {
            if (realm.GetTile(endx, endy).IsSolid)
                corner = new Point(endx, endy);
        }

        foreach (Point point in verticalWall)
        {
            // if our next position would collide with the tile, we fix velocity.
            if (nextPosition.X + this.Width > point.X * Tile.SIZE &&
                nextPosition.X < point.X * Tile.SIZE + Tile.SIZE)
            {
                if (this.IsMovingRight)
                {
                    velocity.X = point.X * Tile.SIZE - (position.X + this.Width);
                }
                else if (this.IsMovingLeft)
                {
                    velocity.X = (point.X * Tile.SIZE + Tile.SIZE) - position.X;
                }
            }
        }

        foreach (Point point in horizontalWall)
        {
            // if our next position would collide with the tile, we fix velocity.
            if (nextPosition.Y + this.Height > point.Y * Tile.SIZE &&
                nextPosition.Y < point.Y * Tile.SIZE + Tile.SIZE)
            {
                if (this.IsMovingDown)
                {
                    velocity.Y = point.Y * Tile.SIZE - (position.Y + this.Height);
                }
                else if (this.IsMovingUp)
                {
                    velocity.Y = (point.Y * Tile.SIZE + Tile.SIZE) - position.Y;
                }
            }
        }

        // in case we only have a corner to consider, we rule that we land on top of it, or hit the bottom of it.
        if (corner.HasValue && verticalWall.Count == 0 && horizontalWall.Count == 0)
        {
            // if our next position would collide with the tile, we fix velocity.
            if (nextPosition.Y + this.Height > corner.Value.Y * Tile.SIZE &&
                nextPosition.Y < corner.Value.Y * Tile.SIZE + Tile.SIZE &&
                nextPosition.X + this.Width > corner.Value.X * Tile.SIZE &&
                nextPosition.X < corner.Value.X * Tile.SIZE + Tile.SIZE)
            {
                if (this.IsMovingDown)
                {
                    velocity.Y = corner.Value.Y * Tile.SIZE - (position.Y + this.Height);
                }
                else if (this.IsMovingUp)
                {
                    velocity.Y = (corner.Value.Y * Tile.SIZE + Tile.SIZE) - position.Y;
                }
            }
        }

        return velocity;
    }
...

Wow. Ill have to study this a bit. So you split up horizontal and vertical detection into two parts... And you use velocity to determine which direction to react to... interesting... Thanks, though. Ill leave it unaccepted for a bit to see if anyone else has suggestions.

@khyperia, Yeah, that's the idea, also, if I'm not moving in a direction, there are no checks performed in that direction. A key element to this detection, is I check both directions before actually moving the entity, which is a common issue people run into. I also fix the velocity rather than the position, making sure the entity never enters the space of the tile.


text:
How can I implement voxel-based lighting with occlusion in a Minecraft-style game?
I am using C# and XNA. My current algorithm for lighting is a recursive method. However, it is expensive, to the point where one 8x128x8 chunk calculated every 5 seconds.

Are there other lighting methods that will make variable-darkness shadows?
Or is the recursive method good, and maybe I am just doing it wrong?

It just seems like recursive stuff is fundamentally expensive (forced to go through around 25k blocks per chunk). I was thinking about using a method similar to ray tracing, but I have no idea how this would work. Another thing I tried was storing light sources in a List, and for each block getting the distance to each light source, and using that to light it to the correct level, but then lighting would go through walls.
My current recursion code is below. This is called from any place in the chunk that does not have a light level of zero, after clearing and re-adding sunlight and torchlight.
world.get___at is a function that can get blocks outside of this chunk (this is inside the chunk class). Location is my own structure that is like a Vector3, but uses integers instead of floating point values. light[,,] is the lightmap for the chunk.
    private void recursiveLight(int x, int y, int z, byte lightLevel)
    {
        Location loc = new Location(x + chunkx * 8, y, z + chunky * 8);
        if (world.getBlockAt(loc).BlockData.isSolid)
            return;
        lightLevel--;
        if (world.getLightAt(loc) >= lightLevel || lightLevel <= 0)
            return;
        if (y < 0 || y > 127 || x < -8 || x > 16 || z < -8 || z > 16)
            return;
        if (x >= 0 && x < 8 && z >= 0 && z < 8)
            light[x, y, z] = lightLevel;

        recursiveLight(x + 1, y, z, lightLevel);
        recursiveLight(x - 1, y, z, lightLevel);
        recursiveLight(x, y + 1, z, lightLevel);
        recursiveLight(x, y - 1, z, lightLevel);
        recursiveLight(x, y, z + 1, lightLevel);
        recursiveLight(x, y, z - 1, lightLevel);
    }

Something is horribly wrong if you're doing 2 million blocks per chunk - especially since there's only 8,192 blocks actually in an 81288 chunk. What could you be doing that you're going through each block ~244 times? (could that be 255?)

I did my math wrong. Sorry :P. Changing. But the reason why you need to go though so many is you have to "bubble out" from every block until you hit a light level greater than the one your setting. That means every block might get overwritten 5-10 times before it hits actual light level. 8x8x128x5 = a lot

How are you storing your Voxels? That is important to reduce traversal times.

Can you post your lighting algorithm? (you ask if you're doing it badly, we have no idea)

I am storing them in a array of "Blocks", and a Block consists of a enum for material, plus a metadata byte for future use.

First: if (y < 0 || y > 127 || x < -8 || x > 16 || z < -8 || z > 16) -- why the "16", not "8"? Second: All these new Location(...) calls got to hurt for no good reason; why not change the method signature to recursiveLight(Location, byte) and add up(), down(), south(), west() and so on methods to the Location class to get the neighbours? Third: Use raytracing. Fourth: profile, profile, profile.

Someone said to answer your own question if you figured it out, so yeah. Figured out a method.
What I am doing is this: First, create a 3d boolean array of "already changed blocks" overlayed over the chunk. Then, fill in sunlight, torchlight, etc (just lighting up the block that its on, no flood filling yet). If you changed something, hit the "changed blocks" in that location to true. Also go though and change every solid block (and therefore no need to calculate lighting for) to "already changed".
Now for the heavy stuff: Go though the entire chunk with 16 passes (for each light level), and if its 'already changed' just continue. Then get the light level for the blocks around itself. Get the highest light level of them. If that light level equals the current passes' light level, set the block you are on to the current level, and set "already changed" for that location to true. Continue.
I know its kind of complicated, I tried to explain my best. But the important fact is, it works and is fast.

Every light has a precise (floating point) position, and bounding sphere defined by a scalar light radius value, LR.
Every voxel has a precise (floating point) position at it's centre, which you can easily calculate from its position in the grid.
Run through every one of 8192 voxels once only, and for each, see if it falls within each of N lights' spherical bounding volumes by checking |VP - LP| < LR, where VP is the voxel's position vector relative to origin and LP is the light's position vector relative to origin. For each light whose radius the current voxel is found to be in, increment it's light factor by the distance from the light centre, |VP - LP|. If you normalise that vector and then get its magnitude, this will be in range 0.0->1.0. The maximum light level a voxel can reach is 1.0.

The runtime is O(s^3 * n), where s is the side length (128) of your voxel region and n is number of light sources. If your light sources are static, this is no problem. If your light sources move in real time, you can work solely on deltas rather than recalculating the whole shebang every update.
You could even store the voxels which each light affects, as references within that light. This way, when the light moves or is destroyed, you can go through just that list, adjusting light values accordingly, rather than having to traverse the entire cubic grid again.

If I understood his algorithm correctly, he tries to do some sort of pseudo-radiosity, by allowing light to reach far-away places even if it means it has to go "around" some corners. Or, in other words, a flood-fill algorithm of the "empty" (non-solid) spaces with a bounded max distance from the origin (the light source) and the distance (and from it, light attenuation) being calculated according to the shortest path to the origin. So - not quite what you propose currently.

Thanks for the detail @MartinSojka. Yep sounds more like an intelligent flood fill. With any attempt at global illumination, costs tend to be high even with clever optimisations. Thus it's good to attempt these problems in 2D first, and if they're even remotely expensive, know that you'll have a definite challenge on your hands in 3D.

Minecraft itself doesn't do the sunlight this way.
You simply fill the sunlight from the top to the bottom, every layer is gathering light from neighbor voxels in the previous layer with attenuation. Very fast - single pass, no lists, no data structures, no recursion.
You have to add torches and other non-flooding lights in a later pass.
There are so many other ways to do this, including fancy directional light propagation etc. , but they are obviously slower and you have to figure out if you want to invest in the additional realism given those penalties.

Wait, so how exactly does Minecraft do it? I couldn't get exactly what you were saying... What does "every layer is gathering light from neighbor voxels in the previous layer with attenuation" mean?

Start with the topmost layer (slice of constant height). Fill it with sunlight. Then go to the layer below, and every voxel there gets its illumination from the closest voxels in the previous layer (above it). Put zero light in solid voxels. You have a couple of ways to decide the "kernel", the weights of the contributions from the voxels above, Minecraft uses the maximum value found, but decreases it by 1 if the propagation is not straight down. This is the lateral attenuation, so unblocked vertical columns of voxels will get the full sunlight propagation and light bends around corners.

Please note that this method is in no way based on any real physics whatsoever :) The main problem is that you are in essence trying to approximate a non-directional light (the atmospheric scattering) AND bouncing radiosity with a simple heuristic. It looks pretty good.

What about a "lip" that hangs over, how does light get up there? How does light travel in an upward direction? When you only go top-down, then you cannot go back upwards to fill in overhangs. Also torches/other light sources. How would you do this? (they could only go down!)

@khyperia: Good question! Maybe minecraft does two passes? One down one up? Still it would be nice to hear an answer to that from Bjorn

@Felheart: it was a while now that I looked at this, but in essence there is a minimum ambient light level that is usually enough for the underneath of overhangs so they are not completely black. When I implemented this myself, I did add a second pass from down->up, but I didn't really see any big aesthetic improvements compared to the ambient method. Torches/pointlights have to be handled separately - I think you can see the propagation pattern used in MC if you put a torch on the middle of a wall and experiment a bit. In my tests, I propagate them in a separate lightfield then add.

Is there an example implementation of this method somewhere? I'm having a lot of trouble trying to implement it based purely on the worded explanation. The code I currently have looks something like this: https://gist.github.com/Ethan-Bierlein/d26236aa6920e1958226668e930a8eff

Okay, so I made a few minor changes (which can be found here) which caused it to start generating semi-correct shadows, but also produced a lot of awful-looking side effects. Any idea as to what's wrong with my implementation?

I'd suggest an algorithm that sort of combines your multi-pass solution with the original recursive method, and is most likely quite a bit faster than either of them.
You'll need 16 lists (or any kind of collections) of blocks, one for each light level.  (Actually, there are ways to optimize this algorithm to use fewer lists, but this way is easiest to describe.)
First, clear the lists and set the light level of all blocks to zero, and then initialize light sources as you do in your current solution.  After (or during) that, add any blocks with a non-zero light level to the corresponding list.
Now, go through the list of blocks with light level 16.  If any of the blocks adjacent to them have light level less than 15, set their light level to 15 and add them to the appropriate list.  (If they were already on another list, you can remove them from it, but it doesn't do any harm even if you don't.)
Then repeat the same for all the other lists, in decreasing order of brightness.  If you find that a block on the list already has a higher light level than it should for being on that list, you can assume it was already processed and not even bother checking its neighbors.  (Then again, it might be faster to just check the neighbors — it depends on how often that happens.  You should probably try it both ways and see which way is faster.)
You may note that I haven't specified how the lists should be stored; really pretty much any reasonable implementation ought to do it, as long as inserting a given block and extracting an arbitrary block are both fast operations.  A linked list should work, but so would any halfway decent implementation of variable-length arrays too.  Just use whatever works best for you.

Addendum: If most of your lights don't move very often (and neither do the walls), it might be even faster to store, for each lit block, a pointer to the light source that determines its light level (or to one of them, if several are tied).  That way, you can avoid global lighting updates almost entirely: if a new light source is added (or an existing one brightened), you only need to do a single recursive lighting pass for the blocks around it, while if one is removed (or dimmed), you only need to update those blocks that point to it.
You can even handle wall changes this way: when a wall is removed, just start a new recursive lighting pass at that block; when one is added, do a lighting recalc for all blocks that point to the same light source as the newly walled block.
(If several lighting changes happen at once — e.g. if a light is moved, which counts as a removal and an addition — you should combine the updates into a single one, using the algorithm above.  Basically, you zero out the light level of all blocks pointing to removed light sources, add any lit blocks surrounding them as well as any new light sources (or existing light sources in the zeroed out areas) to the appropriate lists, and run the updates as above.)


text:
how can I specify interleaved vertex attributes and vertex indices
I'm writing a generic ShaderProgram class that compiles a set of Shader objects, passes args to the shader (like vertex position, vertex normal, tex coords etc), then links the shader components into a shader program, for use with glDrawArrays.
My vertex data already exists in a VertexBufferObject that uses the following data structure to create a vertex buffer:
class CustomVertex
{
public:
float   m_Position[3];      // x, y, z      // offset 0, size = 3*sizeof(float)
float   m_TexCoords[2];     // u, v         // offset 3*sizeof(float), size = 2*sizeof(float)
float   m_Normal[3];        // nx, ny, nz;
float   colour[4];          // r, g, b, a
float   padding[20];        // padded for performance
};

I've already written a working VertexBufferObject class that creates a vertex buffer object from an array of CustomVertex objects.  This array is said to be interleaved.  It renders successfully with the following code:
void VertexBufferObject::Draw()
{
if( ! m_bInitialized )
    return;

glBindBuffer( GL_ARRAY_BUFFER,          m_nVboId );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER,  m_nVboIdIndex );

glEnableClientState( GL_VERTEX_ARRAY );
glEnableClientState( GL_TEXTURE_COORD_ARRAY );
glEnableClientState( GL_NORMAL_ARRAY );
glEnableClientState( GL_COLOR_ARRAY );

glVertexPointer( 3, GL_FLOAT, sizeof(CustomVertex), ((char*)NULL + 0) );
glTexCoordPointer(3, GL_FLOAT, sizeof(CustomVertex), ((char*)NULL + 12));
glNormalPointer(GL_FLOAT, sizeof(CustomVertex), ((char*)NULL + 20));
glColorPointer(3, GL_FLOAT, sizeof(CustomVertex), ((char*)NULL + 32));

glDrawElements( GL_TRIANGLES, m_nNumIndices, GL_UNSIGNED_INT, ((char*)NULL +  0) );

glDisableClientState( GL_VERTEX_ARRAY );
glDisableClientState( GL_TEXTURE_COORD_ARRAY );
glDisableClientState( GL_NORMAL_ARRAY );
glDisableClientState( GL_COLOR_ARRAY );

glBindBuffer( GL_ARRAY_BUFFER,          0 );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER,  0 );
}

Back to the Vertex Array Object though.  My code for creating the Vertex Array object is as follows.  This is performed before the ShaderProgram runtime linking stage, and no glErrors are reported after its steps.
// Specify the shader arg locations (e.g. their order in the shader code)
for( int n = 0; n < vShaderArgs.size(); n ++)
    glBindAttribLocation( m_nProgramId, n, vShaderArgs[n].sFieldName.c_str() );

// Create and bind to a vertex array object, which stores the relationship between
// the buffer and the input attributes
glGenVertexArrays( 1, &m_nVaoHandle );
glBindVertexArray( m_nVaoHandle );

// Enable the vertex attribute array (we're using interleaved array, since its faster)
glBindBuffer( GL_ARRAY_BUFFER,          vShaderArgs[0].nVboId );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER,  vShaderArgs[0].nVboIndexId );

// vertex data
for( int n = 0; n < vShaderArgs.size(); n ++ )
{
    glEnableVertexAttribArray(n);

    glVertexAttribPointer(
        n,
        vShaderArgs[n].nFieldSize,
        GL_FLOAT,
        GL_FALSE,
        vShaderArgs[n].nStride,
        (GLubyte *) NULL + vShaderArgs[n].nFieldOffset
    );

    AppLog::Ref().OutputGlErrors();
}

This doesn't render correctly at all.  I get a pattern of white specks onscreen, in the shape of the terrain rectangle, but there are no regular lines etc.  Here's the code I use for rendering:
void ShaderProgram::Draw()
{
using namespace AntiMatter;

if( ! m_nShaderProgramId || ! m_nVaoHandle )
{
    AppLog::Ref().LogMsg("ShaderProgram::Draw() Couldn't draw object, as initialization of ShaderProgram is incomplete");
    return;
}

glUseProgram( m_nShaderProgramId );
glBindVertexArray( m_nVaoHandle );
glDrawArrays( GL_TRIANGLES, 0, m_nNumTris );

glBindVertexArray(0);
glUseProgram(0);
}

Can anyone see errors or omissions in either the VAO creation code or rendering code?
thanks!

Why is a class called ShaderProgram responsible for storing and rendering a mesh? There seems to be some confusion about what should be responsible for what here.

Yes, you're absolutely right, there is confusion there.  The source is in an early iteration, and now that you & Sam H have pointed me in the right direction, I see the error in my design.  I'm sure I'll address it!

What on earth got you to insert a padding of 20 floats (80 bytes)? Such a large memory-overconsumption surely kills any possible alignment benefits. 4 floats (16 bytes) would have sufficed for a 64 byte alignment, which should be enough (if even neccessary).

GPUs usually want 128-bit aligned data (that's 32 bytes, or 4 floats). No padding is necessary here. It is possible that freefallr confused bits and bytes.

If you want to use VAOs with index buffers, you need glDrawElements() instead of glDrawArrays(). What you are seeing is probably all your vertices being rendered as triangles, as if there was no index buffer.


text:
Where can I read about techniques used in NES-era games?
I enjoy reading about techniques used in NES-era games. Is there a blog or site that is pretty much dedicated to this topic?
For example, here is an article talking about Pac-Man, and another about the movement in The Legend of Zelda.

If it makes sense to make this a CW and a repository of articles from across the web, that works too.

What are you looking for? Most techniques specific to NES-era games are because of the specific hardware such as hardware sprites, dma, and trade offs between buffer sizes, sprite memory, and colors pallet size. The hardware limitations pretty much dictated minimalism as the design pattern.

I added a couple examples. I'm not looking for any specific thing. I just enjoy reading about how they were done. Sometimes it inspires me, and other times it gives me ideas.

Is this fundamentally any different from this question?  http://gamedev.stackexchange.com/questions/443/how-were-8-bit-and-16-bit-games-developed

I didn't see that when searching, but I think it is. That question seems to be around the process. "Are there 'famous' tools? What was the most used programming language? how were they deployed into cartridges?" I'm looking for general coding techniques. Preferably language agnostic, but that doesn't really matter. If you take a look at the links I posted about you will see what I mean.

That kind of question isn't a very good format for this site. It would be better to bring up specific questions or a specific area of a game you want improvement on instead of looking for random reading material.

How is this not a good question? It is very specific, and not a discussion

Both links now appear to be broken. Do you know of other places where the articles can be found?

I'm looking for general coding techniques. Preferably language agnostic, but that doesn't really matter. If you take a look at the links I posted about you will see what I mean.

The NES specifically is very old, so you're not going to find too too much on that. This past year at the Game Developers Conference had a number of classic game Postmortems, which sounds more like what you're looking for. You can find many of them freely in the GDC Vault.
http://www.gdcvault.com/free/gdc-11
If you want something more, the GameBoy survived for a really long time (I worked on and shipped a commercial game in 2001 that still sold > 200,000 copies), specifically the GameBoy Color had graphics hardware on par with the original NES (better actually). For the most part, a lot of old game consoles and old computers were similar in capability. The only thing that set apart a Nintendo from a Commodore 64 was support for a larger number of on screen sprites, and registers for controlling the horizontal and vertical scrolling of the character map (background). Everything until 3D accelerated consoles came along (N64, PS1) was based around more and more advanced forms of hardware sprites and scrollable character maps. Character map hardware was originally designed for displaying text characters, but since you could change the character glyphs, many developers started referring to them tiles and tile hardware.
I do have one suggested link about a NES game, Grand Theiftendo, a homebrew game by a friend of mine:
http://retrocityrampage.com/blog/2011/05/see-rcr-precursor-grand-theftendo-in-action/
If you like what you see, you should check out Retro City Rampage, a dramatically improved commercial version of the game he's been working on.
Above is how many classic game developers had to work... literally, by hard-wiring and creating custom hardware to interface with devices like the NES. If you were an official Nintendo Developer, they would send you an officially pre-modified box that you could test on instead (since not everyone has the technical know-how to wire in and flash flash-memory). And programming wise, nearly everything was done in Assembly (6502 or z80, depending on the device). C compilers took a long time before they became practical for embedded devices.
In the last decade though, things have been more streamlined. Flash carts became available; These were devices you could plug in to a cart programmer (writer), and upload a game binary right to the cart. Then you could plug the cart right in, power on the device, and test. This process can be rather slow though, so on GameBoy Color at least, many developers got familiar with using emulators to test games. Compile, run on emulator. Even if an emulator wasn't 100% accurate, they were often good-enough to initially test. You could flash a cart after you were sure something was working, then sit back and try it as it should be experienced (on device).
Emulators were only ever good for simulating really old hardware, GameBoy and NES era being ideal candidates. Today though, now that everything is 3D accelerated and pushes polygons, it's far more practical to write cross-platform code. Most devices support OpenGL ES, which is an API that is sooooo close to OpenGL, in fact, you can treat GL ES as a subset of regular OpenGL. I.e. You can write games that run on both by writing them against the OpenGL ES spec.
That's my brief on classic->modern gamedev techniques. Hopefully that gives you some insight where to dig for more. Alot of information is out there, you just have to know what you're looking for.

Its worth checking Farat's page especially for NES and Gameboy architecture pages.


text:
vector rotations for branches of a 3d tree
I'm attempting to create a 3d tree procedurally.  I'm hoping that someone can check my vector rotation maths, as I'm a bit confused.
I'm using an l-system (a recursive algorithm for generating branches).
The trunk of the tree is the root node.  It's orientation is aligned to the y axis.
In the next iteration of the tree (e.g. the first branches), I might create a branch that is oriented say by +10 degrees in the X axis and a similar amount in the Z axis, relative to the trunk.
I know that I should keep a rotation matrix at each branch, so that it can be applied to child branches, along with any modifications to the child branch.
My questions then:
for the trunk, the rotation matrix - is that just the identity matrix * initial orientation vector ?
for the first branch (and subsequent branches)  - I'll "inherit" the rotation matrix of the parent branch, and apply x and z rotations to that also.
e.g.
using glm::normalize;
using glm::rotateX;
using glm::vec4;
using glm::mat4;
using glm::rotate;

vec4 vYAxis     = vec4(0.0f, 1.0f, 0.0f, 0.0f);
vec4 vInitial   = normalize( rotateX( vYAxis, 10.0f ) );

mat4 mRotation  = mat4(1.0);

// trunk rotation matrix = identity * initial orientation vector
mRotation *= vInitial;

// first branch = parent rotation matrix * this branches rotations
mRotation *= rotate( 10.0f, 1.0f, 0.0f, 0.0f );     // x rotation
mRotation *= rotate( 10.0f, 0.0f, 0.0f, 1.0f );     // z rotation

Are my maths and approach correct, or am I completely wrong?
Finally, I'm using the glm library with OpenGL / C++ for this.  Is the order of x rotation and z rotation important?

just test your code and see the results, if there was any problem ask how to solve them

From what I can see your approach is good, and your math seems alright as well. I would compile the code and see what the result is to make sure though.

well, my l-system code compiles okay, but it'll be a while before I can display anything on-screen.  I'll need to write the code that utilizes the l-system to draw a tree before I can tell if anything is wrong!


text:
Simplest way to generate a random path
What's the simplest way to generate a random "path" for a level in a game? I don't know what search terms I should use to read more. I've looked into maze generation but thats not quite right.
The end result should look like this:

For a more "controlled" random, you might want to use something akin to Perlin Noise.

As long as you don't want to go "back", meaning that your path goes only into a single direction (let's assume it is going downwards on your image), you can use the following C# code to easily generate those paths:
[Flags]
public enum Direction
{
  Down=1,
  Left=2,
  Right=4
}

public class Path : List<Direction> {}

public Direction GetNewDirection(Direction allowed, Random rnd)
{
  Direction newd;
  int maxd = Enum.GetValues(typeof(Direction)).Length;
  int[] vals = (int[])Enum.GetValues(typeof(Direction));
  do
  {
  var t = rnd.Next(0,maxd);
   newd = (Direction) vals[t];
  }
  while ((newd & allowed) == 0);
  return newd;
}

public Path GenerateRandomPath(int startx, int starty, int endx, int endy, double prob)
{
   Path newpath = new Path();
   Random rnd = new Random();

   int curx = startx; int cury = starty; Direction curd = Direction.Right;
   Direction newd = curd;

   while (!(curx == endx && cury == endy))
   {
     if (rnd.NextDouble() <= prob) // let's generate a turn
     {

       do
       {
        if (curx == endx) newd = GetNewDirection(Direction.Left | Direction.Down, rnd);
        else if (cury == endy) newd = Direction.Right;
        else if (curx <= 0) newd =  GetNewDirection(Direction.Right | Direction.Down, rnd);
        else newd =  GetNewDirection(Direction.Right | Direction.Down | Direction.Left, rnd);

       }
       while ( (newd | curd) == (Direction.Left | Direction.Right)); // excluding going back

       newpath.Add(newd);
       curd = newd;
       switch(newd)
       {
        case Direction.Left:
          curx--;
          break;
        case Direction.Right:
          curx++;
          break;
          case Direction.Down:
          cury++;
          break;
       }
     }

   }

   return newpath;
}

You can generate the path by calling it:
var mynewpath = GenerateRandomPath(0,0,10,10,0.3);

Here the first four parameters are start and end coordinates of your field (determining the dimensions) and the last parameter is the curving probability. Hope it helps...

+1 For having a variable called newd. Also, for a fairly straightforward and simple solution.


text:
matrix 4x4 position data
I understand that a 4x4 matrix holds rotation and position data.
The rotation data is held in the 3x3 sub-matrix at the top left of the matrix.
The position data is held in the last column of the matrix.
e.g.
glm::vec3 vParentPos(
    mParent[3][0],
    mParent[3][1],
    mParent[3][2]
);

My question is - am I accessing the parent matrix correctly in the example above?  I know that opengl uses a different matrix ordering that directx, (row order instead of column order or something), so, should the mParent be accessed as follows instead?
glm::vec3 vParentPos(
    mParent[0][3],
    mParent[1][3],
    mParent[2][3]
);

thanks!

Your first method is the correct one. According to the OpenGL FAQ:

The translation components occupy the 13th, 14th, and 15th elements of the 16-element matrix

It can also be seen in the glm source code (from matrix_transform.inl):
inline detail::tmat4x4<T> translate
/*...*/
{
    detail::tmat4x4<T> Result(m);
    Result[3] = m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3];
    return Result;
}

You can see only Result[3] is affected. This is called column-major storage, but note that OpenGL can be set up in order to use row-major instead (see the OpenGL FAQ on this).

Also be aware that D3D can be set up to use column major too (in fact this is no longer such a religious issue as it was in the fixed pipeline days) - in other words you can't actually rely on anything!


text:
Trying to simulate a cannon ball
I'm writing a game, and I need to simulate a the path of a cannon ball.
I imagine I would have the initial velocity vector, and a vector for gravity.
Is there a good tutorial on how to do this?
(maybe I need to read some high school text books?)

Possibly of interest? http://www.amazon.com/Physics-Game-Developers-David-Bourg/dp/0596000065 - it's not great, but it's not a terrible starting point either.

What I would do is learn how to use Cocos2d. You can use a function thats kind of like a timer, it is called 60 times a second by default but you can change this.
What you would do with this is update the x/y position of your sprite (the cannonball image) by a minuscule amount inside this time function, called ccTime.
If your actually looking for the math for the trajectory, here is an amazing tutorial on that
Here is a question on a forum very similar to yours

You show read the basics of the trajectory from where you can extract any equation you need.
If you google 'cannon ball trajectory' there is hundreds of tutorials of how to compute the position of an object following a cannon ball trajectory at any given time. Here there's an example


text:
SFML - Moving a sprite on mouseclick
I want to be able to move a sprite from a current location to another based upon where the user clicks in the window. This is the code that I have:
#include <SFML/Graphics.hpp>

int main()
{
    // Create the main window
    sf::RenderWindow App(sf::VideoMode(800, 600), "SFML window");

    // Load a sprite to display
    sf::Texture Image;
    if (!Image.LoadFromFile("cb.bmp"))
        return EXIT_FAILURE;
    sf::Sprite Sprite(Image);

    // Define the spead of the sprite
    float spriteSpeed = 200.f;

    // Start the game loop
    while (App.IsOpened())
    {
        if (sf::Keyboard::IsKeyPressed(sf::Keyboard::Escape))
            App.Close();

        if (sf::Mouse::IsButtonPressed(sf::Mouse::Right)) {
            Sprite.SetPosition(sf::Mouse::GetPosition(App).x, sf::Mouse::GetPosition(App).y);
        }

        // Clear screen
        App.Clear();

        // Draw the sprite
        App.Draw(Sprite);

        // Update the window
        App.Display();
    }

    return EXIT_SUCCESS;
}

But instead of just setting the position I want to use Sprite.Move() and gradually move the sprite from one position to another. The question is how? Later I plan on adding a node system into each map so I can use Dijkstra's algorithm, but I'll still need this for moving between nodes.

The easiest way I see is to store velocity, when user clicks on screen. This velocity will define, which direction sprite should move and by what speed (so for example direction * spriteSpeed).
Direction can be obtained by simple vector math: (TargetPosition - CurrentPosition).normalize()
And then you will update sprites position each frame. So just add to while loop: CurrentPosition += Velocity * ElapsedTimeSinceLastFrame. ElapsedTimeSinceLastFrame is just for sure - if you don't use time and run this application on faster machine (while loop will be executed faster), your sprite will move of course faster.
And finally - you should control, if sprite is at the end of its journey. So control, if (Velocity * ElapsedTime).length() is not more than (TargetPos - CurrentPos).length(). If it is, move sprite to target position and set velocity to zero (or set some flag not to update sprite position till next mouse click).


text:
What is a good way to test demand for a new game platform?
I'm working on a game platform that turns your iPhone, android or iPad into a steering wheel, for racing games (like need for speed and dirt 3) and flight simulators for example.
I'd love to figure out smart ways to figure out whether gamers would like something like this.
I originally asked this question over on the gaming SE and it was for getflypad.com. A lot of the tech is built and most of it is doable - the question here is how to test demand and know whether gamers actually want this.

I think we need a bit more information on what you mean by "game platform". Apple generally dislikes meta-platforms and kills any app that hosts other apps, if that's what you meant.

If you intend to have users use their [smartphone of choice] with their PC/Console/Whatever, you need to provide output in a usable format and allow mapping to keyboard/gamepad buttons and/or mouse movement. Also, a driver and/or additional hardware might be needed.

Well, your total potential market is a cross section of:

Racing Game Fans (with current PC racing games)
iPad+iPod Owners

If I was you, I'd try and dig up some sales figures from some modern or recent racing games. Those might be hard to come by, but you might be able to scrape some data from the number of active TrackMania 2 players (or similar such online games). Actually, "active" players might be a more realistic market for your product than mere owners of racing games.
You also need to keep in mind you're competing in the racing wheel market, which may generally have better responsiveness and offer a better overall experience for the player (it's car racing after all, not hand waving). But for a couple dollars as an iOS app, you may still be able to drive a decent amount of impulse "lets give this a try" purchases.
As for ascertaining actual demand for something, you Google it. Look for people asking for the exact app you're asking for "let me play my PC racing games with my iPad as the controller". Now yes, you stand a very good chance of finding nothing, which may actually mean there is no demand. However, that's not to say nobody will want it once they know it exists. It could be something they don't yet know they want.

You could create a website that advertises your theoretical product and pay for some advertising on Google, etc. to generate some traffic to it. Explain that the product is coming soon, and provide a way to sign up for a newsletter.
You can watch trends in traffic (repeat hits, how many first time visitors stick around to read your content, etc.), which should give you some idea of whether there is any interest. Your newsletter subscriptions will not only give you an idea of what kind of interest there is, but also help you have a stronger release.
Rob Walling talks a bit more about this in his book, Start Small, Stay Small.


text:
A more sophisticated ball-paddle collision algorithm for Breakout?
I have a simple breakout game I'm working on. The collision code is solid; things bounce as they should and don't pass through things or do other funkiness, but the reflection is a bit simplistic. As a result, it's easy to get into a state where the ball gets stuck in a loop such that the last blocks cannot be hit without dying to break the loop.
Currently, the paddle collision code reflects the Y speed, and mirrors the X speed depending on what side of the paddle it hits:
        // Check for paddle collisions
        if ((m_ball.rect()).intersects(m_paddle.rect())) {
            double ballCenter = m_ball.rect().getX() + (m_ball.rect().getWidth()/2);
            double paddleCenter = m_paddle.rect().getX() + (m_paddle.rect().getWidth()/2);

            m_ball.setSpeedY(m_ball.speedY() * -1);

            if (ballCenter > paddleCenter) {
                m_ball.setSpeedX(Math.abs(m_ball.speedX()));
            } else {
                m_ball.setSpeedX(-Math.abs(m_ball.speedX()));
            }
        }

Is there any way I could make the algorithm more "interesting", and tighten up the control so the ball doesn't keep get stuck bouncing in the same square?

Use a sliding scale to modify the X speed depending on the location on the paddle.
Set some sort of constant for a max X speed change.  If the ball hits on the very right side of the paddle, add this constant to the X speed.  If it hits on the very left side of the paddle, subtract this constant from the X speed.  If it hits in the very middle of the paddle, do not affect the X speed.
Anywhere in between, use a sliding scale to determine the amount to add or subtract to the X speed.

A lot of break out games will introduce "spin". If the paddle is moving it will influence the X direction of the ball in the direction the paddel is moving.

Jonathan,
I would do as Erick suggests, but I would be careful to make sure the X and Y speed components remain interlocked, otherwise the ball's overall speed will change simply from a collision with the paddle, which is unrealistic physics.
So I would first compute the ball's overall speed from .speedX() and .speedY() (using the Pythagorean theorem), then compute the new X speed from the position of the ball relative to the paddle, and then set the Y speed dependent on a function of the new X speed and the original overall speed, so that the ball simply changes direction (in an infinite number of possible angles) but always maintains the same overall speed.
To put that more concretely, I would do it like this:
if ((m_ball.rect()).intersects(m_paddle.rect())) {
    double ballWidth = m_ball.rect().getWidth();
    double ballCenterX = m_ball.rect().getX() + ballWidth/2;
    double paddleWidth = m_paddle.rect().getWidth();
    double paddleCenterX = m_paddle.rect().getX() + paddleWidth/2;
    double speedX = m_ball.speedX();
    double speedY = m_ball.speedY();

    // Applying the Pythagorean theorem, calculate the ball's overall
    // speed from its X and Y components.  This will always be a
    // positive value.
    double speedXY = Math.sqrt(speedX*speedX + speedY*speedY);

    // Calculate the position of the ball relative to the center of
    // the paddle, and express this as a number between -1 and +1.
    // (Note: collisions at the ends of the paddle may exceed this
    // range, but that is fine.)
    double posX = (ballCenterX - paddleCenterX) / (paddleWidth/2);

    // Define an empirical value (tweak as needed) for controlling
    // the amount of influence the ball's position against the paddle
    // has on the X speed.  This number must be between 0 and 1.
    final double influenceX = 0.75;

    // Let the new X speed be proportional to the ball position on
    // the paddle.  Also make it relative to the original speed and
    // limit it by the influence factor defined above.
    speedX = speedXY * posX * influenceX;
    m_ball.setSpeedX(speedX);

    // Finally, based on the new X speed, calculate the new Y speed
    // such that the new overall speed is the same as the old.  This
    // is another application of the Pythagorean theorem.  The new
    // Y speed will always be nonzero as long as the X speed is less
    // than the original overall speed.
    speedY = Math.sqrt(speedXY*speedXY - speedX*speedX) *
             (speedY > 0? -1 : 1);
    m_ball.setSpeedY(speedY);
}

Note: As time goes on, rounding errors will cause the overall speed to drift slowly from its original value. The desired overall speed might be something you want to add as member data to m_ball (rather than calculating it each time here), or it might be something you want to allow to speed up and slow down according to other gameplay factors.

It's a common game mechanic to slowly speed the ball up until someone loses.  Otherwise you could play forever.

That's a good point!


text:
On Creating a D3DX10 texture atlas
I have a DirectX10 texture (ID3D10Texture2D) that I load from disk with the following code:
CComPtr<ID3D10Device>   spD3D; // Initialized correctly elsewhere

hr = D3DX10CreateTextureFromFile(
        spD3D.p,
        wsFilename.c_str(),
        NULL, NULL,
        &spTextureResource,
        NULL
    );

if( FAILED(hr) || ! spTextureResource.p )
    return false;

spTextureResource->QueryInterface <ID3D10Texture2D> ( &m_spTexture );
if( ! m_spTexture.p )
    return false;

The texture loads fine, I can blit this onscreen.
Later, I want to use that texture as an atlas.  To do so, the first thing I want to do is to call ID3D10Texture2D::Map() in order to get at the texels and parse them (to determine where my tiles are).
The following call fails with E_INVALIDARG:
D3D10_MAPPED_TEXTURE2D mapped;
HRESULT hr = spTexture->Map( 0, D3D10_MAP_READ, 0, &mapped );

So I'm thinking that this fails because the texture can't be read from by the CPU.  So in order to get a texture that is CPU readable, I tried setting the D3DX10_IMAGE_LOAD_INFO structure to include D3D10_CPU_ACCESS_READ.  This fails on D3DX10CreateShaderResourceViewFromFile() with E_INVALIDARG.
So I guess I've given up trying to load in a texture and be able to read its data from on the CPU.
So I thought, what about making a texture with the following D3D10_TEXTURE2D_DESC flags:
    D3D10_TEXTURE2D_DESC    desc;
    ZeroMemory(&desc, sizeof(D3D10_TEXTURE2D_DESC));
    desc.CPUAccessFlags     = D3D10_CPU_ACCESS_READ | D3D10_CPU_ACCESS_WRITE;
    desc.Usage              = D3D10_USAGE_DYNAMIC;
    desc.BindFlags          = D3D10_BIND_RENDER_TARGET | D3D10_BIND_SHADER_RESOURCE;

Step 2 of my plan is to use CopyResource or CopyResourceSubregion to copy data from the disk file into my dynamic texture, so I can use the dynamic texture as a source to read texel data from.
Will this approach work?  Am I barking up the wrong tree and missing an obvious simpler route?
I'm worried that CopyResource won't work either, since the original texture was loaded from disk without the D3D10_CPU_ACCESS_READ flag.
God, I've got to write this for OpenGL too, I hope it's easier with GL!
My plan is to parse this texture and determine where my tiles are, so I can use the texture as an atlas for generating sprites.

I made a splatmap terrain shader with atlas maps, I abandoned it because of filtering problems (bleeding, especially with mip maps).
Good luck though, I'd love to see someone break the 2-4-8-16 texture limit for 'normal' shaders!

In order to read texel information from a texture, we need a texture with Usage = D3D10_USAGE_STAGING.
This allows the D3D10_CPU_ACCESS_READ flag to be set.
I loaded this texture a second time (as a temporary, or "staging" resource, so that I could read the texel information).
So to get read access to a texture, we must fill in this IMAGE_LOAD_INFO structure, which is passed to the D3DX10CreateTextureFromFile() call.
    CComPtr<ID3D10Device>       spD3D       = RenderMgr::I()->D3DDev();
    CComPtr<ID3D10Texture2D>    spTexture;
    CComPtr<ID3D10Resource>     spResource;

    D3DX10_IMAGE_LOAD_INFO  loadInfo;
    loadInfo.Width          = D3DX10_FROM_FILE;
    loadInfo.Height         = D3DX10_FROM_FILE;
    loadInfo.Depth          = D3DX10_FROM_FILE;
    loadInfo.FirstMipLevel  = 0;
    loadInfo.MipLevels      = D3DX10_FROM_FILE;
    loadInfo.Usage          = D3D10_USAGE_STAGING;
    loadInfo.BindFlags      = 0;
    loadInfo.CpuAccessFlags = D3D10_CPU_ACCESS_WRITE | D3D10_CPU_ACCESS_READ;
    loadInfo.MiscFlags      = 0;
    loadInfo.Format         = m_pTexAtlas->Desc().Format;
    loadInfo.Filter         = D3DX10_FILTER_NONE;
    loadInfo.MipFilter      = D3DX10_FILTER_NONE;
    loadInfo.pSrcInfo       = 0;

    hr = D3DX10CreateTextureFromFile(
        spD3D,
        wsTexture.c_str(),
        &loadInfo,
        NULL,
        &spResource,
        NULL
    );

    if( ! SUCCEEDED(hr) )
        return false;

    spResource->QueryInterface <ID3D10Texture2D> (&spTexture);
    if( ! spTexture )
    {
        spResource.Release();
        return false;
    }

    spTexture->GetDesc( &desc );

    ZeroMemory(&mapped, sizeof(D3D10_MAPPED_TEXTURE2D));

    hr = spTexture->Map( D3D10CalcSubresource(0, 0, 1), D3D10_MAP_READ, 0, &mapped );
    if( ! SUCCEEDED(hr) )
        return false;

Okay, so now the Map() call succeeds.  I hope it helps someone out there !!!  I wasted an entire day on this.  I wish there was better documentation for dealing with textures.  I was working from Luna, which like many sources, only deals with textures as they can be mapped to models :S


text:
How should one design an analytics system for an online multiplayer game?
For my simple MMO, the MySQL database stores things like user experience, user level, user coins, health points, etc.
We wanna have an analytics system that can show me trends through daily averages, medians, totals of different stats and actions of the game's user base.
Some answers that need to be answered by this analytics system:

Average health points over time
How many users are what level over time
How many quests were started by users over time vs how many were completed
Cohort analysis on certain groups of users

I was looking into BI systems and thought maybe building an OLAP database with a star schema might be appropriate. But I'm not sure what are good dimensions to use for this and how to deal with changes to the transactional database over time. And it seems like a lot of work to build out a ETL and reporting system as well.
Anything else that's simpler and yet still robust? Are key-value datastores a good option?
What are some commonly used systems for doing this type of analytics?

Any hint on the sizing of your data? and how much "real-time" analysis you need ? do you want "web" report/dashboard? are you looking for a free BI system?

Data is not too big right now. Less than 1GB. Daily aggregate data is good enough. Having the dashboard is essential and we can build that out if need be. The storage design and workflow is the main concern.

Similar question: http://gamedev.stackexchange.com/questions/1627/what-type-of-dashboard-should-i-create-to-understand-how-my-game-is-performing

I wouldn't think key/value stores are a good solution for this - they're not very good at calculating over many records.
In my experience, there are 3 common routes:

run your reporting queries directly against the production database. This is the easiest option, but can affect performance - so, for a game, probably not that useful.
duplicate your production database - e.g. through replication - and run your reporting queries against the copy. This has minimal impact on the production database (replication has a slight overhead), is relatively easy to set up, and uses your knowledge of the existing schema. It may not scale to huge amounts of data, though; to mitigate this, the first step is to pre-calculate commonly needed data. For instance, you might run a nightly batch to calculate daily statistics, a weekly batch for weekly stats etc.

create a proper data warehouse with a schema customized for OLAP. This supports huge data sets, and allows you to use high-end reporting tools allowing non-technical folk to create very sophisticated queries (Cognos and the like).

I wouldn't recommend jumping straight to the data warehouse option - it's a whole new world, designing star schemas is a specialist skill, and you will get far better results by implementing your reports using "traditional" SQL queries, and then moving to the data warehouse when you really, really need to.

I would go the OLAP way (maybe because I'm a bit biased as working for icCube) as this is a solid foundation. You're sure to be able to evolve the system in the future.
You do not need to be a specialist to setup a model with a few dimensions to start with. You could create some dedicated SELECT statements (or VIEWS) to create the cubes and once loaded into icCube, your prod DB won't be used anymore (this is an in-memory OLAP server). Later you could decide to create a dedicated DB if required. I do not see requirements for an ETL in your case.
For the reporting side, we're providing a Google Visualization DataSource for very easy access from Javascript to create dedicated dashboards that does exactly what you want the way you want. Or use existing tools connecting using XMLA (Excel, ...).


text:
In game level editor using AIR or stand alone app using Java or C#
I'm in the process of choosing technologies to build the level editor of a Flash RPG game.
On one side I can use AIR and build a ingame level editor that's probably going to give the best result. The problem is, I think it will be very hard, I don't have good memories using the UI libraries of AS3. I think that would take at least 3 more times (to build the editor) than the other approach.
Or I can use some mature set of tools to build the editor, like the ones commonly used with C# or Java.
The question is: Is it worth the trouble to build the editor in AIR? Or using a stand alone editor is just fine?
EDIT: Me and my team are the only people using this editor.

Seeing @PrinceCharles answer, I'm left wondering if the meat of your question is actually "AIR vs Java/C# for a level editor" or "In game vs standalone level editor". I assumed the first, but there's a significant difference between both.

What's your gripe with AIR? I always considered Flex/AIR as a very powerful UI Framework. IMHO it's really easy to develop custom applications with it...

As David stated it is a personal preference but there are some practical questions as well.
It is also a question of if an how you can create an in-game editor without changing your game code (which I think is not a good idea unless the player should be enabled to use the editor as well) and/or having to implement everything twice. Separating game and editor and having the actual game logic only in one place is a good thing!
But what I also find very important is to have at least some kind of preview/in-game view to see how changes reflect in the actual game. I am working on an XNA game where the editor hosts an XNA component and all the designer stuff is done in WPF. In your case I would suggest doing something similar using some browser control to load/refresh your actual game from within the editor. Continuously pressing Alt+Tab does not make your design work easier ;-)

Indeed there are several implications between making the editor part of the game or making it external. This book presents a very nice comparison, from a practical and technical point of view, of both alternatives, but I don't have it here at the moment. But I kinda assumed Vandell was asking more about which technology to use instead of the placement of the engine, which is why I said it was mostly subjective and personal preference. The choice between making it in game or standalone, not so much. :-)

Another point to consider is the output of the editor (or the input of the game). If you have to re-implement the whole database access layer or some deserialisation methods for your game objects I would think twice about bringing another tech into play. Only if the development time is saved by having powerful controls to speed up editor development.

If you are building an editor for a Flash game, it might make sense to build the game editor in Flash/AIR. That way you wouldn't need to port/rewrite the core logic/rendering code from Flash to C#/Java.
That said, if it were an in-game editor, wouldn't the editor be of the same platform as the game, eg. Flash?

That's a bit subjective. It's going to depend mostly on how familiar you are with each of the technologies. And I think the deciding factor would also be, do you really need the level editor to be available in game? Is the general user supposed to have access to the editor too? If you're the only one that's going to use it, don't think twice, just go with the technology you're more familiar working with, even if it's a standalone editor. Personally, I'd go the standalone editor route, but that's just my preference.
With that said, there are some advantages to building the editor in game. For one, you can use the codebase that you alredy built for the game to aid you with the editor. And you can more easily switch between normal gameplay and level editing on the fly. Is it worth the extra effort? That's up to you.

I think it's indeed a subjective question, I want to know you guys experience on this matter, thank you for sharing your opinion.

Well, in my case I'd probably create a standalone editor in C# because that's what I'm experienced with. :)


text:
Dot Product Vs Cross Product Turning a Turret Towards A Enemy and firing
http://pastebin.com/iw9DHf7s is code demonstrating dot product turning a turretto a target and firing. It works and chooses best angle to spin.
A problem can occur when game goes faster (better computer) and that threshold no longer applies. Making the threshold bigger obviously stops the turret early.
My friend mentions cross product is the way to fix it. Then he disappears for long periods of time. Doesn't dot product NOT get a inner angle between two vectors? Ok lets just say I agree and dot product doesn't work ever.
So tell me how does vector product do the trick? I'm going from a single scalar that I can get degrees out of to a third orthogonal vector. I've read about cross product and the function and watched a you tube video and I don't get (given the same code pasted) how to use cross product here.
Update:
Would this work?
//towerFacing is the at/forward vector of the cannon
Vector v1 = cannonPos - targetPos ;
Vector v2 = towerFacing - cannonPos ;

//The z plane
double cross = v1.x*v2.y - v1.y*v2.x ;
if (cross > 0) { return Direction.Left ; }
if (cross < 0) { return Direction.Right ; }

Obviously the zero is not what we want to use in games. However The difference is now our zero means our at vector and target is perpendicular and on each other which a x b = 0. The dot product since it uses cosine I used the right vector which is orthogonal with the facing( a . b = 0).
Am I wrong on how the cross product works by what has listed for answers still?

The dot method you have on the pastebin is fine if all objects are on the same plane and it is essentially a 2d problem (regardless of if the game is 2d or 3d). If, however, you are in a 3d environment where you need to adjust cannon yaw & pitch, then the cross method would be better because it would give both the direction to turn(rotate towards target) and the 3d axis to rotate about.
If you crossed the cannon's barrel direction with the direction to the target, it gives the proper axis. If you normalized both before crossing, it would even give the arc-sine of the angle between them if you needed (in the same way a dot product could give the arc-cosine).
When crossing, the axis created will give the shortest rotational direction to the target... so does your dot method... but it fails you when the barrel has to change in two dimensions.

So you mean: Get CannonAtVector instead of right and normalize. Cross VicNorm with CannonAtVector. Then rotate barrel about this axis?
Normalize At
Cross VicNorm with At this is my 3D axis to.... rotate about? As in rotate about this axis?

Not sure what you mean by ConnonAtVector. If that means what direction the cannon is currently pointing at then yes. it should be something like (m_cannonMatrix._31, ._32, ._33). Then, if you are going to rotate at a constant rate again, no need to normalize anything but the result of the cross (the axis). then create a rotationMatrix (D3DXMatrixRotationAxis) that takes in an arbitrary axis(your cross result) & angle(how much to rotate this frame only), combine that to m_CannonMatrix, & your done.

What you pulled from the matrix was the forward/at(Z Axis), where as Y is up, and X being right. Also I have not looked at this while. What is the math behind rotation axis with matrices so If I wanted to perform this on my own I could. I'm making the assumption that it is this http://www.kwon3d.com/theory/transform/rot.html.

Correct, local fwd. I'm assuming that your barrel is pointing along m_CannonMatrix' forward axis. with a Y-up system it may need to be the negate of that axis (-Z). It is like the ones you linked but instead of a matrix that represents a rotation around a world axis, it makes one that is a rotation around an arbitrary axis of your choosing. when you combine that with any other matrix, it's like you simply rotated that other one by whatever axis and angle you plugged in.

You don't really need to undestand the math behind if you don't want to... but it's a good idea. As long as you learn how to use it and combine matrices properly, the function will do all the math behind the scenes.  http://msdn.microsoft.com/en-us/library/windows/desktop/bb205357%28v=vs.85%29.aspx

Blockquote A problem can occur when game goes faster (better computer) and that threshold no longer applies.

For starters this is a huge mistake to make and you will find your life much more difficult if you rely on the CPU processing speed to determine your game's frame rate. At a minimum I would update your game based on the actual progression of time rather than CPU cycles. You can still run into problems where different machines will have different amounts of time to process each frame, but your physics and other gameplay systems should advance time strictly on how much real world time passes each frame.

This is correct, but does not have to do with the math question. Also I should note if it concerns, that game actually does operate off of time. The block you quoted: yeah, I should reword that and drop CPU speed(it was actually something else I'm just not recalling at the moment).


text:
UDK game Prisoners/Guards
For school I need to make a little game with UDK, the concept of the game is:
The player is the headguard, he will have some other guard (bots) who will follow him. Between the other guards and the player are some prisoners who need to evade the other guards.
It needs to look like this
My idea was to let the guard bots follow the player at a certain distance and let the prisoners bots in the middle try to evade the guard bots.
Now is the problem i'm new to Unreal Script and the school doesn't support me that well.
Untill now I have only was able to make the guard bots follow me.
I hope you guys can help me or make me something that will make this game work.
Here is the class i'm using to let te bots follow me:
class ChaseControllerAI extends AIController;

var Pawn player;
var float minimalDistance;
var float speed;
var float distanceToPlayer;
var vector selfToPlayer;

auto state Idle
{
    function BeginState(Name PreviousStateName)
    {

        Super.BeginState(PreviousStateName);
    }

    event SeePlayer(Pawn p)
    {

        player = p;
        GotoState('Chase');
    }
Begin:

       player = none;
       self.Pawn.Velocity.x = 0.0;
       self.Pawn.Velocity.Y = 0.0;
       self.Pawn.Velocity.Z = 0.0;
}
state Chase
{
    function BeginState(Name PreviousStateName)
    {

        Super.BeginState(PreviousStateName);
    }
    event PlayerOutOfReach()
    {
        `Log("ChaseControllerAI CHASE Player out of reach.");

        GotoState('Idle');
    }
//  class ChaseController extends AIController; CONTINUED
// State Chase (continued)
    event Tick(float deltaTime)
    {
       `Log("ChaseControllerAI in Event Tick.");

       selfToPlayer =  self.player.Location - self.Pawn.Location;
       distanceToPlayer = Abs(VSize(selfToPlayer));

       if (distanceToPlayer > minimalDistance)
       {
           PlayerOutOfReach();
       }
       else
       {
          self.Pawn.Velocity = Normal(selfToPlayer) * speed;
          //self.Pawn.Acceleration =    Normal(selfToPlayer) * speed;
          self.Pawn.SetRotation(rotator(selfToPlayer));
          self.Pawn.Move(self.Pawn.Velocity*0.001); // or *deltaTime
       }
    }
Begin:
     `Log("Current state Chase:Begin: " @GetStateName()@"");
}

defaultproperties
{
    bAdjustFromWalls=true;
    bIsPlayer= true;
    minimalDistance = 1024; //org 1024
    speed = 500;
}

Have you looked into something like steering behaviors at all? There are some relatively simple things you can do like for seeking points and fleeing from points that might be relevant: http://www.red3d.com/cwr/steer/SeekFlee.html

Can you give us one atomic thing that you would like to accomplish but haven't?  "I would like to make the prisoners attempt to escape from the guards when they see x kind of opportunity."  Something like that?

"self.Pawn.Velocity = Normal(selfToPlayer) * speed;" is this the pawns moving directly towards the player? that would let the prisioners escape. Is best if pawns move to some desired location that is positioned relative to other point, and make that point the same for all paws. Possible make that point the "center of mass" of all prisioners.  You can also make so the "desire to move near this point" is limited by the distance from pawn to pawn. If the distance from pawn to pawn is bigger than the prisioner size, the pawns will want to move to the center..

What you are doing here is similar to a wolfpack hunting.

Assuming that the idea is that prisoners want to escape the circle of guards, trying to avoid them, what you could try is to apply something like the potential fields approach:
http://aigamedev.com/open/tutorials/potential-fields/
With potential fields, guards will apply a repulsive force to the prisoners that come too close to them, and this will change the path prisoners will try to follow, apparently trying to stay away from them. I suppose prisoners will try to move to a position outside the circle of guards: in a simple way, if your prisoner is moving in the direction of a point outside the circle, at each update (or less frequently) you can check if it is close enough (sees) to any guard, and in the update do:
self.Velocity = Normal(self.Velocity) * speed;

// distance is the distance between this Prisoner and the closest Guards,
// minDistance is the distance at which if
if (distance < minDistance)
{
    vector rp = Normal(guard.RepulsiveForce) * (minDistance / distance);
    self.Velocity += rp;
}

Of course the Guard class needs a RepulsiveForce vector that will indicate the direction to which he will try to push close Prisoners: this vector will modify the current velocities of Prisoners that get close enough, and they will look like they will try to avoid them.
But again, what you should also do is running a path planning algorithm (like A* star) for the prisoners to find a path and, while running the A*, treat the Guards (probably with a bigger influence circle) as obstacles.

authors: Влад Киевский