title: 2D platformer corner collision

text:
# Question
Title: 2D platformer corner collision
Repost from my question on stack overflow, didnt know this site existed.

I have a 2d platformer and I need help with collision. To show you my current collision system, here is picture:

Top picture is how game looks normally, bottom picture shows highlighted collision rectangles. Black ones are horizontal (If player rectangle intersects them, move player on Y axis), blue are vertical (move player on the X axis) and red are corners.

I've implemented corner rectangles, after bit of testing after I found out, that when I had black and blue overlapping each other, this happened: Player jumped and intersected both rectangles at once, game would recognize that and resolve both intersection at the same time, cause the player to spaz around the map and ending up in a another rectangle, which would then cause another intesection and resolution until the chain reaction stopped, and player would end up somewhere where he should not have been.

So I added corner rectangles, they should resolve this situation like this: if player hits corner from the bottom, act like horizotal rectangle, if he hits from side, act like vertical.

Thing is, I have no idea how to make them work like that.

Here is my code so far:

```
        if (InputHandler.KeyDown(Keys.W))
        {
            player.MoveUp();
            Parallel.For(0, horizontalPlayerCollisionRectangles.Count, i =>
            {
              if (player.PlayerRectangleInWorld.Intersects(horizontalPlayerCollisionRectangles[i]))
                {
                    player.PlayerPositionY = horizontalPlayerCollisionRectangles[i].Y + horizontalPlayerCollisionRectangles[i].Height;
                }
            });
        }

        if (InputHandler.KeyDown(Keys.D))
        {
            player.MoveRight();
            Parallel.For(0, verticalPlayerCollisionRectangles.Count, i =>
                {
                    if (player.PlayerRectangleInWorld.Intersects(verticalPlayerCollisionRectangles[i]))
                    {
                        player.PlayerPositionX = verticalPlayerCollisionRectangles[i].X - player.PlayerRectangleInWorld.Width;
                    }
                });
        }

        if (InputHandler.KeyDown(Keys.A))
        {
            player.MoveLeft();
            Parallel.For(0, verticalPlayerCollisionRectangles.Count, i =>
            {
                if (player.PlayerRectangleInWorld.Intersects(verticalPlayerCollisionRectangles[i]))
                {
                    player.PlayerPositionX = verticalPlayerCollisionRectangles[i].X + verticalPlayerCollisionRectangles[i].Width;
                }
            });
        }

        if (player.Gravity)
        {
            Parallel.For(0, horizontalPlayerCollisionRectangles.Count, i =>
            {
                if (player.PlayerRectangleInWorld.Intersects(horizontalPlayerCollisionRectangles[i]))
                {
                    player.PlayerPositionY = horizontalPlayerCollisionRectangles[i].Y - player.PlayerRectangleInWorld.Height;
                }
            });
        }

```

Its pretty simple. Now that I think about it, my system is flawed, so thats why I'm asking this question. How to make collision work using collision rectangles?

P.S. I can't use any physics engine like Farseer, it's a school graduation project and I have to code as much as possible by myself.

# Answer
> 4 votes
You're really close to the answer already. What you want to do is implement *all* collision rectangles the same way and your idea for "corner rectangles" is pretty much that.

Here's a high level look at what you need to do.

1. In your collision processing you need to get a list of all rectangles that your player is definitely colliding with.
2. As you loop through this list you need to test the intersection of the player and each rectangle. This intersection will give you `x` and `y` values.
3. Compare `x` and `y`. Whichever value is smaller is the axis you want to resolve along. That is, if `x < y`, adjust your player's position along the x axis. If `y < x`, adjust the player along the y axis.
4. Loop until done.

---

Since you're using XNA you can check out the Platformer Code Sample on App Hub. I believe the relevant code is in the `HandleCollision` method in the `Player` class. This is a working example of what I outlined above.

Metanet also has two really great tutorials on 2D collisions.

1. Tutorial A
2. Tutorial B

---
Tags: xna, c#, xna-4.0
---


# Question
Title: How do you save and load settings for an iOS game?
I've read a few beginning iPhone game programming books, and they've helped tremendously in my education and advancement in creating a few simple games, but of all the books I've read, there doesn't seem to be anything about creating a Settings Menu or how to change and save settings within a game.

What are some ways that settings can be saved/loaded? Where are these settings saved?

This may seem like a simple, uninteresting question, but I can't find anywhere that has a good explanation on how to go about creating a settings menu and how the data is saved/loaded each time the program ends/starts...

Mind you I'm not really expecting to have code thrown at me, but an explanation on how the structure works and how to wrap my head around the whole concept (though code is pretty ;)). Or even some articles that explain the concept that I could read would be very helpful.

# Answer
Ignoring the "menu" part of it (it's the same as any other UI element), for iOS games specifically you can use the built-in NSUserDefaults class to store key-value pair of settings.
> 8 votes

# Answer
Well, you're writing to and reading from temporary variables, and those are in turn written to / read from a file stream when saving and loading, respectively. Your user interface buttons and toggles and other doodats might tie into something like the Command Pattern when hit; but TBH, even that is probably slight overkill for something this simple at its heart. I certainly wouldn't implement Command just for something as simple as settings, but I would use it if it were already part of my UI framework (whether custom or not).

Reading and writing to file streams should be easy enough to find in the iPhone dev docs; alternatively there is probably something like a "temporary local storage" mechanism (this can be found in eg. Chrome, Android, Flash, and HTML5) -- think this is what @Tetrad has mentioned.
> 1 votes

---
Tags: iphone
---


# Question
Title: UDK client, C++ server (is it possible?)
For example I have C++/C# server side with sockets or http web server and UDK client.

I am interesting what about experience with networking in UDK: could I connect UDK client to C++/C# socket server via UDP/TCP? Maybe some tutorials/examples?

# Answer
> 7 votes
I'm assuming your question is asking about just trying to get some information from a server via TCP and not creating your own networking interface for UDK. The latter which would be impossible unless you had access to the UE3 source code just because classes like Actor and such have native replication which you wouldn't be able to override.

As for your original question, yes you can connect your UDK game client to a TCP server. There are two primary options:

1. DLLBind
2. TCPLink

With DLLBind you would have to write a DLL in C++ and then have something a class that reads from that DLL like this:

```
class NewDLLBind extends Object
DLLBind(DLLName);

```

Then inside this unrealscript class, you can call functions as necessary to either send information/get information from your DLL which would handle the TCP/UDP networking for you.

More information about DLLBind can be found here: http://udn.epicgames.com/Three/DLLBind.html.

The other option is to use TCPLink. I've personally never tried it before but it should work although it might take some tinkering around with because the documentation is pretty scarce for it. From my understanding you can just create a class that extends from TcpLink and use it to connect to a server via TCP.

More information here: http://udn.epicgames.com/Three/TcpLink.html and they have examples at the bottom that I would suggest looking at.

Good luck!

# Answer
> 8 votes
I think what you'll find is that the UDK networking protocol which runs on top of UDP and TCP, is tied up with their proprietary client and server code. So no, if you wish to use the actual UDK networking client, you very likely wouldn't be able to write your own socket or webserver, even if you knew what the packet structure was (and wanted to try to reimplement based on that).

However if you want to just use the UDK client for display purposes... maybe; I'm not sure this is possible, though, since AFAIK UDK is entirely scripted, so anything not supported "under the hood" is probably not supported *at all*. If it were possible, consider the following:

* It takes an *impressive* amount of work to construct a protocol on top of TCP that has low enough latency and bandwidth requirements to be suitable for a current generation FPS. TCP is a stream-based protocol and as such, suffers from issues of latency that UDP=based game protocols tend to avoid.
* It takes an *even more impressive* amount of work (at least a couple of months from an experienced, dedicated network developer) to construct a suitable protocol on top of UDP on the other hand, because you need to reimplement the degree of (a) reliability and (b) flow control that TCP provides natively, while avoiding TCP stream aspect, so as to avoid latency issues inherent to TCP.

In both of the above instances (implementing your own TCP *or* UDP), you also would need to consider implementing security through some encryption layer. This is pretty much a necessity for any FPS, for obvious reasons.

If you want to learn the nitty gritty of socket-based networking, great. But be prepared to put in a substantial amount of time, as there are many ins and outs. If, on the other hand, you want to get a game up and running, use the networking provided as part of UDK. Or use some other libraries to help you achieve your goals, in conjunction with the rest of their engine (if possible) or some other engine (if not). YMMV, dependent on your game's requirements.

# Answer
> 3 votes
If you want to create your own C++ servers, you would have write the entire networking part by yourself which is quite difficult as Nick Wiggill describes.

I wouldn't recommend it, but it can be done. UDK can use DLL libraries and thus you could write your own networking part. It would be a huge project, but it could be done.

However if you stick with Unrealscript for the game networking and using C++ networking via DLL's for other data, maybe metainformation like player XP or other persistent progress systems.

# Answer
> 1 votes
I think this is posible, you can use dllbind, in order use another net system like raknet.

And you can select what you want transport by net, but you should read the raknet license, cause if udk consumes 30% of your benefits I dont know how much, raknet or another net library could cost.

to Use raknet is quite simple and it brings many examples, I built a windows client with OGRE3D, it was a small world, my friends could connect it, and we could seen each other.

Server was program for linux os, and client for windows.

raknet use udp reliable packets which is very interesting.

At this moment, I´m trying learn UDK, cause to build a level and many others features are pretty easy.

sorry by me english. :(

be free to contact me, to try learn udk together.

# Answer
> -1 votes
Why not take a chapter out of Obsidian and Bethesda and create a single player experience that all can enjoy, suffice to say the even the big shots seem to feel the need for single player games. Multiplayer with servers is a tough challenge, you won't need game programmers for it you will need a separate dedicated group of people to write and maintain a persistent DB that ensure security to all connected clients. The problem here is you will need a third party group as well a group of people overseeing the implementation of the server code and plugging that into your game code and keeping both code stacks clean. You not only lack the skills and resources for such a feat but chances are even if you get past the hurdles you wouldn't be able to afford the needed help.

The full license for the Unreal Engine starts at: $250k

The gives you access to this: http://news.bigdownload.com/2009/03/17/feature-more-on-unreal-engine-3s-atlas-technology/

Good luck!

---
Tags: networking, client-server, udk, socket
---


# Question
Title: Getting the number of fragments which passed the depth test
In "modern" environments, the "NV Occlusion Query" extension provides a method to get the number of fragments which passed the depth test. However, on the iPad / iPhone using OpenGL ES, the extension is not available.

What is the most performant approach to implement a similar behaviour in the fragment shader?

Some of my ideas:

* Render the object completely in white, then count all the colors together using a two-pass shader where first a vertical line is rendered and for each fragment the shader computes the sum over the whole row. Then, a single vertex is rendered whose fragment sums all the partial sums of the first pass. Doesn't seem to be very efficient.
* Render the object completely in white over a black background. Downsample recursively, abusing the hardware linear interpolation between textures until being at a reasonably small resolution. This leads to fragments which have a greyscale level depending on the number of white pixels where in their corresponding region. Is this even accurate enough?
* Use mipmaps and simply read the pixel on the 1x1 level. Again the question of accuracy and if it is even possible using non-power-of-two textures.

The problem wit these approaches is, that the pipeline gets stalled which results in major performance issues. Therefore, I'm looking for a more performant way to accomplish my goal.

**Using the EXT\_OCCLUSION\_QUERY\_BOOLEAN extension**

Apple introduced EXT\_OCCLUSION\_QUERY\_BOOLEAN in iOS 5.0 for iPad 2.

> ```
> "4.1.6  Occlusion Queries
>
> Occlusion queries use query objects to track the number of fragments or
> samples that pass the depth test. An occlusion query can be started and
> finished by calling BeginQueryEXT and EndQueryEXT, respectively, with a
> target of ANY_SAMPLES_PASSED_EXT or ANY_SAMPLES_PASSED_CONSERVATIVE_EXT.
>
> When an occlusion query is started with the target
> ANY_SAMPLES_PASSED_EXT, the samples-boolean state maintained by the GL is
> set to FALSE. While that occlusion query is active, the samples-boolean
> state is set to TRUE if any fragment or sample passes the depth test. When
> the occlusion query finishes, the samples-boolean state of FALSE or TRUE is
> written to the corresponding query object as the query result value, and
> the query result for that object is marked as available. If the target of
> the query is ANY_SAMPLES_PASSED_CONSERVATIVE_EXT, an implementation may
> choose to use a less precise version of the test which can additionally set
> the samples-boolean state to TRUE in some other implementation dependent
> cases."
>
> ```

The first sentence hints on a behavior which is exactly what I'm looking for: getting the number of pixels which passed the depth test in an asynchronous manner without much performance loss. However, the rest of the document describes only how to get boolean results.

**Is it possible to exploit this extension to get the pixel count?** Does the hardware support it so that there may be hidden API to get access to the pixel count?

Other extensions which could be exploitable would be debugging features like the number of times the fragment shader was invoked (PSInvocations in DirectX - not sure if something simila is available in OpenGL ES). However, this would also result in a pipeline stall.

# Answer
> Is it possible to exploit this extension to get the pixel count? Does the hardware support it so that there may be hidden API to get access to the pixel count?

No, and no. Well, I supposed if you draw a series of one-pixel-sized triangle in window-space, you could count how many boolean values you get. But that would require a *separate* query for each one pixel. Probably not the fastest thing in the world.

If there's a "hidden API", you won't have access to it (since it's hidden), so it doesn't matter. Furthermore, the nature of the extension already suggests that there isn't. After all, if the hardware had the actual fragment count, why not just expose it directly, the way desktop OpenGL does? If the hardware supported it, they could have just taken ARB\_occlusion\_query and used that.

But they didn't. Which strongly suggests that they *couldn't.*
> 1 votes

# Answer
The results are returned in a GLuint, (also can be GLint for a different call) unfortunately, the result is always a 0 or a 1, maybe they will change it to register frags in the future.

also it looks like not a single person on the entire internet has posted about these new extensions... so here they are set up properly...which is not documented anywhere as far as i can tell... you can imagine how they would go in your code from this little sudo code here:

```
import UIKit/UIKit.h

import GLKit/GLKit.h

import "GLProgram.h"

GLuint testBox,hasBeenTested,theParams;

//...

glGenQueriesEXT(1, &testBox);

glBeginQueryEXT(GL_ANY_SAMPLES_PASSED_EXT, testBox);

//... draw an object .......

glEndQueryEXT(GL_ANY_SAMPLES_PASSED_EXT);

glGetQueryObjectuivEXT(testBox, GL_QUERY_RESULT_AVAILABLE_EXT, &hasBeenTested);

if (hasBeenTested) glGetQueryObjectuivEXT(testBox, GL_QUERY_RESULT_EXT, &theParams);

glDeleteQueriesEXT(1, &testBox);

if (!theParams)  object is hidden;  don't draw next time;

```
> 0 votes

---
Tags: opengl, graphics, ios, opengl-es2
---


# Question
Title: How can I get my first-person character in Unity to move to a ledge with an animation?
I'm trying to get this to happen: The character walks up to a large crate, the player presses a button, and an animation starts playing where the character climbs up on to the crate. (all in first person view).

So far I tried this with normal "First Person Controller" Prefab in Unity.

My code so far:

```
function OnTriggerStay(other : Collider){
    if(other.tag == "GrabZone"){
        if(Input.GetKeyDown("e")){
            animation.Play("JumpToLedge");
        }
    }
}

```
However when i use this on The FPC it will always play from the position the animation is created on.

I also tried to create an empty game object, placing the FPC in there. Gives same effect.

I also tried just animating the graphics of the FPC alone. This seems to work but since the Character Controller itself is not animated that stays onthe ground. So the whole FPC wont work anymore.

Is there anyway i could let this animation play on the local position the player is on at that time?

Or can you think of any other logical solution for a grab and climb?

# Answer
> 1 votes
It's a bit of an odd usage, but you could set the blendMode to Additive and make sure your animation starts at the origin.

# Answer
> 0 votes
This might be able to help you, I haven't used it, but it is supposed to help you with dynamically blending animations to match your level.

http://unity3d.com/support/resources/unity-extensions/locomotion-ik.html

Good luck :)

---
Tags: animation, unity, javascript
---


title: Style: When to call GL Enable/Disable

text:
# Question
Title: Style: When to call GL Enable/Disable
I'm working on an OpenGL application and some routines render textured objects, some are just colored primitives. I was wondering if there was a standard convention for how to deal with setting the OpenGL 'state'.

For example, consider this routine (using OpenGL ES / OpenTK):

```
/// <summary>
/// Renders the given tile at the corresponding screen-tile location.
/// </summary>
public static void RenderTile(float[] vertices, float xOffset, float yOffset, uint textureId)
{
    GL.EnableClientState(All.VertexArray);
    GL.EnableClientState(All.ColorArray);
    GL.EnableClientState(All.TextureCoordArray);

    GL.PushMatrix();

    GL.Translate(xOffset, yOffset, 0.0f);

    GL.BindTexture(All.Texture2D, textureId);
    GL.VertexPointer(2, All.Float, 0, vertices);
    GL.ColorPointer(4, All.Float, 0, SQUARE_COLORS);
    GL.TexCoordPointer(2, All.Float, 0, SQUARE_TEXTURE_COORDS);

    GL.DrawArrays(All.TriangleStrip, 0, 4);

    GL.PopMatrix();
}

```

I'm curious about that `GL.EnableClientState(All.TextureCoordArray);` bit. Should I just get into the habit of calling `GL.Enable(...) / Gl.EnableClientState(...)` for everything the current function needs? Even if it is largely redundant? Or is it better to just *assume* that the application has a certain set of things enabled (blending, back-face culling, 2D textures, etc.).

I know this question is pretty subjective, so I'm looking for advice from someone who has worked with a large OpenGL codebase. (As all my experience is for solo projects.)

# Answer
Redundant state changes can add some overhead, and whether or not your driver filters them depends on the driver (so far as I'm aware the GL spec says nothing about this).

Generally I like to set state at the start of each drawing function, and implement wrappers that do their own filtering. I don't unset state at the end because to do so would mean that separation between drawing functions becomes broken - each function should definitely not have knowledge of what's coming next.
> 0 votes

---
Tags: opengl
---


title: Go pure OpenGL or GLSL?

text:
# Question
Title: Go pure OpenGL or GLSL?
I got interested in studying graphic programming so the obvious entry point was to learn OpenGL. But gathering scattered information around forums and sites, it seems that a pure OpenGL implementation is fading out since most things pre-3.0 are being deprecated and quoting a review on Amazon, "since 3.0 it's all about the shaders". Also of the books that I've seen, looks like only the superbible covers the newer version, but only partially because a good portion of the book teaches deprecated functions, and there are books specifically to GLSL.

This is where I ran into my first problem, some hardwares do not support GLSL, including the notebook with intel integrated graphics that I had planned on using. The function

```
GLuint vertShader = glCreateShader(GL_VERTEX_SHADER);

```

causes a segmentation fault and from the looks of it my driver does not support shaders

So my question is, what is the viability of making a game only in OpenGL? will I be missing irreplaceable good features from the shader language? And what kind of hardware (old gen i3, i5, i7, old VGAs) can I expect to run a game with shaders properly?

# Answer
Shader code is definitely clearer and easier to understand than a mess of glTexEnv, glTexGen and texture matrix calls, and has the bonus that you can express any more-or-less arbitrary math operation using it (which you can't do with the fixed pipeline - what you're calling "pure OpenGL"). The only potential downside is that you need to write a certain amount of supporting infrastructure in your code before you can begin to use them, whereas with the old way you can pretty much dive right in. I call that a "potential" downside because I actually think that it makes you prepare things and learn a little more in advance - OpenGL has a reputation for being "easy" and you occasionally do see people being fooled by this and diving right in without really knowing what they're doing first, which does not stand to their good in the longer term.

Hardware-wise you can rely on almost anything released in the past 5/6/7 years to have some degree of shader support, but - in the case of older Intels (some of the 9xx series) - it's not going to be GLSL, but will instead be the older GL\_ARB\_vertex\_program and GL\_ARB\_fragment\_program extensions. These use an assembly language-like shader language, but - confession time - I'm personally quite fond of it. It's actually quite easy to use, if lacking in some more modern features (such as branching) and requiring more lines of shader code to do the same thing. The supporting infrastructure required in your main program for these extensions is a lot more lightweight than for GLSL too.

That's not to say that I'd recommend them over GLSL however, but they are an option that is there if you really need to run on this class of hardware and it's useful to be aware that they exist, which brings me to the final point. Are you really certain that you really need to run on this class of hardware (e.g in the case of your notebook you may have just neglected to get the entry points)?
> 9 votes

# Answer
If you've done any programming in the past, writing your own shader code using GLSL will be much more enjoyable. I originally tried learning fixed-function OpenGL and it was harder for me because it didn't make sense. Then I tried to learn GLSL using the orange book and it was much easier and made more since. Just my 2 cents.

I would definitely go towards GLSL because of the power to write programs for the GPU.
> 6 votes

# Answer
It should also be noted that there is no "pure OpenGL" anymore.

OpenGL ES 2.0 ditched all non-shader stuff, and since WebGL is based on it, it too only works with shaders. OpenGL 3.0 deprecated all of the fixed-function stuff, and 3.1 removed it (in core profiles. Most implementations support compatibility profiles, but MacOSX does not for their 3.2 implementation).

So I wouldn't suggest learning non-shader OpenGL.
> 6 votes

---
Tags: opengl, glsl
---


title: Allegro Game Won't Fire 2D Projectile

text:
# Question
Title: Allegro Game Won't Fire 2D Projectile
To begin with I am developing a PSP application so I have no clue how to debug a PSP application. That doesn't mean I do not know how debug period. Anyway, when I run the game everything runs fine but when I press the X button on the PSP I see no bullet being drawn or updated on the screen. I know the problem doesn't lie with the pad because I press start and it exits my game so I do not think it is the pad that is causing the problem. Maybe the bullet is being drawn out of the screen already. But I am not sure since I cannot debug maybe somebody can see the flaw in my code. **main.cpp**

```
class Missile
{
    private:
        static const double angle = (3.14159265358979323846 / 2);
    public:
        bool Alive;
        static const int V = 5;
        double X;
        double Y;
        void Init(bool alive, int x, int y)
        {
            Alive = alive;
            X = x;
            Y = y;
        }
        void Update()
        {
            Y -= V;
        }
        void Kill()
        {
            Alive = false;
        }
        void Draw(BITMAP* buffer, BITMAP* sprite)
        {

            draw_sprite(buffer, sprite, X, Y);
        }
};
std::vector<Missile*>* bullets = new std::vector<Missile*>();
void FireBullet(Ship* s)
{
        if (bullets->size() < Constants::MAXBULLETS)
        {
            Missile* missile = new Missile();
            missile->Init(true, s->X, s->Y);
            bullets->push_back(missile);
        }
}

void CleanUp()
{
    for(unsigned int index = 0; index < bullets->size(); index++)
    {
        if (bullets->at(index)->Alive == false)
        {
            bullets->erase(bullets->begin() + index);
        }
    }
}
void UpdateBullets()
{
    for(unsigned int index = 0; index < bullets->size(); index++)
    {
        if (bullets->at(index)->Y < 0)
        {
            bullets->at(index)->Update();
        }
        else
        {
            bullets->at(index)->Kill();
        }
    }
}
void DrawBullets(BITMAP* buffer, BITMAP* sprite)
{
    for(unsigned int index = 0; index < bullets->size(); index++)
    {
        if (bullets->at(index)->Alive == true)
        {
            bullets->at(index)->Draw(buffer, sprite);
        }
    }
}
//Entry point of the application
int main(void)
{

    Ship* s = new Ship();
    int x = (WIDTH / 2) - 64;
    allegro_message("Initialzing ship class");
    s->Init(x);
    int frame = 0;
    BITMAP* buffer = NULL;
    BITMAP* background = NULL;
    BITMAP* ship = NULL;
    SceCtrlData pad;
    bool done = false;
    allegro_message("Initializing Game...");
    int rval = allegro_init();
    if (allegro_init() != 0)
    {
        allegro_message("Error initializing Game Because it returned: %i", rval);
        return 1;
    }
    allegro_message("Setting Graphics Mode...Press X To Begin Game. Default Missile count: %i", bullets->size());
    set_color_depth(32);
    int ret = set_gfx_mode(GFX_AUTODETECT,480,272,0,0);
    if (ret != 0)
    {
        allegro_message("Error setting grahpic mode! Because of it returned: %i", ret);
        return ret;
    }
    background = load_bmp("background.bmp", NULL);
    ship = load_bmp("ship.bmp", NULL);
    BITMAP* m = load_bmp("missile.bmp", NULL);
    if (background == NULL || ship == NULL || m == NULL){
        allegro_message("Couldn't load one or more sprites...");
        return 0;
    }
    buffer = create_bitmap(WIDTH, HEIGHT);
    if (buffer == NULL)
    {
        allegro_message("Couldn't create buffer!");
        return 0;
    }
    while(!done)
    {

        sceCtrlReadBufferPositive(&pad, 1);
        if (pad.Buttons & PSP_CTRL_START)
        {
            done = true;
        }
        else if (pad.Buttons & PSP_CTRL_CROSS)
        {
                FireBullet(s);
        }
        else if (pad.Buttons & PSP_CTRL_LEFT)
        {
            s->MoveLeft();
        }
        else if (pad.Buttons & PSP_CTRL_RIGHT)
        {
            s->MoveRight();
        }
        if (bullets->size() > 0)
        {
            UpdateBullets();
            CleanUp();
        }
        clear(buffer);
        draw_sprite(buffer, background, 0, 0);
        s->Draw(buffer, ship, frame);
        DrawBullets(buffer, m);
        masked_blit(buffer, screen, 0, 0, 0, 0, WIDTH, HEIGHT);
        if (frame == (60 * 10))
        {
            frame = 0;
        }
        frame++;
        vsync();

    }
    allegro_message("Clearing resources!");
    clear(buffer);
    clear(ship);
    clear(background);
    clear(screen);
    allegro_message("Thank you for playing!");
    return 0;
}
END_OF_MAIN()

```

# Answer
I see two problems right off the bat, the first has to do with the marked line below:

```
void UpdateBullets()
{
    for(unsigned int index = 0; index < bullets->size(); index++)
    {
        if (bullets->at(index)->Y < 0) //<-- HERE
        {
            bullets->at(index)->Update();
        }
        else
        {
            bullets->at(index)->Kill();
        }
    }
}

```

The origin for screen coordinates is the upper left corner of the screen, as such, the line `if(bullets->at(index)->Y < 0)` is always `false`, making every bullet fired immediately set `Alive = false`. Swapping the lines `bullets->at(index)->Update();` and `bullets->at(index)->Kill();` should fix the problem.

The second issue is:

```
int rval = allegro_init();
if (allegro_init() != 0) {
...
}

```

Calling `allegro_init()` multiple times is ineffective, you are already storing the return value in `rval` so just check its value instead: `if(rval != 0) { ... }`
> 3 votes

---
Tags: c++, 2d, bullet-physics, allegro
---


title: iphone 3d library with physics

text:
# Question
Title: iphone 3d library with physics
are there any light 3d iphone libraries that must have:

* Physics ( ragdoll physics )
* 3D scene graph
* Advanced lighting (lightmapping and stuff)
* Sound engine
* Ability to import 3D model from blender, 3d studio max, etc.

it should preferably be mature and have no bugs. i have seen cocos3d but many say it is riddled with bugs.

# Answer
Here is a list of game engines/frameworks for iPhone 3D development (but I am not sure whether they satisfy all your requirements):
> 0 votes

# Answer
Possible candidates are UDK, Unity or ShiVa. These are game-engines and not "libraries" in the common sense. There's no library that covers all your requirements, as each of your bullet point would be a library on its own.
> 1 votes

---
Tags: physics, 3d, iphone
---


# Question
Title: Where can I find animated textures for free?
I'm looking for some animated textures, especially water textures that show movement.

After a bit of searching, I could only find this list. Although those textures are certainly not bad, there are only 4 to choose from. I was wondering if there is another website with free animated textures.

For static textures, I can find hundreds of websites which offer them for free, but for animated textures, websites seem to be rare.

Does anyone know of a website that offers free animated textures?

# Answer
You might want to glance over the content creation community portals for Second Life, as this had (and probably still has) one of the largest communities of people creating in-game objects, many of them with animated textures.

The SL WIKI is probably a good place to start, as well as the creators page on SL.
> -1 votes

---
Tags: textures, animation, water
---


title: Particles in XNA - can't get em to work

text:
# Question
Title: Particles in XNA - can't get em to work
I am trying to have an explosion appear when a player lands on a mine. I checked out the particle example on the XNA website but it seemed to over complicate it a lot. So any simpler neater explosion particle effect would be cool to be linked to ;)

But on to the problem, i can't even see the explosion though i cannot see what is going wrong. Here's my explosion class (a lot of this is from the particle example):

```
using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics.PackedVector;

namespace StayUp
{

struct ExplosionVertex
    {
        public Vector3 Position;
        public Short2 Corner;
        public Color Random;
        public float Time;
        public Vector3 Velocity;

        public ExplosionVertex(Vector3 position, Short2 Corner, Vector3 velocity, Color random, float Time)
        {
            this.Position = position;
            this.Corner = Corner;
            this.Velocity = velocity;
            this.Random = random;
            this.Time = Time;
        }

        public static readonly VertexDeclaration VertexDeclaration = new VertexDeclaration
        (
            new VertexElement(0, VertexElementFormat.Short2,
                                VertexElementUsage.Position, 0),

            new VertexElement(4, VertexElementFormat.Vector3,
                                VertexElementUsage.Position, 1),

            new VertexElement(16, VertexElementFormat.Vector3,
                                    VertexElementUsage.Normal, 0),

            new VertexElement(28, VertexElementFormat.Color,
                                    VertexElementUsage.Color, 0),

            new VertexElement(32, VertexElementFormat.Single,
                                    VertexElementUsage.TextureCoordinate, 0)
        );

        // Describe the size of this vertex structure.
        public const int SizeInBytes = 36;
    }

    public class Explosion : DrawableGameComponent
    {
        #region Fields

        string TextureName = "explosion";
        int MaxParticles = 100;
        TimeSpan Duration = TimeSpan.FromSeconds(2);
        float DurationRandomness = 1;
        float MinHorizontalVelocity = 0.02f;
        float MaxHorizontalVelocity = 0.03f;
        float MinVerticalVelocity = -0.02f;
        float MaxVerticalVelocity = 0.02f;
        float EndVelocity = 0;
        Color MinColor = Color.DarkGray;
        Color MaxColor = Color.Gray;
        float MinRotateSpeed = -1;
        float MaxRotateSpeed = 1;
        float MinStartSize = 0.07f;
        float MaxStartSize = 0.07f;
        float MinEndSize = 0.7f;
        float MaxEndSize = 1.4f;
        BlendState blendState = BlendState.Additive;

        // For loading the effect and particle texture.
        ContentManager content;

        // Custom effect for drawing particles. This computes the particle
        // animation entirely in the vertex shader: no per-particle CPU work required!
        Effect particleEffect;

        // Shortcuts for accessing frequently changed effect parameters.
        EffectParameter effectViewParameter;
        EffectParameter effectProjectionParameter;
        EffectParameter effectViewportScaleParameter;
        EffectParameter effectTimeParameter;

        // An array of particles, treated as a circular queue.
        ExplosionVertex[] particles;

        // A vertex buffer holding our particles. This contains the same data as
        // the particles array, but copied across to where the GPU can access it.
        DynamicVertexBuffer vertexBuffer;

        // Index buffer turns sets of four vertices into particle quads (pairs of triangles).
        IndexBuffer indexBuffer;

        int firstActiveParticle;
        int firstNewParticle;
        int firstFreeParticle;
        int firstRetiredParticle;

        // Store the current time, in seconds.
        float currentTime;

        // Count how many times Draw has been called. This is used to know
        // when it is safe to retire old particles back into the free list.
        int drawCounter;

        // Shared random number generator.
        static Random random = new Random();

        #endregion

        #region Initialization

        /// <summary>
        /// Constructor.
        /// </summary>
        public Explosion(Game game, ContentManager content)
            : base(game)
        {
            this.content = content;
        }

        /// <summary>
        /// Initializes the component.
        /// </summary>
        public override void Initialize()
        {
            // Allocate the particle array, and fill in the Corner fields (which never change).
            particles = new ExplosionVertex[MaxParticles * 4];

            for (int i = 0; i < MaxParticles; i++)
            {
                particles[i * 4 + 0].Corner = new Short2(-1, -1);
                particles[i * 4 + 1].Corner = new Short2(1, -1);
                particles[i * 4 + 2].Corner = new Short2(1, 1);
                particles[i * 4 + 3].Corner = new Short2(-1, 1);
            }

            base.Initialize();
        }

        /// <summary>
        /// Loads graphics for the particle system.
        /// </summary>
        protected override void LoadContent()
        {
            LoadParticleEffect();

            // Create a dynamic vertex buffer.
            vertexBuffer = new DynamicVertexBuffer(GraphicsDevice, ExplosionVertex.VertexDeclaration,
                                                   MaxParticles * 4, BufferUsage.WriteOnly);

            // Create and populate the index buffer.
            ushort[] indices = new ushort[MaxParticles * 6];

            for (int i = 0; i < MaxParticles; i++)
            {
                indices[i * 6 + 0] = (ushort)(i * 4 + 0);
                indices[i * 6 + 1] = (ushort)(i * 4 + 1);
                indices[i * 6 + 2] = (ushort)(i * 4 + 2);

                indices[i * 6 + 3] = (ushort)(i * 4 + 0);
                indices[i * 6 + 4] = (ushort)(i * 4 + 2);
                indices[i * 6 + 5] = (ushort)(i * 4 + 3);
            }

            indexBuffer = new IndexBuffer(GraphicsDevice, typeof(ushort), indices.Length, BufferUsage.WriteOnly);

            indexBuffer.SetData(indices);
        }

        /// <summary>
        /// Helper for loading and initializing the particle effect.
        /// </summary>
        void LoadParticleEffect()
        {
            Effect effect = content.Load<Effect>("ParticleEffect");

            // If we have several particle systems, the content manager will return
            // a single shared effect instance to them all. But we want to preconfigure
            // the effect with parameters that are specific to this particular
            // particle system. By cloning the effect, we prevent one particle system
            // from stomping over the parameter settings of another.

            particleEffect = effect.Clone();

            EffectParameterCollection parameters = particleEffect.Parameters;

            // Look up shortcuts for parameters that change every frame.
            effectViewParameter = parameters["View"];
            effectProjectionParameter = parameters["Projection"];
            effectViewportScaleParameter = parameters["ViewportScale"];
            effectTimeParameter = parameters["CurrentTime"];

            // Set the values of parameters that do not change.
            parameters["Duration"].SetValue((float)Duration.TotalSeconds);
            parameters["DurationRandomness"].SetValue(DurationRandomness);
            parameters["Gravity"].SetValue(Vector3.Zero);
            parameters["EndVelocity"].SetValue(EndVelocity);
            parameters["MinColor"].SetValue(MinColor.ToVector4());
            parameters["MaxColor"].SetValue(MaxColor.ToVector4());

            parameters["RotateSpeed"].SetValue(
                new Vector2(MinRotateSpeed, MaxRotateSpeed));

            parameters["StartSize"].SetValue(
                new Vector2(MinStartSize, MaxStartSize));

            parameters["EndSize"].SetValue(
                new Vector2(MinEndSize, MaxEndSize));

            // Load the particle texture, and set it onto the effect.
            Texture2D texture = content.Load<Texture2D>(TextureName);

            parameters["Tex"].SetValue(texture);
        }

        #endregion

        #region Update and Draw

        /// <summary>
        /// Updates the particle system.
        /// </summary>
        public override void Update(GameTime gameTime)
        {
            if (gameTime == null)
                throw new ArgumentNullException("gameTime");

            currentTime += (float)gameTime.ElapsedGameTime.TotalSeconds;

            RetireActiveParticles();
            FreeRetiredParticles();

            // If we let our timer go on increasing for ever, it would eventually
            // run out of floating point precision, at which point the particles
            // would render incorrectly. An easy way to prevent this is to notice
            // that the time value doesn't matter when no particles are being drawn,
            // so we can reset it back to zero any time the active queue is empty.

            if (firstActiveParticle == firstFreeParticle)
                currentTime = 0;

            if (firstRetiredParticle == firstActiveParticle)
                drawCounter = 0;
        }

        /// <summary>
        /// Helper for checking when active particles have reached the end of
        /// their life. It moves old particles from the active area of the queue
        /// to the retired section.
        /// </summary>
        void RetireActiveParticles()
        {
            float particleDuration = (float)Duration.TotalSeconds;

            while (firstActiveParticle != firstNewParticle)
            {
                // Is this particle old enough to retire?
                // We multiply the active particle index by four, because each
                // particle consists of a quad that is made up of four vertices.
                float particleAge = currentTime - particles[firstActiveParticle * 4].Time;

                if (particleAge < particleDuration)
                    break;

                // Remember the time at which we retired this particle.
                particles[firstActiveParticle * 4].Time = drawCounter;

                // Move the particle from the active to the retired queue.
                firstActiveParticle++;

                if (firstActiveParticle >= MaxParticles)
                    firstActiveParticle = 0;
            }
        }

        /// <summary>
        /// Helper for checking when retired particles have been kept around long
        /// enough that we can be sure the GPU is no longer using them. It moves
        /// old particles from the retired area of the queue to the free section.
        /// </summary>
        void FreeRetiredParticles()
        {
            while (firstRetiredParticle != firstActiveParticle)
            {
                // Has this particle been unused long enough that
                // the GPU is sure to be finished with it?
                // We multiply the retired particle index by four, because each
                // particle consists of a quad that is made up of four vertices.
                int age = drawCounter - (int)particles[firstRetiredParticle * 4].Time;

                // The GPU is never supposed to get more than 2 frames behind the CPU.
                // We add 1 to that, just to be safe in case of buggy drivers that
                // might bend the rules and let the GPU get further behind.
                if (age < 3)
                    break;

                // Move the particle from the retired to the free queue.
                firstRetiredParticle++;

                if (firstRetiredParticle >= MaxParticles)
                    firstRetiredParticle = 0;
            }
        }

        /// <summary>
        /// Draws the particle system.
        /// </summary>
        public override void Draw(GameTime gameTime)
        {
            GraphicsDevice device = GraphicsDevice;

            // Restore the vertex buffer contents if the graphics device was lost.
            if (vertexBuffer.IsContentLost)
            {
                vertexBuffer.SetData(particles);
            }

            // If there are any particles waiting in the newly added queue,
            // we'd better upload them to the GPU ready for drawing.
            if (firstNewParticle != firstFreeParticle)
            {
                AddNewParticlesToVertexBuffer();
            }

            // If there are any active particles, draw them now!
            if (firstActiveParticle != firstFreeParticle)
            {
                device.BlendState = blendState;
                device.DepthStencilState = DepthStencilState.DepthRead;

                effectViewportScaleParameter.SetValue(new Vector2(0.5f / device.Viewport.AspectRatio, -0.5f));

                effectTimeParameter.SetValue(currentTime);

                device.SetVertexBuffer(vertexBuffer);
                device.Indices = indexBuffer;

                foreach (EffectPass pass in particleEffect.CurrentTechnique.Passes)
                {
                    pass.Apply();

                    if (firstActiveParticle < firstFreeParticle)
                    {
                        device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0,
                                                     firstActiveParticle * 4, (firstFreeParticle - firstActiveParticle) * 4,
                                                     firstActiveParticle * 6, (firstFreeParticle - firstActiveParticle) * 2);
                    }
                    else
                    {
                        device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0,
                                                     firstActiveParticle * 4, (MaxParticles - firstActiveParticle) * 4,
                                                     firstActiveParticle * 6, (MaxParticles - firstActiveParticle) * 2);

                        if (firstFreeParticle > 0)
                        {
                            device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0,
                                                         0, firstFreeParticle * 4,
                                                         0, firstFreeParticle * 2);
                        }
                    }
                }

                device.DepthStencilState = DepthStencilState.Default;
            }

            drawCounter++;
        }

        /// <summary>
        /// Helper for uploading new particles from our managed
        /// array to the GPU vertex buffer.
        /// </summary>
        void AddNewParticlesToVertexBuffer()
        {
            int stride = ExplosionVertex.SizeInBytes;

            if (firstNewParticle < firstFreeParticle)
            {
                // If the new particles are all in one consecutive range,
                // we can upload them all in a single call.
                vertexBuffer.SetData(firstNewParticle * stride * 4, particles,
                                     firstNewParticle * 4,
                                     (firstFreeParticle - firstNewParticle) * 4,
                                     stride, SetDataOptions.NoOverwrite);
            }
            else
            {
                // If the new particle range wraps past the end of the queue
                // back to the start, we must split them over two upload calls.
                vertexBuffer.SetData(firstNewParticle * stride * 4, particles,
                                     firstNewParticle * 4,
                                     (MaxParticles - firstNewParticle) * 4,
                                     stride, SetDataOptions.NoOverwrite);

                if (firstFreeParticle > 0)
                {
                    vertexBuffer.SetData(0, particles,
                                         0, firstFreeParticle * 4,
                                         stride, SetDataOptions.NoOverwrite);
                }
            }

            // Move the particles we just uploaded from the new to the active queue.
            firstNewParticle = firstFreeParticle;
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Sets the camera view and projection matrices
        /// that will be used to draw this particle system.
        /// </summary>
        public void SetCamera(Matrix view, Matrix projection)
        {
            effectViewParameter.SetValue(view);
            effectProjectionParameter.SetValue(projection);
        }

        /// <summary>
        /// Adds a new particle to the system.
        /// </summary>
        public void AddParticle(Vector3 position, Vector3 velocity)
        {
            // Figure out where in the circular queue to allocate the new particle.
            int nextFreeParticle = firstFreeParticle + 1;

            if (nextFreeParticle >= MaxParticles)
                nextFreeParticle = 0;

            // If there are no free particles, we just have to give up.
            if (nextFreeParticle == firstRetiredParticle)
                return;

            // Add in some random amount of horizontal velocity.
            float horizontalVelocity = MathHelper.Lerp(MinHorizontalVelocity,
                                                       MaxHorizontalVelocity,
                                                       (float)random.NextDouble());

            double horizontalAngle = random.NextDouble() * MathHelper.TwoPi;

            velocity.X += horizontalVelocity * (float)Math.Cos(horizontalAngle);
            velocity.Z += horizontalVelocity * (float)Math.Sin(horizontalAngle);

            // Add in some random amount of vertical velocity.
            velocity.Y += MathHelper.Lerp(MinVerticalVelocity,
                                          MaxVerticalVelocity,
                                          (float)random.NextDouble());

            // Choose four random control values. These will be used by the vertex
            // shader to give each particle a different size, rotation, and color.
            Color randomValues = new Color((byte)random.Next(255),
                                           (byte)random.Next(255),
                                           (byte)random.Next(255),
                                           (byte)random.Next(255));

            // Fill in the particle vertex structure.
            for (int i = 0; i < 4; i++)
            {
                particles[firstFreeParticle * 4 + i].Position = position;
                particles[firstFreeParticle * 4 + i].Velocity = velocity;
                particles[firstFreeParticle * 4 + i].Random = randomValues;
                particles[firstFreeParticle * 4 + i].Time = currentTime;
            }

            firstFreeParticle = nextFreeParticle;
        }

        #endregion
    }
}

```

And here is my HLSL (also HLSL from example)

```
float4x4 View;
float4x4 Projection;
float2 ViewportScale;

float CurrentTime;

float Duration;
float DurationRandomness;
float3 Gravity;
float EndVelocity;
float4 MinColor;
float4 MaxColor;

float2 RotateSpeed;
float2 StartSize;
float2 EndSize;

texture Tex;

sampler TexSampler = sampler_state
{
    Texture = <Tex>;

    MinFilter = Linear;
    MagFilter = Linear;
    MipFilter = Linear;

    AddressU = Clamp;
    AddressV = Clamp;
};

struct VertexShaderInput
{
    float2 Corner : POSITION0;
    float3 Position : POSITION1;
    float3 Velocity : NORMAL0;
    float4 Random : COLOR0;
    float Time : TEXCOORD0;
};

struct VertexShaderOutput
{
    float4 Position : POSITION0;
    float4 Color : COLOR0;
    float2 TextureCoordinate : COLOR1;
};

float4 ComputeParticlePosition(float3 position, float3 velocity, float age, float normalizedAge)
{
    float startVelocity = length(velocity);

    float endVelocity = startVelocity * EndVelocity;

    float velocityIntegral = startVelocity * normalizedAge +
                             (endVelocity - startVelocity) * normalizedAge *
                                                             normalizedAge / 2;

    position += normalize(velocity) * velocityIntegral * Duration;

    position += Gravity * age * normalizedAge;

    return mul(mul(float4(position, 1), View), Projection);
}

float ComputeParticleSize(float randomValue, float normalizedAge)
{
    float startSize = lerp(StartSize.x, StartSize.y, randomValue);
    float endSize = lerp(EndSize.x, EndSize.y, randomValue);

    float size = lerp(startSize, endSize, normalizedAge);

    return size * Projection._m11;
}

float4 ComputeParticleColor(float4 projectedPosition, float randomValue, float normalizedAge)
{
    float4 color = lerp(MinColor, MaxColor, randomValue);

    color.a *= normalizedAge * (1-normalizedAge) * (1-normalizedAge) * 6.7;

    return color;
}

float2x2 ComputeParticleRotation(float randomValue, float age)
{
    // Apply a random factor to make each particle rotate at a different speed.
    float rotateSpeed = lerp(RotateSpeed.x, RotateSpeed.y, randomValue);

    float rotation = rotateSpeed * age;

    // Compute a 2x2 rotation matrix.
    float c = cos(rotation);
    float s = sin(rotation);

    return float2x2(c, -s, s, c);
}

VertexShaderOutput ParticleVertexShader(VertexShaderInput input)
{
    VertexShaderOutput output;

    float age = CurrentTime - input.Time;

    age *= 1 + input.Random.x * DurationRandomness;

    float normalizedAge = saturate(age / Duration);

    output.Position = ComputeParticlePosition(input.Position, input.Velocity, age, normalizedAge);

    float size = ComputeParticleSize(input.Random.y, normalizedAge);
    float2x2 rotation = ComputeParticleRotation(input.Random.w, age);

    output.Position.xy += mul(input.Corner, rotation) * size * ViewportScale;

    output.Color = ComputeParticleColor(output.Position, input.Random.z, normalizedAge);
    output.TextureCoordinate = (input.Corner + 1) / 2;

    return output;
}

float4 ParticlePixelShader(VertexShaderOutput input) : COLOR0
{
    float4 output = tex2D(TexSampler, input.TextureCoordinate) * input.Color;
    return output;
}

technique Particles
{
    pass P0
    {
        VertexShader = compile vs_2_0 ParticleVertexShader();
        PixelShader = compile ps_2_0 ParticlePixelShader();
    }
}

```

# Answer
> 0 votes
Ended up using the example on the site. Realized i was using it wrong and should have used it more like a library.

# Answer
> -1 votes
The first element on your struct ExplosionVertex is position, so the first element in your VertexDeclaration has to be VertexElementFormat.Vector3

Your VertexDeclaration has to describe your particle struct, and the order is very important

```
    public Vector3 Position;
    public Short2 Corner;
    public Color Random;
    public float Time;
    public Vector3 Velocity;

    public static readonly VertexDeclaration VertexDeclaration = new VertexDeclaration
    (
        new VertexElement(0, VertexElementFormat.Vector3,
                            VertexElementUsage.Position, 0),

        new VertexElement(11, VertexElementFormat.Short2,
                            VertexElementUsage.TextureCoordinate, 0),

        new VertexElement(15, VertexElementFormat.Color,
                                VertexElementUsage.Color, 0),

        new VertexElement(19, VertexElementFormat.Single,
                                VertexElementUsage.TextureCoordinate, 1),

        new VertexElement(23, VertexElementFormat.Vector3,
                                VertexElementUsage.TextureCoordinate, 2)
    );

    public const int SizeInBytes = 36;

```

---
Tags: xna, particles
---


title: GUI for DirectX

text:
# Question
Title: GUI for DirectX
I'm looking for a GUI library built on top of DirectX- preferably 9, but I can also do 11. I've looked at stuff like DXUT, but it's way too much for me- I'm only needing some UI controls which I would rather not write (and debug) myself, and their need to keep a C-compatible API is definitely a big downside. I'd rather look at UI libs that are designed to be integrated into an existing DirectX-based system, rather than forming the basis of a system. Any recommendations?

Edit:

I guess that nobody has heard of a DirectX GUI written by someone who has heard of the basics of object-orientation? The purpose of not using DXUT was because using their API was worse than writing my own, and the documentation that starts with `namespace::type::GetInstance()` is *not* qualifying as "better than DXUT".

# Answer
> 6 votes
CEGUI

# Answer
> 3 votes
MyGUI is very good. It works with DirectX as well as OpenGL and OGRE.

# Answer
> 2 votes
In my experience, there's not much available for DirectX, which I think is a great shame. The closest thing I've found is AntTweakBar which (unless you only want the GUI to act as an interface to tweak colours/behaviours/graphics/etc) isn't very fully featured.

Of course I haven't used it very much, so it may have more features to it but check it out at: http://www.antisphere.com/Wiki/tools:anttweakbar

# Answer
> 2 votes
Check out GWEN from the maker of Garry's Mod.

# Answer
> 0 votes
I don't know if this will get you what you're looking for, but here's a MSDN document on WPF and Win32 Interoperation. The section "Hosting WPF Content in a Microsoft Win32 Window" may be of the most interest to you. Also, from the first link: Walkthrough: Hosting WPF in Win32.

While I've never done this, it may be able to get you the benifits you're looking for without having to do too much wheel re-inventing.

# Answer
> 0 votes
Delphi/ C++Builder with FireMonkey

FireMonkey is a cross platform (opengl for mac and directX for windows) gui library which look similar to native controls as possible.

http://www.embarcadero.com/products/firemonkey;

http://www.embarcadero.com/products/delphi

# Answer
> 0 votes
There is also librocket which allows one to implement the render part by yourself. So you will be able to adapt it to DirectX, wich is already done within one of the examples.

Furthermore it's XHTML1.0 and CSS2.0 based and allows you to build your ui as you would build a websie, with some constraints tho.

---
Tags: c++, directx, gui
---


title: Sloped tiles in Platformer

text:
# Question
Title: Sloped tiles in Platformer
I'm extreme new to game development and this is my second project. I’m working on a platform game that expands on the Platformer example provided at the app hub, so far I’ve got parallax scrolling (horizontal and vertical), moving platforms, tight touch controls, double jumps, melee attacks projectiles, and Game State management all working. BUT for the life of me I can’t figure out how to implement sloped tiles. I’ve searched for a ton of tutorials but I can’t find any good ones (by good I mean ones that i can understand). Again I would but grateful for any help that someone could provide.

Here is the code i am using for collisions (I've edit it to try and incorporate the code from the link below but still no luck. it runs but this code still treats the sloped tile as if they were regular tiles:

Edited Code

```
    /// <summary>
    /// Detects and resolves all collisions between the player and his neighboring
    /// tiles. When a collision is detected, the player is pushed away along one
    /// axis to prevent overlapping. There is some special logic for the Y axis to
    /// handle platforms which behave differently depending on direction of movement.
    /// </summary>

     private void HandleCollisions()
    {
        // Get the player's bounding rectangle and find neighboring tiles.
        Rectangle bounds = BoundingRectangle;
        int leftTile = (int)Math.Floor((float)bounds.Left / Tile.Width);
        int rightTile = (int)Math.Ceiling(((float)bounds.Right / Tile.Width)) - 1;
        int topTile = (int)Math.Floor((float)bounds.Top / Tile.Height);
        int bottomTile = (int)Math.Ceiling(((float)bounds.Bottom / Tile.Height)) - 1;

        // Was the player on a ramp last frame?
         bool wasOnRamp = isOnRamp;

        float dist =
            (float)Math.Sqrt
            (Math.Pow
            (MathHelper.Clamp
            (bounds.Center.X - bounds.Left, 0, Tile.Width), 2) +
            Math.Pow
            (MathHelper.Clamp
            (bounds.Bottom - bounds.Bottom, 0, Tile.Height), 2));

        float slopeTopLeft =
            (bounds.Bottom -
            ((bounds.Center.X - bounds.Left) *
            (float)Math.Sin
            (Math.Atan2
            (bounds.Height,
            (bounds.Center.X - bounds.Left)))));

        float slopeTopRight =
            (bounds.Bottom -
            ((bounds.Center.X - bounds.Right) *
            (float)Math.Sin
            (Math.Atan2
            (bounds.Height,
            (bounds.Center.X - bounds.Right)))));

        // Reset flag to search for ground collision.
        isOnGround = false;
        isOnRamp = false;

        //For each potentially colliding movable tile.
        foreach (var movableTile in level.movableTiles)
        {

            // Reset flag to search for movable tile collision.
            movableTile.PlayerIsOn = false;

            //check to see if player is on tile.
            if ((BoundingRectangle.Bottom >= movableTile.BoundingRectangle.Top) &&
                (BoundingRectangle.Left >= movableTile.BoundingRectangle.Left - (BoundingRectangle.Width)) &&
                (BoundingRectangle.Right <= movableTile.BoundingRectangle.Right + (BoundingRectangle.Width)))
            {
                if ((BoundingRectangle.Bottom < movableTile.BoundingRectangle.Top + 5))
                {

                    movableTile.PlayerIsOn = true;

                }

            }

            bounds = HandleCollision(bounds, movableTile.Collision, movableTile.BoundingRectangle);
        }

        //  for (int x = leftTile; x <= rightTile; ++x)
        // {
        //  TileCollision collision = Level.GetCollision(x, bottomTile);
        // if (collision == TileCollision.SlantedUp || collision == TileCollision.SlantedDown)
        // {
        //    isOnRamp = true;
        // }
        // }

        // For each potentially colliding tile,
        for (int y = topTile; y <= bottomTile; ++y)
        {
            for (int x = leftTile; x <= rightTile; ++x)
            {
                // If this tile is collidable,
                TileCollision collision = Level.GetCollision(x, y);

                /*
                if (collision == TileCollision.SlantedUp)
                {
                    //create a rectangle collision box
                    Rectangle tileCol = Level.GetBounds(x, y); //new Rectangle(x * Tile.Size, (y * Tile.Size), Tile.Size, Tile.Size + 1);

                    //if player collision "col" collides with "tileCol" and you haven't done this before this itteration (only happens once per full double loop)
                    if (bounds.Intersects(tileCol) && !isOnRamp)
                    {

                        //get the angle of the tile
                        float angle = level.angle;  // [level.tile[x, y]];

                        //get the x distance of how far away the player's right is inside the tile
                        float dist = (bounds.X + bounds.Width) - tileCol.X;

                        //constructs the opposite of a right triangle
                        float opposite = (float)(Math.Tan(MathHelper.ToRadians(angle)) * (dist));

                        if (angle < 90)
                        {
                            //if player's right is less then or equal to tile's right
                            if (bounds.X + bounds.Width <= tileCol.X + tileCol.Width)
                            {
                                //place player on slope. this works properly
                                position.Y = tileCol.Y - opposite;
                                //tell the program we don't wanna go through this again until the next full loop starts.
                                isOnRamp = true;
                            }
                        }

                        else if (angle > 90)
                        {
                            if ((bounds.X + bounds.Width) >= tileCol.X)
                            {
                                //this is where the error is. the player goes "up" a slope that's 315 degrees, instead of down it.
                                //how do I make the player go down the slope that's 315 degrees!?
                                position.Y = tileCol.Y + opposite;
                                isOnRamp = true;
                            }
                        }
                    }

                }

                */

                //If we touched a checkpoint tile, set our new checkpoint here
                if (collision == TileCollision.Checkpoint)
                    level.checkpoint = new Vector2(x, y) * Tile.Size;

                if (collision != TileCollision.Passable)
                {
                    float angleInRadians = MathHelper.ToRadians(45);
                    float m = (float)Math.Sin(angleInRadians) / (float)Math.Cos(angleInRadians);

                    // Determine collision depth (with direction) and magnitude.
                    Rectangle tileBounds = Level.GetBounds(x, y);
                    Vector2 depth = RectangleExtensions.GetIntersectionDepth(bounds, tileBounds);
                    if (depth != Vector2.Zero)
                    {
                        float absDepthX = Math.Abs(depth.X);
                        float absDepthY = Math.Abs(depth.Y);

                        // List<TileEdge> collidableEdges = Level.GetCollidableEdges(x, y);

                        // Resolve the collision along the shallow axis.
                        if (absDepthY < absDepthX || collision == TileCollision.Platform)
                        {
                            // If we crossed the top of a tile, we are on the ground.
                            if (previousBottom <= tileBounds.Top)
                                isOnGround = true;

                            // Ignore platforms, unless we are on the ground.
                            if (collision == TileCollision.Impassable || IsOnGround)
                            {
                                // Resolve the collision along the Y axis.
                                Position = new Vector2(Position.X, Position.Y + depth.Y);

                                // Perform further collisions with the new bounds.
                                bounds = BoundingRectangle;
                            }
                        }
                        else if (collision == TileCollision.Impassable) // Ignore platforms.
                        {
                            // Resolve the collision along the X axis.
                            Position = new Vector2(Position.X + depth.X, Position.Y);

                            // Perform further collisions with the new bounds.
                            bounds = BoundingRectangle;
                        }

                        else if (collision == TileCollision.SlantedUp)
                        {
                           // float dist = (bounds.X + bounds.Width) - depth.X;
                           // float opposite = (float)(Math.Tan(MathHelper.ToRadians(45)) * (dist));

                           //  float a = Position.X - bottomTile;

                            //bounds = m * a + absDepth.Y;

                           //  Position = new Vector2(Position.X + depth.X, Position.Y - opposite);

                           // bounds = BoundingRectangle;

                            // Resolve the collision along the Y axis.
                            Position = new Vector2
                                (Position.X, slopeTopLeft);
                            Position = new Vector2
                                ((float)Math.Round(Position.X),
                                (float)Math.Round(Position.Y));

                            // Perform further collisions with the new bounds.
                            bounds = BoundingRectangle;
                       }

                    }
                }
            }
        }

        // Save the new bounds bottom.
        previousBottom = bounds.Bottom;
    }

    private Rectangle HandleCollision(Rectangle bounds, TileCollision collision, Rectangle tileBounds)
    {
        Vector2 depth = RectangleExtensions.GetIntersectionDepth(bounds, tileBounds);
        if (depth != Vector2.Zero)
        {
            float absDepthX = Math.Abs(depth.X);
            float absDepthY = Math.Abs(depth.Y);

            // Resolve the collision along the shallow axis.
            if (absDepthY < absDepthX || collision == TileCollision.Platform)
            {
                // If we crossed the top of a tile, we are on the ground.
                if (previousBottom <= tileBounds.Top)
                    isOnGround = true;

                // Ignore platforms, unless we are on the ground.
                if (collision == TileCollision.Impassable || IsOnGround)
                {
                    // Resolve the collision along the Y axis.
                    Position = new Vector2(Position.X, Position.Y + depth.Y);

                    // Perform further collisions with the new bounds.
                    bounds = BoundingRectangle;
                }
            }
            else if (collision == TileCollision.Impassable) // Ignore platforms.
            {
                // Resolve the collision along the X axis.
                Position = new Vector2(Position.X + depth.X, Position.Y);

                // Perform further collisions with the new bounds.
                bounds = BoundingRectangle;
            }

        }
        return bounds;
    }

```

# Answer
> 8 votes
Sorry codeless answer here, though hopefully you will find quite useful if you can bothered writing the simple code to accompany the technique.

This is a technique i use quite a bit in platformers to handle slopes. I call it the "5 Point Collision" technique.

Basically, your character has 5 main points associated with them, as shown in the image above.

2 head collision points (green) 2 wall collision points (red) 1 ground collision point (yellow)

Every step of the game you check collision on each of these 5 points when moving. If either of the head collision points are hit, you have jumped to high! If either of the wall collision points are hit, you have hit a wall, and if your ground collision point is hit, you have hit the ground, and should move your character up a pixel (until it no longer detects ground).

So how does this handle slopes?

Well if you look at the image above, you'll notice that some things may be low enough to pass under the wall collision points, and then hit the ground collision point, forcing the character to move upwards. This means if you had a slope, if the slope is too great, it will hit the wall collision point before the ground collision point; no access. However if the slope is low enough, it shall hit the ground collision point before the wall collision point, moving the character up, and therefore making the character walk up the slope.

Extra points can be added for collision detection to improve mechanics, though remember every point you add means more calculations...

Adding two ground collision points, and spreading them evenly along the bottom sometimes helps. The further the ground collision points are from the middle, the steeper slopes are that the player can handle. Alternatively you could just make the wall collision points higher up, but this may not end well (your character may end up "Jumping" onto obstacles. So my advice is keep the wall collisions reasonably low, (remember if the head collision points are in the corner as shown in my image, then they can also act as wall collision points).

Sorry don't have access to any code to help you out here, and its 1am, too tired to think of it off the top of my head.

Hope it helps you, and if not, someone else who glances by :)

# Answer
> 5 votes
If you know what the angle of the tile is then you can just find the gradient of the slope:

```
// angle is the angle of the sloped tile
// m is the gradient = rise/run
// c is the offset up of the slope, you may want to make it negative as the computer
// screen coordinates are upside down.

float angleInRadians = MathHelper.ToRadians(angle);
float m = Math.Sin(angleInRadians)  // Sin gives us the height, and Cos gives us the width
       /  Math.Cos(angleInRadians); // It's best to only work this out once (like in LoadContent)

float x = playerX - tileX; // playerX is the x coordinate of the player
                           // tileX is the x coordinate of the tile's bottom left corner

// y = mx + c
playerY = m * x + tileY; // In this case, c will be the y coordinate of the bottom left corner of the sloped tile.

```

---
Tags: xna-4.0
---


title: I want to split the texture width

text:
# Question
Title: I want to split the texture width
Simple question:

I have this image that is 200x200. I want to change it to 100x200 inside the HSLS, making it thin. Anyone have idea? I tried to do something like

```
output *= tex2D(CustomTextureSampler, float2(input.UV.x*2,input.UV.y));

```

Didn't work. it simple returns black.

# Answer
I got the answer, lost all day, then I posted here I figured out:

```
output *= tex2D(CustomTextureSampler, float2((input.UV.x-0.5)*2,input.UV.y));

```

I was failing in it before before I was trying to do something like:

```
output *= tex2d(CustomTextureSampler, (input.UV-float2(0.5,0)) * float2(2,1));

```

and it wasnt working, seems like the UV and float2 couldn't make math between themselves.
> 1 votes

---
Tags: xna-4.0
---


# Question
Title: Create a website that lists all the game servers from a country
I have seen some sites which shows servers(for online games) from various parts of world with there name and ip's. I am looking forward to develop something of same sort.

But the issue is how to get all the IP's of servers playing a certain game. Is there any criteria for the same. For eg: I want to list all online servers from US which are playing Counter Strike and also to get the players in it and other info.

# Answer
It's different for each game. For Valve games that don't use the P2P server technology (CS 1.6, DoD 1.3, CS:S etc), there will be a list of server IPs that Valve will maintain. I don't believe that Valve publishes how to to access this list, so you may have to figure that part out yourself using tools like WireShark.

Once you get this list, you will need to connect to each IP using a specific port and figure out how to ask each server for its current information (map, player count, etc). This part will likely be using UDP. Again, I doubt that Valve or other companies will publish how to do this and you'll have to figure it out yourself.

I'll elaborate on what I said at the top: this process will be roughly the same for all games with a server list, but the ports and protocols will all be different for different developers.

As for listing which server is in what country, hopefully the server provides that information, but if it doesn't you can use something like GeoIP: http://en.wikipedia.org/wiki/Geolocation\_software
> 2 votes

---
Tags: web
---


# Question
Title: Rotate a bitmap and bitmap is getting blur in android
I am developing an android game. and in this I want to move an object along a Bezier path.

my object is rotating with some angle on this curve.

I used this piece of code:

```
public void update() {

        // check collision with bottom wall if heading down
        if (droid.getSpeed().getyDirection() == Speed.DIRECTION_DOWN
                && droid.getY() + droid.getBitmap().getHeight() / 2 >= getHeight()/2 &&
                droid.getY() + droid.getBitmap().getHeight() / 2 <= getHeight()/2+ 100 ) {

            int pointX[], pointY[];
            pointX = new int[4];
            pointY = new int[4];
            int  X , Y;

                pointX[0] = getWidth()/2;
                pointX[1] = getWidth()/2 + 50;
                pointX[2] = getWidth()/2 + 25;
                pointX[3] = getWidth()/2;
                pointY[0] = getHeight()/2;
                pointY[1] = getHeight()/2 + 25;
                pointY[2] = getHeight()/2 + 50;
                pointY[3] = getHeight()/2 + 100;

                Log.i(TAG, "In the While Zone of Last Half Zone");
                X = (int) ((pointX[3] * u * u * u) + (3 * pointX[2] * u * u * (1-u)) + (3 * pointX[1] * u * (1-u) * (1-u)) +
                    (pointX[0] * (1-u) * (1-u) * (1-u)));

                Y = (int) ((pointY[3] * u * u * u) + (3 * pointY[2] * u * u * (1-u)) + (3 * pointY[1] * u * (1-u) * (1-u)) +
                        (pointY[0] * (1-u) * (1-u) * (1-u)));

                Log.i(TAG+" Value of X: ", Double.toString(X));
                Log.i(TAG+" Value of Y: ", Double.toString(Y));

                double deltaX = X - droid.getX();
                double deltaY = Y - droid.getY();

                Log.i("deltaX :", Double.toString(deltaX));
                Log.i("deltaY :", Double.toString(deltaY));

                double angle = Math.atan2(deltaY, deltaX)  ;
                Log.i(TAG+" Angle: ", Double.toString(angle));
                Matrix mtx = new Matrix();
                mtx.preRotate((float) angle);
                mtx.postScale(1, 1);

                Bitmap rotatedBMP = Bitmap.createBitmap(droid.getBitmap(), droid.getX(), droid.getY(),  X - droid.getX(), Y - droid.getY(), mtx, true);
                droid.setBitmap(rotatedBMP);
                droid.curveUpdate(X, Y);
                u = u + 0.001;
                Log.i(TAG+" Value of U: ", Double.toString(u));

        }
        // check collision with top wall if heading up

        // Update the lone droid
        else{
            droid.update();
        }

    }

```

my object is moving and rotating as i supposed but image is getting blur. am not getting why is so.

Please suggest what can be the problem.

Thanks.

# Answer
Rotating a bitmap will always result in a blurred image - there is no way around that. (Except for rotations of 90/270/360 degrees.) Even high-end programs like photoshop cannot work around the issue - but they mitigate it.

First, a bitmap stores its information pixel per pixel. So you have a large grid of pixels that composes the image. To see it in action, open you favorite bitmap painting tool and zoom in to the max. At that point, you can see the individual pixel that composes an image.

Those pixels are always arranged in a grid of horizontal rows and vertical columns. Always vertical and horizontal. This is where the rotation problem arise...

The image above shows what is going on. In the top left you have an example bitmap. Notice that its rows and column are horizontal and vertical. In the bottom right, you first have the same bitmap, with a slight rotation. But as I explained earlier, you cannot leave rows non-horizontal, so you have to transcribe the rotated image to an horizontal/vertical grid (shown in red in the image).

By the way, each square represents a pixel. As you can see the pixels of the red grid do not align cleanly with the bitmap behind. (In fact the bitmap is now a little bit larger than it used to be - another effect of the rotation.) To figure how each of the grid pixel should be colored, you take an average of the pixels in the bitmap overlapping the pixel you want to draw.

Which, of course, results is colors that are slightly different and therefore a blurred image.

The technique you use to average the color are varied and some result it much much better images, but they also take longer to evaluate.

I suspect that the Android .createBitmap image does do a good job at it. You have a few solutions:

* there may be a different library for bitmap manipulation for Android
* use opengl quad's, they do a good job at rotations
* use image magick to create sprites of pre-rotated images

If you are not using OpenGL, then most games load sprite sheets with rotation already done (see other image).. You only need a quadrant worth of rotation pre-calculated. It saves memory and you can rotate on the fly to 90/180/270 without loosing quality to cover the other 4 quadrant (going back to the first figure, notice that the grids will align perfectly with rotations of 90/180/270 degrees).
> 5 votes

# Answer
I'm not an android developer but after taking a quick look in to the documentation I will try to speculate...

The last parameter of Bitmap.createBitmap is filter. If it's set then the function will do bi-linear or tri-linear (if there is scale) filter, which will look like blur. I'm afraid that if you disable this you will like the result even less. My guess is that you are using some pixelated art style that will just not work well.

If a pixelated art style is what you are using and is what you want I suggest that you manually draw a few frames on different angles and pick the closest one depending of the normal of the curve.

Note: Bi-linear and tri-linear filtering are what games use these days but the textures should not be super high frequency. Like if you make a checkerboard texture with pixel size squares after transformation it will look really bad no matter what hardware or drawing API you are using.
> 0 votes

---
Tags: android
---


# Question
Title: How common is automated testing in game development?
Do gamers developers use to write unit and integration tests? How common is it among puzzle developers? And among developers of MMORPGs and FPSes?

(I have no background in game development neither am I cogitating about working with it - it is just a doubt that occurred to me. So, no need of trying to *convince* me to write them, even because I already like to write automated tests.)

# Answer
In general, unit and integration testing of games isn't that common. This is mostly because the rendering aspect of games is usually closely tied to the rest of the game mechanics that it can be very hard to actually write unit tests that work.

That said, unit testing can happen in game development, and if the code is set up for it, it can be of great benefit. However, it can be much more common to write automated tests for games, usually in the form of an AI program that can effectively play the game at a higher speed than a normal player. There's some excellent stories of developers doing just that in this question about automated testing. This sort of automated testing is potentially better, since unit testing might not catch a bug in the rendering engine, but an automated test is more likely to expose such a problem.

In the end, though, this all depends on the studio. Some studios will some sort of automated testing, while others might just hire 20 high school kids over the summer to play their game for hours on end.
> 40 votes

# Answer
In my experience, it's not very common.

Mostly unit testing doesn't occur because most game developers come from a time and culture before things like that were widespread, and therefore it's hard to make the argument now that such methods are necessary. This has become even more true in recent years with the expectation that the user is able to patch his own software after release.

Partly it's because the dominant language in the game development industry is C++ and that makes unit testing a little more cumbersome than other languages. Unit testing frameworks exist but they are not as easy to use as similar systems in more modern languages that can use reflection and similar tricks to speed up the detection of test cases.

Also, it's because games don't generally lend themselves to unit testing - much of the logic depends on semi-deterministic sources (eg. graphics hardware, input timings, the frame rate), much of the output is hard to measure (eg. on-screen graphics, sound effects) and some is almost meaningless outside of the full game context making (eg. complex reactive AI, physics simulations). There are exceptions - many, if you work hard to make the code that way - but on the whole testing is more expensive in games than in most other types of software and so the cost/benefit ratio is more dubious.

As for integration testing, I've never heard of the term being explicitly used in game development but many developers do conduct automated tests of the whole system where possible. At a guess I'd say maybe 1 in 3 pro developers do this, as it's not always easy to set up, and because the benefits are reduced by the fact that pretty much every medium to large developer (or their publisher) has a QA department that will manually perform similar tests. QA are typically paid much less than developers so it may be considered economical to leave testing to them, rather than to invest extra code time on it. (Controversial.)
> 19 votes

# Answer
In general automating UI testing (even in regular programs) is harder than regular automation. So even though you can write unit tests for your games, testing the actual game is harder. Most companies use human testers that run the game time and again.

For example Here is an article explaining how they do it in a small Game Studio (2 devs). From what I read it seems like their validation is not very detailed (automation starts the game and logs any errors/asserts).

However some companies are very successful with semi automation (Such as Microsoft Test Studios). That is, Developers or SDETs build tools that make testing the game much easier. There have been Gamefest talks where they discuss how they tested Crackdown for example or Fable. For example, they still use testers that verify that every object is where it's supposed to be but they use a tool that takes a snapshot of that location so that all that the human does is visually verify it is there without having to play the game.

Here is a good talk on what kind of tools they build/use to test the games. It's called "Test Lead Gems: Getting Out in Front of the Increasing Complexity of Our Games"
> 9 votes

# Answer
I don't see how writing a game is different to any other piece of software as far as testing goes. Each component of the software, whether it be triggering a timed event, sending commands to an in-game character, or pressing menu buttons, should be tested for proper execution.

Testing whether the game is possible to complete is a different matter and doesn't fall under unit or integration testing so much.
> 8 votes

# Answer
I participated in a roundtable discussion about automated testing at GDC 2011. IIRC, there were about 60 people in the room. At one point the moderator took a survey of unit test coverage. There was *one person* who claimed greater than 90% code coverage. Everyone else laughed at the thought of ever reaching **1%** coverage. If that group is a fair representation of the industry as a whole, I'd say automated testing generally doesn't happen much, if at all.

The other answers here give good reasons as to why. I just thought it would be useful to have a first-hand account.
> 4 votes

# Answer
I would wager that MMO and multiplayer server code, however, is a bit more often tested.

At the very least, automated regression tests have been common. I've seen these implemented as mass sanity-checks during server start-up, to e.g. make sure that a new "cloud" server was configured correctly before it begins accepting players; a fairly good regression suite built up over 3-4 years, in that case, ran in about 4 seconds, while bringing up a virtual host (from a blank OS image) took almost 10 minutes, so it was well worth the time. We ran the same tests on a "tinderbox" (continual build system) on our Subversion repository to check for some annoying, fairly common errors that liked to creep back in. In particular, the multi-server functionality had a nasty habit of trying to create duplicates of objects as they were passed around: the object instantiation, caching, and network-passing code was close to 100% covered; we kept thinking we'd thought of everything that could be tested, and then discover some “fun,” new edge case.

At several MMO's that I've worked on, we also would develop "stub clients" to perform initial unit-testing, and usually provided "operator" commands to do ad-hoc unit testing of new features. This let us execute server code before the client was ready to take advantage of it, and exercise "impossible" situations (e.g. teleporting a player inside of a wall) to ensure that the error recovery handlers would work well. Bringing a new feature online on the server might sometimes take many days less than the client support for it; conversely, we'd sometimes have to create a "dummy" server method for the client, returning fake-but-well-formed data, if they got ahead of us.

However, MMO development in general is subject to a lot more of these kinds of problems, which might reflect the environment. When I was working on embedded game systems, “testing” was practically unheard-of for anything except some reusable widget code (e.g. text editors).
> 4 votes

# Answer
Another reason why automated testing is not that common in Game Development that may be considered is that for most games there are plenty of Beta testing volunteers who preceive Game Beta participation as an "edge" when the game is released. Automated testing has of course grown out of quality requirements, but also out of budget restrictions. Therefore, since in gaming there are plenty of experienced testers who are prepared to test for free, perhaps this is another reason automated tests are not that widespread.
> 3 votes

---
Tags: unit-testing
---


# Question
Title: Pre Computing shadows, advantages/disadvantages?
Today I was looking at a still frame of a game, and noticed that all of the shadows were dynamic (created per frame). As we know, shadows can be quite expensive. I was wondering why shadows could not be simply mapped at run time for non moving objects, and then only do dynamic shadows for players, vehicles, etc. What are the advantages/disadvantages of doing this?

# Answer
> 4 votes
Disadvantages:

* Lightmaps are very large textures. If you have enough processing to make all shadows dynamic you can probably use the memory for something else.
* Non unified lighting model. Some lighting models like deferred don't mix well with prebaked shadows.
* Light mappers are usually very slow. You need to wait few hours to preview lighting changes in the scene.
* You can't pre-bake lights in case that light sources are moving even if everything else the scene is static.

Advantages:

* You can have much higher quality shadows and lighting.
* Faster processing
* Virtually unlimited number of light sources can be used

---
Tags: shadows
---