# Question
Title: XNA 4.0 and Lidgren Library, How do I create a server/client hybrid?
My use of terminology may be off a little bit. I have been playing around with the Lidgren XNA sample for how the library works, and it is simple to implement it looks like.

I am curious on the logic or theory behind making the game client also act as a server? Basically I want a user to open the game client and have the option of "Hosting a Game" which would allow others to connect to that computer and play multiplayer.

It was suggested that I use some sort of thread to kick off the server code in the background for that host client and then connect the two pieces together for full functionality.

# Answer
This is a quote of my comment earlier so this question can be resolved:

> "It was suggested that I use some sort of thread to kick off the server code in the background for that host client and then connect the two pieces together for full functionality." This is exactly how hosting your own game should work. Just a second thread or a new process on the host's machine that he can then join himself as well.
> 1 votes

---
Tags: xna, c#, networking, client-server
---


# Question
Title: Abstracting Entity System animation states
I recently started designing a Game Engine using the Entity System paradigm, i.e. having entities as an aggregation of components, and systems that implement the actual game. Whereas I've had difficulties in various aspects, what concerns me most is the abstraction / modularity of the various Components / Systems. Specifically, let's say my `Player` has several animation states, eg. `Walking`, `Sleeping`, `Jumping`, and one type of `Opponent` entity has several (not necessarily the same) states as well, eg. `Walking`, `Hiding` etc.

How should I design the engine, so that it handles the various (animation) states of each entity type? Should there be different animation Systems for each Entity type? Should I use flags that signal the animation System to render the correct entity? Also, can I avoid using "hard-coded" enums for the various poses? I can see that a scripting system could probably help, but I'm almost sure there is a simpler solution.

# Answer
> 4 votes
No to different systems for each type, that's cutting the division of responsibility too fine.

This is what I'm doing in my current personal project:

There are many ways to handle state but you probably need one that makes sense to humans, or at least a bridge between human and code. You have to think of the **animation system as a big blender** instead of one of discrete states, for example you go from idle to walking slowly by adding 50% walk to the system and then later add 100% run.

External to the animation system you can use strings to make working with the system agreeable and easy to scripts and code alike. Internal to the system you build a **mapping between that string and the animation data**, this can be done with a key-value store like a hashmap (to avoid enums altogether by making the animation data the store) or with a string-to-enum lookup if you like working that way. It's all a matter of taste at that point. I prefer key-value since it can be totally data driven from XML or INI files.

To handle different types you can, at the system layer, allow for **creating sets of mapping of animations** so that set for "minion" and "run" for the "minion" is different than the set for "run" and "female player" type.

In summary: the animation system is generic and you only have one system; the outside world needs a friendly interface; the inside world needs to map generic states to entity types.

And my list of things I want to do but don't fit into my design yet:

*TODO*: mapping movement speed to animation type automatically so instead of having the main program know about "walk" versus "run" the animation system can convert "move at x speed" to the proper animation.

*TODO*: split animations like head and torso tracking in a transparent way.

*TODO*: reaction animations (like getting punched in the face) handled by the system and not the main program.

---
Tags: animation, entity-system
---


# Question
Title: Picking 2D objects after transforming camera in XNA
I have an XNA application (a force based visualisation of some circles) that I've implemented zooming and scrolling in, thanks to this guide.

Before I had the camera implemented, I had picking implemented (click and drag a circle to move it around). However, after the camera transformation I'm struggling to match up my mouse X,Y coordinates with the post-transformation coordinates of my circles.

I attempted to multiply my mouse X,Y vector with my camera transformation matrix. Given a mouse click at (356, 492), after translation I get (713,300), but my objects are around (-1000,900) or so.

So, given a mouse click in local X,Y coordinates and circle locations in post-transformation X,Y coordinates, how do I match them up?

(If it's needed, my VS2010 project is here.)

# Answer
> 5 votes
The view matrix transforms from world space to view space. Your mouse is in view space and you want to transform it into world space. That's the *opposite* of what the view matrix does. But the solution is simple - just multiply by the *inverse* view matrix instead.

```
Matrix inverseViewMatrix = Matrix.Invert(camera.ViewMatrix);
Vector2 worldMousePosition = Vector2.Transform(mousePosition, inverseViewMatrix);

```

You can then match that location against your world space circles.

# Answer
> 0 votes
You can also use method Viewport.Unproject(...).

---
Tags: xna, picking
---


# Question
Title: Where should I place my reaction code in Per-Pixel Collision Detection?
I have this collision detection code:

```
public bool PerPixelCollision(Player player, Game1 dog)
{
    Matrix atob = player.Transform * Matrix.Invert(dog.Transform);

    Vector2 stepX = Vector2.TransformNormal(Vector2.UnitX, atob);
    Vector2 stepY = Vector2.TransformNormal(Vector2.UnitY, atob);

    Vector2 iBPos = Vector2.Transform(Vector2.Zero, atob);

    for(int deltax = 0; deltax < player.playerTexture.Width; deltax++)
    {
        Vector2 bpos = iBPos;
        for (int deltay = 0; deltay < player.playerTexture.Height; deltay++)
        {
            int bx = (int)bpos.X;
            int by = (int)bpos.Y;

            if (bx >= 0 && bx < dog.dogTexture.Width && by >= 0 && by < dog.dogTexture.Height)
            {
                if (player.TextureData[deltax + deltay * player.playerTexture.Width].A > 150 && dog.TextureData[bx + by * dog.Texture.Width].A > 150)
                {
                    return true;
                }
            }
            bpos += stepY;
        }
        iBPos += stepX;
    }
    return false;
}

```

What I want to know is where to put in the code where something happens. For example, I want to put in `player.playerPosition.X -= 200` just as a test, but I don't know where to put it. I tried putting it under the `return true` and above it, but under it, it said unreachable code, and above it nothing happened. I also tried putting it by `bpos += stepY;` but that didn't work either. Where do I put the code?

# Answer
> 3 votes
It sounds like you need to learn how to use the debugger. I found a dubugger tutorial for XNA in parts One and Two. It says advanced, but it starts out pretty basic with breakpoints and ramps up from there.

If you want to test your collision code, you can set a break point at the top and step through it, or you can set breakpoints at the return case you want to look at. I recommend starting with setting the breakpoint at the top and stepping though your code. I think you're at a pretty beginner level, and it would be very valuable to see how your code is actually executed. Once you look at this enough I think you'll be able to figure out why putting code after a return statement will never be reached.

---
Tags: xna, collision-detection
---


# Question
Title: I am looking for a simple tutorial for sprite animation in android
> **Possible Duplicate:**
> What's the best way to create animations when doing Android development?

I saw a couple of them on the internet but they are beyond my level of understanding ...I need to start with basics in a simpler way if possible...can anyone guide me to some good online resources for this

# Answer
This link might help you: http://www.droidnova.com/2d-sprite-animation-in-android,471.html

A quick google on "Sprite animation android" would yield alot of nice answers.

However, since you mentioned that most were beyond your level of understanding, I suggest you look at the following article on sprites first: http://www.rpgrevolution.com/tutorial/rough-guide-to-sprite-animation\_107.html

In short, the computer would divide a sprite sheet into many frames, and cycle through the frames repeatedly to simulate an animation effect.

The best way is to simply follow through a tutorial. You might not understand it at first, but copying and pasting codes helps in understanding as well.

Cheers!
> 0 votes

---
Tags: android
---


title: Collision within a poly

text:
# Question
Title: Collision within a poly
For an html5 engine I'm making, for speed I'm using a path poly. I'm having trouble trying to find ways to get collision with the walls of the poly. To make it simple I just have a vector for the object and an array of vectors for the poly. I'm using Cartesian vectors and they're 2d.

Say **poly = \[\[550,0\],\[169,523\],\[-444,323\],\[-444,-323\],\[169,-523\]\]**, it's just a pentagon I generated.

The object that will collide is **object**, **object.pos** is its position and **object.vel** is it's velocity. They're both 2d vectors too.

I've had some success to get it to find a collision, but it's just black box code I ripped from a c++ example. It's very obscure inside and all it does though is return true/false and doesn't return what vertices are collided or collision point, I'd really like to be able to understand this and make my own so I can have more meaningful collision. I'll tackle that later though.

**Again the question is just how does one find a collision to walls of a poly given you know the poly vertices and the object's position + velocity?** If more info is needed please let me know. And if all anyone can do is point me to the right direction that's great.

# Answer
This might not directly answer your question, but to make things much simpler for you I would recommend you use box 2d.

There are 2 implementation for javascript:

* box2dweb which is the most up to date convert of a port.
* box2d js which is the first (older direct port)

This lib is really good at 2d physics/collisions.
> 1 votes

---
Tags: collision-detection, javascript, html5
---


title: Baking Key Frame Animation in Blender

text:
# Question
Title: Baking Key Frame Animation in Blender
I have a rigged model using an armiture in blender, I was wonder how you could bake the animation as kayframed data so that I could remove the armiture and the model still walks without being rigged.

# Answer
> 1 votes
This is a somewhat manual process but works without any plugins in 2.5 and later. For each keyframe you want to 'bake' you need to insert a VisualLocation, VisualRotation or VisualLocRot keyframe in the target armature. After this you can unparent your control rig and the target still moves as it used to.

---
Tags: animation, blender
---


# Question
Title: 2D side scroller - How to implement X/Y movement?
I'm currently writing a small 2D, side-scroller-ish kind of game.

I have a simple camera that follows the player around and the physics are ready.

I'm using 32x32 tiles that build out the world, they are all stored in a 2D array, something along this:

```
[ 0, 0, 0, 0,
  0, 0, 0, 0,
  1, 1, 0, 1,
  1, 1, 1, 1  ]

```

The 1s are land and 0s are air.

Now the world is dynamic and I want it to be quite large (1 big world) around 1000x800 tiles total.

My biggest issue atm is how to implement the "scrolling effect". Also keep in mind that the player can go in any direction (up/right/left/right).

Thanks

# Answer
> 3 votes
Handling large worlds requires two things.

First, you want to break your world into a grid of macro cells. Think of the tiles you are using for the world, but on a bigger level. Each cell might have 32x32, 64x64, or even 128x128 tiles in it. The advantages of this approach are that memory accesses will be quicker, it's easier to figure out which in-world objects are close to the player and hence should be active or inactive, and you can page and unpage the cells for on-deman loading of game world content.

The second problem to deal with is how you deal with you world coordinates. For large enough game worlds, a floating point number loses too much accuracy. When objects are near the frites of the world this inaccuracy can result in very noticeable glitches. Fixes include switching to doubles, using two sets of position vectors (an integer vector to denote cell or tile and a float to denote position in the cell/tile). Keep in mind that for the latter approach you will need to convert into float vectors for physics and graphics; when doing so, convert to positions relative to the camera and not the world origin, so that there are never any inaccuracies in the players view.

Complementary to both of those is the idea of just sleeping/disabling all game objects far away from the camera. If the player can't see something, there's no reason to do it. That allows you to potentially unload whole cells from memory ( useful if you have a lot of game data per cell and want to support memory-constrained mobile or console devices ), and it means that you will never have to deal with float inaccuracy and can simply use camera- relative floats for physics and graphics always.

# Answer
> 0 votes
```
  if player.x > (screen.width-300) or player.x < 300:
     everything.x -= player.dx
  if(player.y > (screen.height-300) or player.y < 300:
     everything.y -= player.dx

```

By player.dx and dy, I mean the player's x and y velocities. By everything, I mean every object on the screen, including the player (because you both add and subtract the player's change in coordinates, he will not move on the screen during scrolling).

---
Tags: 2d, tiles, side-scroller, tilemap, platformer
---


# Question
Title: Linker error while trying to extend and recompile irrlicht
I am trying to create a custom `IGUIElement` in irrlicht, for that I have included the sources from irrlicht and extended the CIGUIStatictext class. Now whenever I try to compile my project, I get a host of linker errors, I must admit to ignorance of the compilation process and am not really able to figure out why this is happening. I'm including the source for both my header and cpp class as pastebin.

sample of the linker errors:

```
1>graphNode.obj : error LNK2019: unresolved external symbol "public: virtual__thiscall irr::gui::CGUIStaticText::~CGUIStaticText(void)" (??1CGUIStaticText@gui@irr@@UAE@XZ) referenced in function__unwindfunclet$??
    0graphNode@gui@irr@@QAE@PAVIGUIEnvironment@12@PAVIGUIElement@12@HV?$rect@H@core@2@PB_W@Z$0 1>graphNode.obj : error LNK2019: unresolved external symbol "public:__thiscall irr::gui::CGUIStaticText::CGUIStaticText
    (wchar_t const *,bool,class irr::gui::IGUIEnvironment *,class irr::gui::IGUIElement *,int,class irr::core::rect<int> const &,bool)" (??0CGUIStaticText@gui@irr@@QAE@PB_W_NPAVIGUIEnvironment@12@PAVIGUIElement@12@
    HABV?$rect@H@core@2@1@Z) referenced in function "public: __thiscall irr::gui::graphNode::graphNode(class irr::gui::IGUIEnvironment *,class irr::gui::IGUIElement *,int,class irr::core::rect<int>,wchar_t const*)"
    (??0graphNode@gui@irr@@QAE@PAVIGUIEnvironment@12@PAVIGUIElement@12@HV?$rect@H@core@2@PB_W@Z)

1>graphNode.obj : error LNK2001: unresolved external symbol "public: virtual bool__thiscall irr::gui::graphNode::OnEvent(struct irr::SEvent const &)" (?OnEvent@graphNode@gui@irr@@UAE_NABUSEvent@3@@Z)
1>graphNode.obj : error LNK2001: unresolved external symbol "public: virtual void__thiscall irr::gui::CGUIStaticText::updateAbsolutePosition(void)" (?updateAbsolutePosition@CGUIStaticText@gui@irr@@UAEXXZ)
1>graphNode.obj : error LNK2001: unresolved external symbol "public: virtual void __thiscall irr::gui::CGUIStaticText::draw(void)" (?draw@CGUIStaticText@gui@irr@@UAEXXZ)
1>graphNode.obj : error LNK2001: unresolved external symbol "public: virtual void __thiscall irr::gui::CGUIStaticText::setText(wchar_t const *)" (?setText@CGUIStaticText@gui@irr@@UAEXPB_W@Z)

```

# Answer
> 1 votes
It looks like your problem is that you haven't included the necessary libraries in your project. If you look at the distribution of irrlicht, there is a "lib" folder where you can find the appropriate library. You need to make sure this library "irrlicht.lib" is included under the projects link settings and that it is located in one of the paths that are searched for libraries (also a project setting).

It sounds like what you've done is add the file CGUIText to your project. You don't need to do that, that code exists in the library. If you just pick one class out of the source for that library, it will most likely not compile because it will depend on other classes in the library that you haven't included. You *could* integrate all of the source of the library into your project and use it that way, but there is no reason to do this unless you plan to heavily modify the library's source. You *do* want to include the header though, as you have.

A quick overview of building: There are two main steps, compiling and linking.

Compiling works on only one file at a time and one by one takes your cpp files and converts them into binary coded obj files. Some of these will reference objects in other files, in which case they are essentially given a place holder and the promise that it will be filled in by the next step.

Linking takes all of these obj files, as well as any additional libraries you are referencing and smashes them all together into the final executable. This includes taking all those "place holder" tags and filling in the actual address that those objects ended up at after everything was put together.

Those errors you are getting are essentially saying "you promised that these functions existed somewhere, but I looked through all the parts you gave me and I couldn't find them anywhere."

---
Tags: c++, irrlicht
---


title: Can I do iPhone game dev on iPod touch?

text:
# Question
Title: Can I do iPhone game dev on iPod touch?
I do not want a mobile phone, but are there any issues I'd run into by developing games on an iPod for iPhone?

# Answer
> 5 votes
There is no problem with developing for the iPod touch. Most testers had those as primary hardware where I worked before.

One thing the iPhone was used for (apart from specific hardware bugs) was incoming phone calls. But now you can simulate those on the ipod touch with FaceTime.

I think there were months where I had only iPods with diferent iOS versions during dev. The iPhone is definitely not mandatory.

Hope this helps.

**Edit**: Actually due to the memory limitations it is a much better idea to develop for the iPod touch rather than the iPhone. This way you will deliver a product which will run properly on a larger number of devices.

# Answer
> 2 votes
You will not be able to test or run higher end games and graphics as the iPod Touch hardware has not been kept up to date with the latest iPhone and iPad hardware. If you are only interested in simpler games and graphics, though, there should not be a huge issue. You'll want to have some friends test your game on the other iDevices before publishing it, though (always a good idea in any case).

---
Tags: iphone, ios
---


# Question
Title: How should game objects with fixed positions in the world be positioned?
I have some game objects that are always at the same position in my game world as they make up some of the scenery of my puzzle game. At the moment, their positions are sort of hard coded in and some of their positions are calculated relative to the hard coded positions of other objects at the time of game initialization. This has been hard to maintain because whenever I've decided to change the position of these scenery objects as the game design evolved, I have to go and rewrite parts of the code that place the created objects and calculate their positions in the world.

Is there a more maintainable way of handling the positioning of fixed game objects?

# Answer
> 4 votes
Yes, store their position, and really any other data about them that you might wish to change at some point in some sort of configuration file that the game reads at start up. Generally I've found a good rule of thumb is that if anything in the code is referring to a specific instance of something, it is worth considering moving that out of the code.

---
Tags: java
---


title: Multiple passes in direct3d10

text:
# Question
Title: Multiple passes in direct3d10
I begin to learning direct3d10 and stuck with multiple passes. As input I have a triangle(that stored in vb/ib) and effect file:

```
//some vertex shader and globals goes there. skip them to preserve simplicity

float4 ColorPixelShader(PixelInputType input) : SV_Target
{
    return float4(1,0,0,0);
}

float4 ColorPixelShader1(PixelInputType input) : SV_Target
{
    return float4(0,1,0,0);
}

technique10 ColorTechnique
{
    pass pass0
    {
        SetVertexShader(CompileShader(vs_4_0, ColorVertexShader()));
        SetPixelShader(CompileShader(ps_4_0, ColorPixelShader()));
        SetGeometryShader(NULL);
    }
    pass pass1
    {
        SetVertexShader(CompileShader(vs_4_0, ColorVertexShader()));
        SetPixelShader(CompileShader(ps_4_0, ColorPixelShader1()));
        SetGeometryShader(NULL);
    }
}

```

And some render code:

```
pass1->Apply(0);
device->DrawIndexed(indexCount, 0, 0);

pass2->Apply(0);
device->DrawIndexed(indexCount, 0, 0);

```

What I'd expect to see is the green triangle, but it always shows me red triangle. What am I doing wrong?

Also, I've got another question - should I set vertex shader in every pass?

I've added ColorVertexShader1 that translates vertex position by some delta, and 've got following picture: https://i.stack.imgur.com/kE6l0.jpg

# Answer
When rendering any geometry, any fragments that fail the depth test against the content of the depth buffer will be discarded.

A common depth testing function is the "less" compare, which allows a fragment if the depth for the fragment is strictly closer than the value in the depth buffer. This is so similiar to the function "less-or-equal" that in most cases, it's not noticeable.

When you're rendering the exact same geometry with the exact same vertex shader and transformations, you will get fragments with the exact same depth value in both passes.

In those cases, "less" and "less-or-equal" differ in semantics, and the difference is that "less" will reject your fragment, while "less-or-equal" will not.

As @Patrick Hughes mentions, there is also the possibility that you've got blending modes set such that if any fragment is generated in the second pass, it has no visible effect, but as the common default blending parameters are to keep the new fragment completely, this rarely tends to be a root cause.
> 2 votes

---
Tags: c++, rendering, directx10
---


# Question
Title: Distributing cross-platform .jar containing natives for LWJGL?
I'm making a game in Java using Slick2d, which depends on LWJGL. I can get everything to work in my development environment, but when I export it to a .jar, it needs the natives placed in the same directory as the .jar. What I'm asking is if it's possible to package the natives for all operating systems in the .jar, and automatically use the right ones depending on what OS was detected.

So, is this possible?

# Answer
I recently had the same sort of issues.

I recommend the following:

First, get jarsplice.

Also, assuming that your dev environment is Eclipse, but if not, you'll need to do the equivalent.

1. Export your game to a jar (*NOT* a runnable jar, just a regular jar)
2. Start jarsplice. Add your jar.
3. Add slick.jar, lwjgl.jar, and whatever other jars you are using from slick2d (for example, I use audio, and so usually need the jogg and jorbis jar file)
4. Add the native-(OS).jar(like native-win32.jar, native-mac.jar, native-linux.jar) files in the slick lib directory. (DO NOT ADD THE NATIVES, THEY ARE IN THE JARS ABOVE)
5. Set the appropriate main class.
6. Create the fat jar
7. Behold as your jar will work on windows, mac, and linux.
> 3 votes

---
Tags: java, lwjgl, slick
---


title: 3D picking lwjgl

text:
# Question
Title: 3D picking lwjgl
I have written some code to preform 3D picking that for some reason dosn't work entirely correct! (Im using LWJGL just so you know.)

I posted this at stackoverflow at first but after researching some more in to my problem i found this neat site and tought that you guys might be more qualified to answer this question.

This is how the code looks like:

```
if(Mouse.getEventButton() == 1) {
  if (!Mouse.getEventButtonState()) {
    Camera.get().generateViewMatrix();

    float screenSpaceX = ((Mouse.getX()/800f/2f)-1.0f)*Camera.get().getAspectRatio();
    float screenSpaceY = 1.0f-(2*((600-Mouse.getY())/600f));
    float displacementRate = (float)Math.tan(Camera.get().getFovy()/2);

    screenSpaceX *= displacementRate;
    screenSpaceY *= displacementRate;

    Vector4f cameraSpaceNear = new Vector4f((float) (screenSpaceX * Camera.get().getNear()), (float) (screenSpaceY * Camera.get().getNear()), (float) (-Camera.get().getNear()), 1);
    Vector4f cameraSpaceFar = new Vector4f((float) (screenSpaceX * Camera.get().getFar()), (float) (screenSpaceY * Camera.get().getFar()), (float) (-Camera.get().getFar()), 1);

    Matrix4f tmpView = new Matrix4f();
    Camera.get().getViewMatrix().transpose(tmpView);
    Matrix4f invertedViewMatrix = (Matrix4f)tmpView.invert();

    Vector4f worldSpaceNear = new Vector4f();
    Matrix4f.transform(invertedViewMatrix, cameraSpaceNear, worldSpaceNear);

    Vector4f worldSpaceFar = new Vector4f();
    Matrix4f.transform(invertedViewMatrix, cameraSpaceFar, worldSpaceFar);

    Vector3f rayPosition = new Vector3f(worldSpaceNear.x, worldSpaceNear.y, worldSpaceNear.z);
    Vector3f rayDirection = new Vector3f(worldSpaceFar.x - worldSpaceNear.x, worldSpaceFar.y - worldSpaceNear.y, worldSpaceFar.z - worldSpaceNear.z);

    rayDirection.normalise();

    Ray clickRay = new Ray(rayPosition, rayDirection);

    Vector tMin = new Vector(), tMax = new Vector(), tempPoint;
    float largestEnteringValue, smallestExitingValue, temp, closestEnteringValue = Camera.get().getFar()+0.1f;
    Drawable closestDrawableHit = null;
    for(Drawable d : this.worldModel.getDrawableThings()) {
        // Calcualte AABB for each object... needs to be moved later...
        firstVertex = true;
        for(Surface surface : d.getSurfaces()) {
            for(Vertex v : surface.getVertices()) {
                worldPosition.x = (v.x+d.getPosition().x)*d.getScale().x;
                worldPosition.y = (v.y+d.getPosition().y)*d.getScale().y;
                worldPosition.z = (v.z+d.getPosition().z)*d.getScale().z;
                worldPosition = worldPosition.rotate(d.getRotation());
                if (firstVertex) {
                    maxX = worldPosition.x; maxY = worldPosition.y; maxZ = worldPosition.z;
                    minX = worldPosition.x; minY = worldPosition.y; minZ = worldPosition.z;
                    firstVertex = false;
                } else {
                    if (worldPosition.x > maxX) {
                        maxX = worldPosition.x;
                    }
                    if (worldPosition.x < minX) {
                        minX = worldPosition.x;
                    }
                    if (worldPosition.y > maxY) {
                        maxY = worldPosition.y;
                    }
                    if (worldPosition.y < minY) {
                        minY = worldPosition.y;
                    }
                    if (worldPosition.z > maxZ) {
                        maxZ = worldPosition.z;
                    }
                    if (worldPosition.z < minZ) {
                        minZ = worldPosition.z;
                    }
                }
            }
        }

        // ray/slabs intersection test...

        // clickRay.getOrigin().x + clickRay.getDirection().x * f = minX
        // clickRay.getOrigin().x - minX = -clickRay.getDirection().x * f
        // clickRay.getOrigin().x/-clickRay.getDirection().x - minX/-clickRay.getDirection().x = f
        // -clickRay.getOrigin().x/clickRay.getDirection().x + minX/clickRay.getDirection().x = f

        largestEnteringValue = -clickRay.getOrigin().x/clickRay.getDirection().x + minX/clickRay.getDirection().x;
        temp = -clickRay.getOrigin().y/clickRay.getDirection().y + minY/clickRay.getDirection().y;
        if(largestEnteringValue < temp) {
            largestEnteringValue = temp;
        }
        temp = -clickRay.getOrigin().z/clickRay.getDirection().z + minZ/clickRay.getDirection().z;
        if(largestEnteringValue < temp) {
            largestEnteringValue = temp;
        }

        smallestExitingValue = -clickRay.getOrigin().x/clickRay.getDirection().x + maxX/clickRay.getDirection().x;
        temp = -clickRay.getOrigin().y/clickRay.getDirection().y + maxY/clickRay.getDirection().y;
        if(smallestExitingValue > temp) {
            smallestExitingValue = temp;
        }
        temp = -clickRay.getOrigin().z/clickRay.getDirection().z + maxZ/clickRay.getDirection().z;
        if(smallestExitingValue < temp) {
            smallestExitingValue = temp;
        }

            if(largestEnteringValue > smallestExitingValue) {
                //System.out.println("Miss!");
            } else {
                if (largestEnteringValue < closestEnteringValue) {
                    closestEnteringValue = largestEnteringValue;
                    closestDrawableHit = d;
                }
            }

    }
    if(closestDrawableHit != null) {
        System.out.println("Hit at: (" + clickRay.setDistance(closestEnteringValue).x + ", " + clickRay.getCurrentPosition().y + ", " + clickRay.getCurrentPosition().z);
        this.worldModel.removeDrawableThing(closestDrawableHit);
    }
  }
}

```

I just don't understand what's wrong, the ray are shooting and i do hit stuff that gets removed but the result of the ray are verry strange it sometimes removes the thing im clicking at, sometimes it removes things thats not even close to what im clicking at, and sometimes it removes nothing at all.

**Edit:**

Okay so i have continued searching for errors and by debugging the ray (by painting smal dots where it travles) i can now se that there is something oviously wrong with the ray that im sending out... it has its origin near the world center (nearer or further away depending on where on the screen im clicking) and always shots to the same position no matter where I direct my camera...

My initial toughts is that there might be some error in the way i calculate my viewMatrix (since it's not possible to get the viewmatrix from the gluLookAt method in lwjgl; I have to build it my self and I guess thats where the problem is at)...

**Edit2:**

This is how i calculate it currently:

```
private double[][] viewMatrixDouble = {{0,0,0,0}, {0,0,0,0}, {0,0,0,0}, {0,0,0,1}};

public Vector getCameraDirectionVector() {
    Vector actualEye = this.getActualEyePosition();
    return new Vector(lookAt.x-actualEye.x, lookAt.y-actualEye.y, lookAt.z-actualEye.z);
}

public Vector getActualEyePosition() {
    return eye.rotate(this.getRotation());
}

public void generateViewMatrix() {

    Vector cameraDirectionVector = getCameraDirectionVector().normalize();
    Vector side = Vector.cross(cameraDirectionVector, this.upVector).normalize();
    Vector up = Vector.cross(side, cameraDirectionVector);

    viewMatrixDouble[0][0] = side.x;                    viewMatrixDouble[0][1] = up.x;                  viewMatrixDouble[0][2] = -cameraDirectionVector.x;
    viewMatrixDouble[1][0] = side.y;                    viewMatrixDouble[1][1] = up.y;                  viewMatrixDouble[1][2] = -cameraDirectionVector.y;
    viewMatrixDouble[2][0] = side.z;                    viewMatrixDouble[2][1] = up.z;                  viewMatrixDouble[2][2] = -cameraDirectionVector.z;

    /*
    Vector actualEyePosition = this.getActualEyePosition();
    Vector zaxis = new Vector(this.lookAt.x - actualEyePosition.x, this.lookAt.y - actualEyePosition.y, this.lookAt.z - actualEyePosition.z).normalize();
    Vector xaxis = Vector.cross(upVector, zaxis).normalize();
    Vector yaxis = Vector.cross(zaxis, xaxis);
    viewMatrixDouble[0][0] = xaxis.x;                   viewMatrixDouble[0][1] = yaxis.x;                   viewMatrixDouble[0][2] = zaxis.x;
    viewMatrixDouble[1][0] = xaxis.y;                   viewMatrixDouble[1][1] = yaxis.y;                   viewMatrixDouble[1][2] = zaxis.y;
    viewMatrixDouble[2][0] = xaxis.z;                   viewMatrixDouble[2][1] = yaxis.z;                   viewMatrixDouble[2][2] = zaxis.z;
    viewMatrixDouble[3][0] = -Vector.dot(xaxis, actualEyePosition); viewMatrixDouble[3][1] =-Vector.dot(yaxis, actualEyePosition);  viewMatrixDouble[3][2] = -Vector.dot(zaxis, actualEyePosition);
    */
    viewMatrix = new Matrix4f();
    viewMatrix.load(getViewMatrixAsFloatBuffer());
}

```

Would be verry greatfull if anyone could verify if this is wrong or right, and if it's wrong; supply me with the right way of doing it... I have read alot of threads and documentations about this but i can't seam to wrapp my head around it...

**Edit3:**

Okay with the help of Byte56 (thanks alot for the help) i have now concluded that it's not the viewMatrix that is the problem... I still get the same messedup result; anyone that think that they can find the error in my code, i certenly can't, have bean working on this for 3 days now :(

# Answer
> 1 votes
Okay so i finaly managed to solve this with the help of @Byte56 and a friend of mine.

Here is the result, it's is a litle bit buggy but it works reasonably well :D

It also contains my algorithm for Ray / AABB intersection test, tought it might help someone that are doing this in the future...

```
while(Mouse.next()) {
if(Mouse.getEventButton() == 1) {
    if (!Mouse.getEventButtonState()) {
    Camera.get().generateViewMatrix();

    float screenSpaceX = ((2*Mouse.getX()/800f)-1.0f)*Camera.get().getAspectRatio();
    float screenSpaceY = ((2*Mouse.getY()/600f)-1.0f);
    float displacementRate = (float)Math.tan(Math.toRadians(Camera.get().getFovy()/2));

    screenSpaceX *= displacementRate;
    screenSpaceY *= displacementRate;

    Vector4f cameraSpaceNear = new Vector4f((float) (screenSpaceX * Camera.get().getNear()), (float) (screenSpaceY * Camera.get().getNear()), (float) (-Camera.get().getNear()), 1);
    Vector4f cameraSpaceFar = new Vector4f((float) (screenSpaceX * Camera.get().getFar()), (float) (screenSpaceY * Camera.get().getFar()), (float) (-Camera.get().getFar()), 1);

    Matrix4f tmpView = new Matrix4f().load(Camera.get().getViewMatrix());

    Matrix4f invertedViewMatrix = (Matrix4f)tmpView.invert();

    Vector4f worldSpaceNear = new Vector4f();
                    Matrix4f.transform(invertedViewMatrix, cameraSpaceNear, worldSpaceNear);

    Vector4f worldSpaceFar = new Vector4f();
    Matrix4f.transform(invertedViewMatrix, cameraSpaceFar, worldSpaceFar);

    Vector3f rayPosition = new Vector3f(worldSpaceNear.x, worldSpaceNear.y, worldSpaceNear.z);
    Vector3f rayDirection = new Vector3f(worldSpaceFar.x - worldSpaceNear.x, worldSpaceFar.y - worldSpaceNear.y, worldSpaceFar.z - worldSpaceNear.z);

    rayDirection = new Vector(rayDirection).rotateX(-Camera.get().getRotation().x).rotateY(-Camera.get().getRotation().y).rotateZ(-Camera.get().getRotation().z).to3f();

    rayDirection.normalise();

    rayPosition.z = -rayPosition.z;
    // TODO: origin is a little bit off.... probably has to do with the Camera.get().getActualEyePosition....
    Ray clickRay = new Ray(rayPosition, rayDirection);

    /* Debugg to se where the rays shoot from/at: */
    /*
    this.worldModel.addDrawableThing(new StageObject("smallGrassPlate", new Vector(clickRay.getOrigin().x, clickRay.getOrigin().y,clickRay.getOrigin().z), new Vector(), new Vector(0.3f, 0.3f, 0.3f)));
                    for(float f = Camera.get().getNear(); f < Camera.get().getFar(); f += 1f) {
                        this.worldModel.addDrawableThing(new StageObject("cube", new Vector(clickRay.setDistance(f).x, clickRay.getCurrentPosition().y,clickRay.getCurrentPosition().z), new Vector(), new Vector(0.3f, 0.3f, 0.3f)));
                    }
    */
    float largestEnteringValue, smallestExitingValue, temp1, temp2, closestEnteringValue = Camera.get().getFar()+0.1f;
    Drawable closestDrawableHit = null;

    for(Drawable d : this.worldModel.getDrawableThings()) {
        // Calcualte AABB for each object... needs to be moved later...
        firstVertex = true;
        for(Surface surface : d.getSurfaces()) {
            for(Vertex v : surface.getVertices()) {
                worldPosition.x = (v.x+d.getPosition().x)*d.getScale().x;
                worldPosition.y = (v.y+d.getPosition().y)*d.getScale().y;
                worldPosition.z = (v.z+d.getPosition().z)*d.getScale().z;
                worldPosition = worldPosition.rotate(d.getRotation());
                if (firstVertex) {
                    maxX = worldPosition.x; maxY = worldPosition.y; maxZ = worldPosition.z;
                    minX = worldPosition.x; minY = worldPosition.y; minZ = worldPosition.z;
                    firstVertex = false;
                } else {
                    if (worldPosition.x > maxX) {
                        maxX = worldPosition.x;
                    }
                    if (worldPosition.x < minX) {
                        minX = worldPosition.x;
                    }
                    if (worldPosition.y > maxY) {
                        maxY = worldPosition.y;
                    }
                    if (worldPosition.y < minY) {
                        minY = worldPosition.y;
                    }
                    if (worldPosition.z > maxZ) {
                        maxZ = worldPosition.z;
                    }
                    if (worldPosition.z < minZ) {
                        minZ = worldPosition.z;
                    }
                }
            }
        }

        // ray/slabs intersection test...

        // clickRay.getOrigin().x + clickRay.getDirection().x * f = minX
        // clickRay.getOrigin().x - minX = -clickRay.getDirection().x * f
        // clickRay.getOrigin().x/-clickRay.getDirection().x - minX/-clickRay.getDirection().x = f
        // -clickRay.getOrigin().x/clickRay.getDirection().x + minX/clickRay.getDirection().x = f
        // (minX - clickRay.getOrigin.x) / clickRay.getDirection().x = f

        // TODO: Fix something better here...
        if (clickRay.getDirection().x == 0 || clickRay.getDirection().y == 0) {
            System.out.println("Nu stötte vi på 0 i division!");
            System.exit(1);
        }
        temp1 = (minX - clickRay.getOrigin().x)/clickRay.getDirection().x;
        temp2 = (maxX - clickRay.getOrigin().x)/clickRay.getDirection().x;

        if (temp2 > temp1) {
            largestEnteringValue = temp1;
            smallestExitingValue = temp2;
        } else {
            largestEnteringValue = temp2;
            smallestExitingValue = temp1;
        }

        temp1 = (minY - clickRay.getOrigin().y)/clickRay.getDirection().y;
        temp2 = (maxY - clickRay.getOrigin().y)/clickRay.getDirection().y;
        if (temp2 > temp1) {
            if (largestEnteringValue < temp1 ) {
                largestEnteringValue = temp1;
            }
            if (smallestExitingValue > temp2) {
                smallestExitingValue = temp2;
            }
        } else {
            if (largestEnteringValue < temp2 ) {
                largestEnteringValue = temp2;
            }
            if (smallestExitingValue > temp1) {
                smallestExitingValue = temp1;
            }
        }

        temp1 = (minZ - clickRay.getOrigin().z)/clickRay.getDirection().z;
        temp2 = (maxZ - clickRay.getOrigin().z)/clickRay.getDirection().z;
        if (temp2 > temp1) {
            if (largestEnteringValue < temp1 ) {
                largestEnteringValue = temp1;
            }
            if (smallestExitingValue > temp2) {
                smallestExitingValue = temp2;
            }
        } else {
            if (largestEnteringValue < temp2 ) {
                largestEnteringValue = temp2;
            }
            if (smallestExitingValue > temp1) {
                smallestExitingValue = temp1;
            }
        }

        if(largestEnteringValue <= smallestExitingValue) {
            if (largestEnteringValue < closestEnteringValue) {
                closestEnteringValue = largestEnteringValue;
                closestDrawableHit = d;
            }
        }

    }
    if(closestDrawableHit != null) {
        this.worldModel.removeDrawableThing(closestDrawableHit);
    }
}
}

```

And this code is in my camera class for generating view matrix:

```
public Vector getActualEyePosition() {
    Vector rotatedEye = eye.clone();
    rotatedEye.x -= lookAt.x*2;
    rotatedEye.y -= lookAt.y*2;
    rotatedEye.z -= lookAt.z*2;
    rotatedEye = rotatedEye.rotate(this.getRotation());
    return new Vector(-rotatedEye.x, -rotatedEye.y, rotatedEye.z);
}

public void generateViewMatrix() {
    Vector actualEye = this.getActualEyePosition();
    Vector3f forward;
    Vector3f side = new Vector3f();
    Vector3f up;
    forward = new Vector3f(lookAt.x - eye.x, lookAt.y - eye.y, lookAt.z - eye.z);

    up = upVector.to3f();

    forward.normalise();

    /* Side = forward x up */
    Vector3f.cross(forward, up, side);
    side.normalise();

    /* Recompute up as: up = side x forward */
    Vector3f.cross(side, forward, up);

    viewMatrix.m00 = side.x;
    viewMatrix.m10 = side.y;
    viewMatrix.m20 = side.z;
    viewMatrix.m30 = -(Vector3f.dot(side, actualEye.to3f()));

    viewMatrix.m01 = up.x;
    viewMatrix.m11 = up.y;
    viewMatrix.m21 = up.z;
    viewMatrix.m31 = -(Vector3f.dot(up, actualEye.to3f()));

    viewMatrix.m02 = -forward.x;
    viewMatrix.m12 = -forward.y;
    viewMatrix.m22 = -forward.z;
    viewMatrix.m32 = -(Vector3f.dot(forward, actualEye.to3f()));
}

```

I want to point out that there are 2 types of vectors here the first is my own "Vector" and the other one is lwjgls "Vector3f".

Hope this helps any one thats having the same problems as I had and that it dosn't take them 5 days to fix this :D

# Answer
> 2 votes
I recently attempted to implement picking, and this thread was invaluable in getting things to work. One problem that I ran into though is that I don't think that the accepted answer generates the right view matrix in all cases. Let me suggest an alternative for obtaining it, which is much simpler and more likely to be right - it just pulls the matrix straight out of OpenGL.

Unfortunately the code is written in Scala so you may have to tweak it a little bit to get it to work in Java, but there should only be minor differences.

```
  def storeViewMat() = {
    viewMatrix = new Matrix4f()
    var buf: FloatBuffer = BufferUtils.createFloatBuffer(16 * 4)

    // Get your current model view matrix from OpenGL.
    glGetFloat(GL_MODELVIEW_MATRIX, buf)

    // rewind the buffer
    buf.rewind()

    viewMatrix.m00 = buf.get(0)
    viewMatrix.m01 = buf.get(1)
    viewMatrix.m02 = buf.get(2)
    viewMatrix.m03 = buf.get(3)

    viewMatrix.m10 = buf.get(4)
    viewMatrix.m11 = buf.get(5)
    viewMatrix.m12 = buf.get(6)
    viewMatrix.m13 = buf.get(7)

    viewMatrix.m20 = buf.get(8)
    viewMatrix.m21 = buf.get(9)
    viewMatrix.m22 = buf.get(10)
    viewMatrix.m23 = buf.get(11)

    viewMatrix.m30 = buf.get(12)
    viewMatrix.m31 = buf.get(13)
    viewMatrix.m32 = buf.get(14)
    viewMatrix.m33 = buf.get(15)
  }

```

This code will store the view matrix inside a Matrix4f named `viewMatrix`. I hope this helps anyone who comes across this thread in the future!

# Answer
> 1 votes
I wrote an answer on this before for picking within a 3D game, using LWJGL. You should see if the answer here is useful to you.

And as for your camera's view matrix, you can generate it with something like the following code:

```
Matrix4f CreateView(Vector3f position, Vector3f direction, Vector3f up) {
    Vector3f rightVector = new Vector3f();
    Vector3f.cross(up, direction, rightVector);
    rightVector = (Vector3f) rightVector.normalize();
    Matrix4f result = new Matrix4f();
    result.m00 = rightVector.x;
    result.m10 = rightVector.y;
    result.m20 = rightVector.z;
    result.m30 = -(Vector3f.dot(rightVector, position));

    result.m01 = up.x;
    result.m11 = up.y;
    result.m21 = up.z;
    result.m31 = -(Vector3f.dot(up, position));

    result.m02 = direction.x;
    result.m12 = direction.y;
    result.m22 = direction.z;
    result.m32 = -(Vector3f.dot(direction, position));

    return result;
}

```

Where the up vector and direction vector are both normalized.

This looks like you're doing the same thing. I'd take a look your code here:

```
viewMatrix.load(getViewMatrixAsFloatBuffer());

```

Make sure it's doing what you think it should be. I put my matrix into a float buffer like so:

```
public static FloatBuffer MatrixToFloatBuffer(Matrix4f matrix) {
    FloatBuffer fb = BufferUtils.createFloatBuffer(16);
    int i = 0;
    fb.put(i++, matrix.m00);
    fb.put(i++, matrix.m01);
    fb.put(i++, matrix.m02);
    fb.put(i++, matrix.m03);
    fb.put(i++, matrix.m10);
    fb.put(i++, matrix.m11);
    fb.put(i++, matrix.m12);
    fb.put(i++, matrix.m13);
    fb.put(i++, matrix.m20);
    fb.put(i++, matrix.m21);
    fb.put(i++, matrix.m22);
    fb.put(i++, matrix.m23);
    fb.put(i++, matrix.m30);
    fb.put(i++, matrix.m31);
    fb.put(i++, matrix.m32);
    fb.put(i++, matrix.m33);
    return fb;
}

```

So after generating my view matrix, I can load it like so:

```
glLoadMatrix(WorldCamera.MatrixToFloatBuffer(WORLD.Camera.view));

```

Also check your "up" and "side" vectors to ensure they are correct.

---
Tags: opengl, 3d, lwjgl, picking
---


# Question
Title: Basics of drawing in 2d with OpenGL 3 shaders
I am new to OpenGL 3 and graphics programming, and want to create some basic 2d graphics. I have the following scenario of how I might go about drawing a basic (but general) 2d rectangle. I'm not sure if this is the correct way to think about it, or, if it is, how to implement it.

In my head, here's how I imagine doing it:

1. `t = make_rectangle(width, height)`
    * build general VBO, centered at 0, 0
2. optionally: `t.set_scale(2)`
3. optionally: `t.set_angle(30)`
4. `t.draw_at(x, y)`
    * calculates some sort of scale/rotate/translate matrix (or matrices), passes the VBO and the matrix to a shader program
5. Something happens to clip the world to the view visible on screen.

I'm really unclear on how 4 and 5 will work. The main problem is that all the tutorials I find either: use fixed function pipeline, are for 3d, or are unclear how to do something this "simple".

Can someone provide me with either a better way to think of / do this, or some concrete code detailing performing the transformations in a shader and constructing and passing the data required for this shader transformation?

# Answer
The basics of drawing are really not much different than with 3D. You need a set of vertices, a transformation matrix, and material properties. For a sprite-based game, the vertices will always be a simple quad, and the material will usually just be a texture (though there are often other properties, e.g. to make sprites blink different colors when an enemy takes damage, or the like).

In this case, you can create a single VBO for all sprites, and reuse it.

If you have complex shapes, you're going to want to use a batching approach. Push all your pre-transformed vertices into a single large VBO and render them all in one go. Doing a separate GL draw call for each object is slow.

The transformation matrix at its simplest is a 3x3 matrix representing the homogeneous transformation. You have your translate (location), rotation, and scale. The matrix is composed by concatenating (multiplying) the matrices together. GL prefers column-major column matrices (but you are free to use any other representation, if you wish, but I won't get into how).

Your 2D transformation then is the combination of the Rotation, Scale, and Translation matrices:

```
|1, 0, tx|   |cos(theta), -sin(theta), 0|   |sx, 0,  0|
|0, 1, ty| * |sin(theta), cos(theta),  9| * |0,  sy, 0|
|0, 0, 1 |   |0,          0,           1|   |0,  0,  1|

```

The matrix can either be applied to your vertices on the CPU before uploading, if you're pushing all your vertices into a single VBO.

If you're using raw sprites, instancing can be a lot faster. In this case, you will use a single draw call to render a number of copies of your quad VBO. To access the matrices, they must be stored in either a texture or what's called a Texture Buffer Object. The latter is better. The idea there is that you upload all your transformation matrices for your objects into a VBO, which is bound to a Texture, which is then bound to the shader. The vertex shader uses the special variable gl\_InstanceID and the texelFetch() command to read the matrices out of the Buffer Texture, and then you apply it to the vertices.

You can read more about how to use Buffer Texture Objects here:

http://www.opengl.org/wiki/Buffer\_Texture

You can read more about instancing here:

http://www.opengl.org/wiki/Vertex\_Specification#Instancing

With the instancing approach, you also want to pack in the UV coordinates, and you'll need to use a texture atlas for rendering. I recommend using 2D texture arrays for your atlases, assuming all your sprites have the same width and height. It has a lot of advantages over a traditional texture atlas. The traditional kind works just fine in many cases, if that's what you'd prefer.

The end result is that you'll only have a single draw call for every "material" (e.g. texture), which with atlasing might well be hundreds or thousands of individual objects.

A rough pseudo-code overview then:

```
init():
  vbo_quad = createVBO()
  pushQuadVerts(vbo_quad)

  tex_atlas = createTextureAtlas()

  vbo_objects = createVBO()
  tex_objects = createTextureBuffer(vbo_objects)

  shader = loadShaders("vertex.glsl", "fragment.glsl")

update():
  for each object:
    calculateObjectTransform()
    pushTransformOntoVBO(vbo_objects)

draw():
  bindVBO(vbo_quad)
  bindTexture(UNIT0, tex_atlas)
  bindTexture(UNIT1, tex_objects)

  drawArraysInstanced(GL_QUADS, 0, 4, number_of_objects)

```

As a final hint, if you're going the instanced route, you might find it a bit quicker and easier to avoid calculating the entire transformation matrix on the CPU, and instead calculate it on the GPU. You can pass in the rotation, scale, and translation. If you do the math, you can take those inputs and calculate the matrix directly. Then instead of needing to eat up 9 floats in memory bandwidth to the GPU and doing a lot of work on the serial CPU, you can pass in 5 floats (4 if you only have uniform scale) and do the work on the parallel GPU.

The math comes out something like this (off the top of my head, so double check):

```
|sx * cos(theta), -sy * sin(theta), tx|
|sx * sin(theta),  sy * cos(theta), ty|
|0,                0,               1 |

```

Nice and easy.
> 3 votes

# Answer
What you'll want to do is create a vertex shader that will pass the VBO directly on it's way down the pipe. This way, any transformations you make to you VBO will be applied. This however, will cause you to have to relearn transformations if you ever switch to 3D as you will want to impliment them in the shader instead. How I would break it up is, using your steps:

1) Create the VBO of your basic rectangle.

2 & 3) Edit each element in your VBO, or if you want to learn to do it in the shader, create a transformation matrix of what you want to do to the rectangle.

4)Here you will need to about the glDrawArrays command. If you wish to do your transformation in the shader, you will need to learn about glUniformMatrix4fv command or one of it's many cousins as well as how to implment it on the GLSL side.

5)You will want to learn about perspective matrix, want kinds there are, like orthoginal views and frustum, well those are for 3D, but you'll get the idea. But, working in two dimentsions makes things a little easier as your limits will be -1.0 to 1.0 unless you change them.

I recommend looking up a book by Edward Angel, namely his Interactive Computer Graphics book, the latest edition will assist you, though local librarys may only have older versions that are centered on older versions of OpenGL, it will help you build the basics. If your wanting a more free-bee lession approach, the http://openglbook.com/ is decently done. It helps get a simple implimentation going in both 2D and 3D and will help with the basic first steps, though it is not the best implimentation. And once you get going, fool around with the code and shaders, best way to learn.
> 6 votes

---
Tags: opengl, 2d, mathematics, shaders
---


# Question
Title: How do I resolve a collision of a rectangle with two rectangular tiles at once?
I am having some problems with collision detection between a player and the environment in a tile-based game. I have a player objects, `Tile`s and what I call `MapObject`s. The tiles are all 16×16. The `MapObject`s can be any size, but in my case they are all 16×16. The game jitters when the player runs along the `MapObject`s or tiles. The player is unable to move right, and will get warped forward when moving left. I have found the problem: My collision detection will move the player left/right if colliding the object from the side, and up/down if collision from up/down.

Now imagine that my player is sitting on 2 tiles, at (10,12) and (11,12), and the player is mostly standing on the (11,12) tile. The collision detection will first run on then (10,12) tile, it calculates the collision depth, and finds that is is a collision from the side, and therefore move the object to the right. After, it will do the collision detection with (11,12) and it will move the character up. So the player will not fall down, but are unable to move right. And when moving left, the same problem will make the player warp forward.

This problem have been bugging me for a few days now, and I just can't find a solution!

---

Here is my code that does the collision detection.

```
 public void ApplyObjectCollision(IPhysicsObject obj, List<IComponent> mapObjects, TileMap map)
        {
            PhysicsVariables physicsVars = GetPhysicsVariables();
            Rectangle bounds = ((IComponent)obj).GetBound();
            int leftTile = (int)Math.Floor((float)bounds.Left / map.GetTileSize());
            int rightTile = (int)Math.Ceiling(((float)bounds.Right / map.GetTileSize())) - 1;
            int topTile = (int)Math.Floor((float)bounds.Top / map.GetTileSize());
            int bottomTile = (int)Math.Ceiling(((float)bounds.Bottom / map.GetTileSize())) - 1;

            // Reset flag to search for ground collision.
            obj.IsOnGround = false;

            // For each potentially colliding tile,
            for (int y = topTile; y <= bottomTile; ++y)
            {
                for (int x = leftTile; x <= rightTile; ++x)
                {
                    IComponent tile = map.Get(x, y);
                    if (tile != null)
                    {
                        bounds = HandelCollision(obj, tile, bounds, physicsVars);
                    }
                }
            }

            // Handel collision for all Moving objects
            foreach (IComponent mo in mapObjects)
            {
                if (mo == obj)
                    continue;

                if (mo.GetBound().Intersects(((IComponent)obj).GetBound()))
                {
                    bounds = HandelCollision(obj, mo, bounds, physicsVars);
                }
            }
        }
        private Rectangle HandelCollision(IPhysicsObject obj, IComponent objb, Rectangle bounds, PhysicsVaraibales physicsVars)
        {
            // If this tile is collidable,
            SpriteCollision collision = ((IComponent)objb).GetCollisionType();

            if (collision != SpriteCollision.Passable)
            {
                // Determine collision depth (with direction) and magnitude.
                Rectangle tileBounds = ((IComponent)objb).GetBound();
                Vector2 depth = bounds.GetIntersectionDepth(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 == SpriteCollision.Platform)
                    {
                        // If we crossed the top of a tile, we are on the ground.
                        if (obj.PreviousBound.Bottom <= tileBounds.Top)
                            obj.IsOnGround = true;

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

                            // If we hit something about us, remove all velosity upwards
                            if (depth.Y > 0 && obj.IsJumping)
                            {
                                obj.Velocity = new Vector2(obj.Velocity.X, 0);
                                obj.JumpTime = physicsVars.MaxJumpTime;
                            }

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

                        // Perform further collisions with the new bounds.
                        return ((IComponent)obj).GetBound();
                    }
                }
            }
            return bounds;
        }

```

**Update:** I have uploaded the source code here. I think my general approach might be wrong for working with small tiles.

# Answer
Like Byte56 suggested, rather than fix the collision, you simply doesn't allow the collision to happen in the first place.

Here's a snippet of how my engine handles it

```
// Reset flags just like you do.
this.IsPushingLeft = false;
this.IsPushingRight = false;

// verticalWall is just a struct containing all the common data for whatever wall of tiles the entity would hit in the next frame.
if (verticalWall.HasValue && verticalWall.Value.IsSolid)
{
    // If we're moving right and the next position (deltaPosition) would result in a collision, we fix it so the collision doesn't happen.
    if (this.IsMovingRight && deltaPosition.X + this.Width >= verticalWall.Value.BoundingBox.Left)
    {
        this.IsPushingRight = true;
        deltaVelocity.X = verticalWall.Value.BoundingBox.Left - this.Right - 1.00f;
    }
    // If we're moving left and the next position (deltaPosition) would result in a collision, we fix it so the collision doesn't happen.
    else if (this.IsMovingLeft && deltaPosition.X < verticalWall.Value.BoundingBox.Right)
    {
        this.IsPushingLeft = true;
        deltaVelocity.X = verticalWall.Value.BoundingBox.Right - this.Left;
    }
}

// Reset flags just like you do.
this.IsPushingDown = false;
this.IsPushingUp = false;
// verticalWall is just a struct containing all the common data for whatever ceiling or floor of tiles the entity would hit in the next frame.
if (horizontalWall.HasValue && horizontalWall.Value.IsSolid)
{
    // If we're moving down and the next position (deltaPosition) would result in a collision, we fix it so the collision doesn't happen.
    if (this.IsMovingDown && deltaPosition.Y + this.Height >= horizontalWall.Value.BoundingBox.Top)
    {
        this.ActiveFriction = horizontalWall.Value.Friction;
        this.IsPushingDown = true;
        deltaVelocity.Y = horizontalWall.Value.BoundingBox.Top - this.Bottom - 1.00f;
    }
    // If we're moving up and the next position (deltaPosition) would result in a collision, we fix it so the collision doesn't happen.
    else if (this.IsMovingUp && deltaPosition.Y < horizontalWall.Value.BoundingBox.Bottom)
    {
        this.IsPushingUp = true;
        deltaVelocity.Y = horizontalWall.Value.BoundingBox.Bottom - this.Top;
    }
}

```

This is a somewhat generic AABB collision type. Only thing that stands out is my approach to walls rather than individual tiles, but with individual tiles it's the same thing, you'd just do the check for each tile instead.

What I essentially do, is fix the velocity vector, so rather than moving `speed * delta`, I move `speed * delta - collisionOffset`, resulting in the entity ending just next to the wall, outside the potential collision.

Here's the walls I check collision against, depending on direction.
> 7 votes

# Answer
## Diagrammatically

When I have collision problems, I draw. This is your problem, as I understand it:

Tiles `A` and `B`, considered separately, have their own ideas of where you should go to get out of each of their collisions. In this case, the displacement out of `A` is superfluous: The displacement out of `B` is *already* the minimum exit distance. However, in a corner between two tiles, the combination of both displacements may be necessary to get you out of the collision. Sometimes you need that extra information, sometimes you don't.

Essentially, sometimes some tiles' contributions to the collision resolution must be dropped in order to get resolution with minimal displacement.

## Untested thrown-together algorithm which looks okay

On collision, go through all *combinations* of displacement suggestions received from tiles. Carry out the combined displacement that involves fewest tiles but still manages to get you out of the collision.

**Example run:**

In the particular case doodled above, The combinations would be: `a`, `b` or `a+b`, with `a` and `b` respecting the displacement vectors suggested by tiles `A` and `B` respectively.

Displacing by `a` would *not* get us out of the collision, so that's out.

Displacing by `b` *would*.

Displacing by `a+b` also *would*, but it involves two tiles.

Hence `b` wins out and we get minimum exit. If we always go in this order of *least to most tiles involved*, we could already return `b` before even checking `a+b`, as `b` involves only one tile and so would win regardless.

-

I hope this abstraction is useful.
> 5 votes

---
Tags: c#, collision-detection, tiles, tilemap, collision-resolution
---


# Question
Title: Should I go with OpenGL to see my future in Game Development industry?
> **Possible Duplicate:**
> Should I continue studying OpenGL or just switch to DirectX to give me a better chance of landing a job in the game industry?

I tried Google but found quite old articles, so I am in search of an answer in context to year 2012.

Hi all, I don't know if you will consider this question appropriate for this community but I am constantly searching for a perfect answer. What I have seen is that most of the games that are released these days are DirectX 1x based. Except for few games like Starcraft or Diablo which don't have high end graphics are using OpenGL. So I have few questions to ask.

The platforms i would like to target are PC (windows), Xbox 360 and PS3 (must).

1. Should I go with learning OpenGL to see my future in game development industry? Or should I shift to Directx?
2. If I learn OpenGL first, will it be difficult to learn direcx then?
3. Which API is most suitable for indie development?
4. Which one of the two API's are better from coder's (programmer's) point of view? Like OOP and style of coding.

Is openGL being cross platform should be the only reason to choose it over Directx? Even when vendors are not providing enough stable drivers for it.

Thanks in advance.

I have read this post, but I have few questions. Should I continue studying OpenGL or just switch to DirectX to give me a better chance of landing a job in the game industry?

# Answer
> 4 votes
Firstly, if your making games, are you sure you want to be making game engines from scratch rather than using something like Unity, Unreal's engine and so on?

1. OpenGL is needed on Mobile phones, OSX and every console other than the X-Box (well the other console use their own thing thats a stripped down OpenGL similar to OpenGL ES since ES 2.0 wasn't out back then). So you will definitely need it in the games industry. You will probably also need DirectX. Having said that I think most game devs now program using premade off the shelf engines and don't worry about the graphics API (other than possibly things like shaders).
2. I don't know much DirectX (being a Linux user myself) but I can't see learning 1 really causing you problems learning the other. They should bother share similar underlying concepts. The main thing would be the coordinate system.
3. For an indie game developer it can depend. Indie games are niche products. Having support for other platforms such as OSX can give you a large number of extra sales as the number of game available on the platform is fairly limited and there more likely wanting to boost support for their platforms. You can also throw in Linux support for little extra and get some good PR (the main hassle is building for a whole bunch of different targets). Mobile phones are also something to look at as they all use OpenGL ES. Porting to WebGL is also another possibility with things like Google's Nativeclient and emscripten (Compiles code to JavaScript) or just redoing it in JavaScript (or even using JavaScript across the board the desktop, web and mobile).

Having said that, many indie devs make stuff using XNA and sell through the Xbox store. Since it's built right into the Xbox they get some good sales and XNA seems like a good platform.

4) Once again I'm not that familiar with DirectX.

I've heard John Carmack prefers DirectX and I also saw the dev working on the infinity universe engine say similar things (But they went to DX11 from whatever OGL version they where targeting, Carmack would probably have been using an older OpenGL version). But OpenGL has had massive changes recently, many of which have made coding in it much easier (uniform buffer objects, GLSL uniform routines). Those changes will take a while to roll out.

OpenGL doesn't have much OOP. It does however refer to things as 'Objects' (VertexBufferObjects, VertexArrayObjects, TextureObjects, FrameBufferObjects). Those things are fairly easy to wrap in a class for whatever language your using. You don't need to implement the whole API just the parts you want. There is a C++ binding called OGLplus although it's newish and not widely used.

From what I can see from Googling DirectX also requires similar OOP frameworks to be produced.

If they both need the frameworks then the coding probably doesn't matter to much since you should only be using it in the framework.

Finally OpenGL gets some flac for having broken implementation on some system (Such as netbooks with Intel chipsets, even the ones that do work are often only OpenGL 2.x).

Or being out of date on many system (The latest version of OSX 10.7.x has 3.2, the previous version 10.6.x was 3.0, then 10.5.x is either 2.0, 1.5 or 1.3 depending on the video card (Minecraft sticks to 1.3 as it's render target for basically this reason), those systems are going to be stuck at that OpenGL version forever unless the users pay for an upgrade and 10.5 was only released in 2007 so you will have to live with it for a while longer). One good thing is you can just target what extensions you want and make your framework support fallbacks (For example you can make a VertexBufferObject class that will use the 1 vertex at a time fixed pipeline functionality if the VBO extension is missing). Also remember OSX doesn't support DirectX at all.

# Answer
> 3 votes
The answer whenever a beginner asks 'should I learn this or that' is always: Learn everything you can. Honestly, I don't understand why people would think they can only possibly learn one of the alternatives.

And yes, your chances of getting a job writing rendering code as your first games industry job are slim unless you are so into rendering that you write some amazing demos, in which case you'd probably not be asking this question. And even if you did get hired to work on rendering it's most likely to be working on modifications to an existing engine where the knowlege of maths related to graphics and the skill of being able to read and understand other people's code is worth 100x the knowlege of any particular API.

For all those reasons I'd suggest writing as much code as you can as early as you can and to do that in OpenGL, simply because it's a 'C' style API and thus easier for a beginner to get to grips with.

btw. I have to correct the myth that comes up time and time again whenever OpenGL vs. DirectX is discussed, to paraphrase "that DirectX is used on Windows and XBox and OpenGL is used everywhere else". This is not true. OpenGL is useful for MacOS or Linux development, although neither are big games platforms. And OpenGL in it's ES form is most widely used on mobiles and tables these days. But *NO* current generation games console uses OpenGL, in fact the only games console I'm aware of that ever used it was the N64. PS3 and Wii developers post commands buffers directly the GPU using libraries supplied by the platform and Xbox 360 uses a modified form of DirectX.

# Answer
> 1 votes
As a beginner, I think shooting for cross-platform is a huge mistake. It's just adding an extra layer of complexity that you don't need right now; what you need is to focus on learning core concepts and how they fit in to the overall flow of a graphics pipeline and structure of a program.

Either of OpenGL or Direct3D will give you that.

I have to admit right now that I'm biased so take the next two points with an appropriately sized grain of salt.

* Driver quality is hugely important and even more so for a beginner. If something goes wrong you need a fairly reasonable reassurance that it's due to a problem in your own code and not a driver bug. Direct3D drivers are just so much higher quality, owing to not needing to support decades of accumulated legacy, having a simpler driver model and a tighter certification process.
* Tools, documentation, examples, etc tend to be better for Direct3D. In particular you get the debug runtimes and PIX, both of which are extremely valuable for hunting down problems in your code.

U62's final paragraph is correct - OpenGL is not as portable as it is often made out to be. You can achieve a certain level of portability by restricting youself to a common subset of full OpenGL and OpenGL ES, but again with the extra layer of complexity thing. It's most definitely not a simple "recompile and off you go" however, and even if it were you would still have to deal with other platform-specific subsystems (sound, memory, input, file access, threading, networking, windowing, etc) - the code for which may even dwarf the rendering code.

---
Tags: opengl, directx, directx11
---


# Question
Title: How do I make my character slide down high-angled slopes?
I am currently working on my character's movement in *Unity3D*. I managed to make him move relatively to the mouse cursor. I set a slope limit of 45°, which does not allow the character to walk up the mountains with higher degrees. But he can still jump them up.

How do I manage to make him slide down again when he jumped at places with too high slope?

Thanks in advance.

**edit:** Code snippet of my basic movement. using UnityEngine; using System.Collections;

```
public class BasicMovement : MonoBehaviour {
    private float speed;
    private float jumpSpeed;
    private float gravity;
    private float slopeLimit;
    private Vector3 moveDirection = Vector3.zero;

    void Start()
    {
        PlayerSettings settings = GetComponent<PlayerSettings>();
        speed = settings.GetSpeed();
        jumpSpeed = settings.GetJumpSpeed();
        gravity = settings.GetGravity();
        slopeLimit = settings.GetSlopeLimit();
    }

    void Update() {
        CharacterController controller = GetComponent<CharacterController>();
        controller.slopeLimit = slopeLimit;

        if (controller.isGrounded) {
            moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
            moveDirection = transform.TransformDirection(moveDirection);
            moveDirection *= speed;

            if (Input.GetButton("Jump")) {
                moveDirection.y = jumpSpeed;
            }

        }
        moveDirection.y -= gravity * Time.deltaTime;
        controller.Move(moveDirection * Time.deltaTime);
    }
}

```

# Answer
Your braking when ground is hit is wrong, you simply stop the vertical movement, but that is only how a ground hit works when the ground is flat.

What you should do is to project `moveDirection` on the surface that is hit, that will give you the new `moveDirection`. If your library has a function to project a vector on a plane or surface that is what you should use. If not you should subtract `moveDirection`'s projection on the surface's normal from `moveDirection` itself.
> 1 votes

# Answer
just check before jumping if character is standing on a ground, I mean if he is not on a high angled slope. and leave anything else to the physics engine.

based on the code you provided I can see where the problem is:

according to Unity script reference, `CharacterController.isGrounded` is only returning if character is touching the ground. it doesn't check for slopelimit. after a little searching FPSWalkerEnhanced seems to be something that solves you issue.
> 0 votes

---
Tags: unity, movement, terrain, character
---


# Question
Title: Android opengles 2.0 :different resolutions rendering and input
I'm currently developing a sprite based 2D game for android using opengles 2.0. I've got some basic rendering done that mimics the spritebatch functionality of xna (draw sprite, rotation, color). But all of this works for a fixed projection matrix, but android has a lot of screen sizes.

Q1)Would this be an okay method to scale up/down the drawing?

1)Draw the whole screen to a texture. 2)Draw the above texture as a quad to the device.

I found the above through some searching, not sure if it's the best one, are there any alternatives?

Q2)How do you handle inputs for different resolutions? I currently get the position of a touch and use it raw. Would it be okay to get the position, and then scale the position to size of the texture used for rendering, and the perform calculations on it?

Thanks.

# Answer
A1. Drawing to a texture and then using it to draw a quad on screen has several problems:

* you could be rendering more than you have to if the actual screen is smaller
* you'd get a lower quality rendering if the actual screen is larger
* that doesn't solve the issue of different screen aspect ratios and you would end up with stretched/squashed image if it's different than the ratio you used for rendering.

The only proper way to solve it is to modify your projection matrix. As you're developing a 2D game you're probably using an ortho projection so this shouldn't be a problem as you only need to scale its height (or top/bottom parameters, depends how you calculate the matrix) with glViewport() taking care of horizontal scaling.

A2. Convert your input to a virtual unit system and have your game accept it, e.g. float virtualX = pointer.getX() / resolutionX; This way if the pointer got moved by 50% of the screen it will always end up being 0.5.
> 0 votes

---
Tags: android, opengl-es2
---


title: Write depth buffer to texture

text:
# Question
Title: Write depth buffer to texture
I need to read depth buffer from GPU and write it to texture. How this can be done? Here is how texture for depth buffer is created:

```
depthBufferDesc.Width = screenWidth;
depthBufferDesc.Height = screenHeight;
depthBufferDesc.MipLevels = 1;
depthBufferDesc.ArraySize = 1;
depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
depthBufferDesc.SampleDesc.Count = 1;
depthBufferDesc.SampleDesc.Quality = 0;
depthBufferDesc.Usage = D3D10_USAGE_DEFAULT;
depthBufferDesc.BindFlags = D3D10_BIND_DEPTH_STENCIL;
depthBufferDesc.CPUAccessFlags = 0;
depthBufferDesc.MiscFlags = 0;

m_device->CreateTexture2D(&depthBufferDesc, NULL, m_depthStencilBuffer);

```

Also, I've got another question: is it possible to bind depth buffer texture as sampler to the pixel shader?

# Answer
> 1 votes
You bind that texture to a depth stencil view and also a shader resource view to sample from it in another shader.

You need to add D3D10\_BIND\_SHADER\_RESOURCE to the depthBufferDesc.BindFlags field.

---
Tags: c++, rendering, directx10
---


title: Random numbers on C++

text:
# Question
Title: Random numbers on C++
Recently I got used to modern languages which include a stock good random generator, which usually is the Mersenne Twister; now that I got back to C++ I have to decide what to use.

I searched for Mersenne Twister implementations and I noticed there are so many: is there one which is more used and widespread, or am I supposed to pick one assuming they are all equally good?

# Answer
C++11 includes a Mersenne Twister generator by default as part of its new `<random>` interface. For example, to generate integers uniformly between \[-10, 10\] using MT:

```
std::mt19937 eng; // This is the Mersenne Twister
std:::uniform_int_distribution<int> dist(-10, 10)
for (int i = 0; i < 10; ++i)
    std::cout << dist(eng) << std::endl;

```

Most of this is also available in any compiler offering TR1 though the names are slightly different; `std::tr1::mt19937` and `std::tr1::uniform_int<int>`.

I usually caution people away from using Mersenne Twister. It's an okay algorithm but a lot of its popularity is just marketing. 624 dimensions of randomness is more than most people need, and MT carries relatively heavy state requirements and when it does a full table recalc it can blow cache. I am personally partial to xorshift which gives excellent periods and reasonable distributions for anything a game needs, with tiny memory and CPU requirements.

I've written a (mostly?) C++11-compliant xorshift generator - xorshift.hpp, xorshift.cpp \- and placed it in the public domain. You can plug this into any C++11 randomization function, as above:

```
xorshift eng;
std:::uniform_int_distribution<int> dist(-10, 10)
for (int i = 0; i < 10; ++i)
    std::cout << dist(eng) << std::endl;

```
> 19 votes

# Answer
Another RNG I've used before for gamedev purposes is Bob Jenkins' "small" RNG, described here.

(He also has a cryptographic-strength RNG called ISAAC, but it's bigger and slower, and games don't need that level of strength.)
> 1 votes

---
Tags: c++, random
---


title: Automating XNA Performance Testing?

text:
# Question
Title: Automating XNA Performance Testing?
I was wondering what peoples approaches or thoughts were on automating performance testing in XNA. Currently I am looking at only working in 2d, but that poses many areas where performance can be improved with different implementations.

An example would be if you had 2 different implementations of spatial partitioning, one may be faster than another but without doing some actual performance testing you wouldn't be able to tell which one for sure (unless you saw the code was blatantly slow in certain parts). You could write a unit test which for a given time frame kept adding/updating/removing entities for both implementations and see how many were made in each timeframe and the higher one would be the faster one (in this given example).

Another higher level example would be if you wanted to see how many entities you can have on the screen roughly without going beneath 60fps. The problem with this is to automate it you would need to use the hidden form trick or some other thing to kick off a *mock* game and purely test which parts you care about and disable everything else.

I know that this isnt a simple affair really as even if you can automate the tests, really it is up to a human to interpret if the results are performant enough, but as part of a build step you could have it run these tests and publish the results somewhere for comparison.

This way if you go from version 1.1 to 1.2 but have changed a few underlying algorithms you may notice that generally the performance score would have gone up, meaning you have improved your overall performance of the application, and then from 1.2 to 1.3 you may notice that you have then dropped overall performance a bit.

So has anyone automated this sort of thing in their projects, and if so how do you measure your performance comparisons at a high level and what frameworks do you use to test? As providing you have written your code so its testable/mockable for most parts you can just use your tests as a mechanism for getting some performance results...

=== Edit ===

Just for clarity, I am more interested in the best way to make use of automated tests within XNA to track your performance, not play testing or guessing by manually running your game on a machine. This is completely different to seeing if your game is playable on X hardware, it is more about tracking the change in performance as your game engine/framework changes.

As mentioned in one of the comments you could easily test "how many nodes can I insert/remove/update within QuadTreeA within 2 seconds", but you have to physically look at these results every time to see if it has changed, which may be fine and is still better than just relying on playing it to see if you notice any difference between version. However if you were to put an Assert in to notify you of a fail if it goes lower than lets say 5000 in 2 seconds you have a brittle test as it is then contextual to the hardware, not just the implementation. Although that being said these sort of automated tests are only really any use if you are running your tests as some sort of build pipeline i.e:

Checkout -\> Run Unit Tests -\> Run Integration Tests -\> Run Performance Tests -\> Package

So then you can easily compare the stats from one build to another on the CI server as a report of some sort, and again this may not mean much to anyone if you are not used to Continuous Integration. The main crux of this question is to see how people manage this between builds and how they find it best to report upon. As I said it can be subjective but as knowledge will be gained from the answers it seems a worthwhile question.

# Answer
I take it you completely want to rule "Run the actual game" out, so basically my answer is disqualified from the get-go. But maybe you can take *something* away from it, hence why I post this regardless:

For my Master's thesis, I have various independent/parallel implementations to achieve the same thing for some modules of my game engine and I need to carry out some performance measurements. Technically, nothing would prevent me from just running the game and looking at the numbers displayed in the on-screen profiler, but I still wanted to automate that because it is a tedious process to perform whenever my implementation changes.

So what I have is this:

* A scoped profiler (that puts an object on the stack, takes a time stamp upon construction and one upon deconstruction) that is used to measure how long the function/scope of interest took to execute
* A module that stores a certain number of profiled samples and dumps the mean across the last n samples to a simple text file
* An in-game command line that can be used to start a game, load a map, change the algorithm that is used within the module to be inspected, change the path of the profiler dump file and lots of other stuff. Said command line is set up to check for a certain special file within the executable directory and load it to execute the string retrieved from it (as a means of very, very crude inter process communication)

So what this allows me to do is launch my application from any half-decent scripting environment (say, windows command prompt via batch scripts - but I actually use Ruby for that purpose), set a dump file path, load a map, leave it running for a few minutes, quit the running game, set another dump file path, switch the algorithm to use, load the map again, rinse, repeat. The Ruby script communicates with the game in-flight by creating that special file the command line module is looking for and putting the desired commands in the syntax the command line understands in it.

I don't actually have use continuous integration on this project right now, but nothing would prevent me from souping up that Ruby script to also parse the generated performance logs and produce xUnit-compatible XML to communicate with the CI-system when performance has unexpectedly gone haywire for some reason and run the script on every full build on the build sever.

Alright, so neither is my game written in XNA (it's plain C++ and DirectX), nor does this approach respect the fact that you don't actually want to *run* the game on your build sever. It also is nowhere near as flexible as what you are probably out for - but still, it is a neat, low-tech aproach to automated performance measuring that is somewhat CI-friendly (provided one has a beefy build server).

**Edit:** As for how far I have actually taken that approach - I only compare performance measurings gained from different implementations of just this one module. But the whole system is set up in a way that would allow me to dump any single one of the categories defined for my lightweight profiling framework and use the external scripting environment to interpret the results in whatever way seems useful right there and then. Taking the performance profiling aspect out of the equation, I further intend to

* Check for validity/consistency of all the assets by loading all the maps containing all the models/textures/sounds and checking the engine logs for anything unusual
* stress-test the engine and monitor the logs for any unexpected behavior that way across a timespan of several hours/days
> 2 votes

# Answer
I don't see what you describe as a helpful tool. As a developer a plain performance number is almost useless.

What you want is to profile your code, split it into logical chunks of and measure how much time each of those use, peak and average. Now you can tell what part of the code is causing problems, and you know where to look for optimizations.

The tricky part is not performance changes from one build to the other, you don't need an automated to figure that. The tricky part is performance differences between different machines, there is no way to extrapolate performance from one machine to another with different video card etc.

So what you want is a benchmark feature so that you can do a one click run and get the profiling numbers. This way you'll be able to test multiple machines simultaneously. There are several ways of doing this, for instance you can override the user input to get as close to running a normal game session as possible.

You might also want to have a longer test in order to spot memory leaks.
> 0 votes

---
Tags: xna, performance, testing
---


# Question
Title: Is it safe to set FPS rate to a constant?
I learned from game class that in update function, every movements must be time dependent for the sake of linearity in movement.

We made a simple game. Every move like going left, right or jump is written time dependent.

But, in some other computers, our game is worked very differently. For example, our character jumps higher than it should be. I guess this is because each computer has different FPS rate according to its specification.

My question is that what should we do to make this game work in same way in every computer? Setting FPS rate to a constant is a solution?

# Answer
> 20 votes
You will want to separate the game speed from frame rate. Check out this article: http://gafferongames.com/game-physics/fix-your-timestep/

I'll sum up parts that apply to your problem. We face 2 issues:

* Frame rates may fluctuate and vary across different hardware, so you want to keep game speed constant and independent of frame/rendering rate.
* It is also important to keep each time step you advance your physics to be a constant because that keeps the physics stable due the way most physics engines are designed (such as Box2D which Angry Bird uses); they use something called an integrator to do the math

To solve these problems, as the article states, we want our loop to be structure so that "the renderer produces time and the physics simulation consumes it in discrete dt sized chunks."

Each loop we update physics according to how much time is given, then render the final state. See code from article (I simplified it a bit and commented):

```
const double dt = 0.01;

double currentTime = current_time_in_seconds();
double accumulator = 0.0;

while ( !quit )
{
     double newTime = current_time_in_seconds();
     double frameTime = newTime - currentTime; //total time available this frame,
                                               //or the amount of time passed since
                                               //last iteration of main loop
     currentTime = newTime;

     accumulator += frameTime; //accumulator keeps track of how much time left

     while ( accumulator >= dt ) //consume available time in fix-sized chunks (dt)
                                 //Why fixed? for stable physics
     {
          integrate( &state, dt ); //step forward physics/game engine by time dt
          accumulator -= dt; //we used up dt amount of time, update accumulator
     }
//NOTE: there might still be some time left in accumulator, see explanation below
     render(state); //Render current state of the game given by physics/game engine
}

```

Because we consume time in fix-sized chunks (dt), there might be say half a (dt) amount of time left in `accumulator`. In above code this may cause physics to fall behind for a few iterations until accumulator sums up to at least 1 (dt). This may cause stuttering as we render state of the game advanced by different time steps each iteration. Therefore, we smooth this out by linearly interpolating between current and previous physical states; I'll explain more below the code:

```
const double dt = 0.01;

double currentTime = current_time_in_seconds();
double accumulator = 0.0;

State currentState;
State nextState;

while ( !quit )
{
     double newTime = current_time_in_seconds();
     double frameTime = newTime - currentTime;
     if ( frameTime > 0.25 )
          frameTime = 0.25;   // note: max frame time to avoid spiral of death
     currentTime = newTime;

     accumulator += frameTime;

     while ( accumulator >= dt )
     {
          currentState= nextState;
          integrate( nextState, dt );
          accumulator -= dt;
     }

     const double alpha = accumulator / dt;

     State state = nextState*alpha + currentState * ( 1.0 - alpha );

     render( state );
}

```

I saw a lot of confusion about the above code from article's comments about the interpolation so I changed the variable names to make it more understandable.

I'll explain it in my way here:

* When `accumulator` = 0, `alpha` = 0, `state` = `currentState`. We simply render `currentState`.
* When `accumulator` = 1/3\*dt, this means we need to render a state that is `currentState plus 1/3*dt` ahead in time. To do this, we actually make our physics engine advance 1 dt ahead of rendering to produce `nextState` and linearly interpolate between `currentState` and `nextState` to get `currentState plus 1/3*dt`.

In this case, our physics engine is actually running 1 time step(dt) ahead of rendering for the sake of keeping game speed and rendering consistent.

Any questions about above explanation, please do ask.

Note: I take no credit for above approaches; they all from the article mentioned.

# Answer
> 1 votes
The way to go is to use the delta time since the last update (ie. deltatime=1/fps or just the time since last update)

The thing is that you seems already to do that, so what can be wrong then?

I use milliseconds on an integer so I force my games to not run over say 200-300fps (~4msec) and if they run over say 200msec/frame I block that too (5fps). This is so I won't have any underflows/overflows in the calcs and so most **rounding errors** won't be big enough to notice.

On say a platformer where you 'add' the delta to say a jump speed (or its acceleration), you might want to use floats everywhere (for all variables connected to the deltatime: position, acceleration, ...)

---
Tags: movement
---


# Question
Title: Using "screenshots" in a game, is it allowed?
Lets say I have a game that is some kind of a quiz, and its questions are themed around gaming.

For it to be interesting, I would need to make references to well-known games and game-related stuff.

In a copyright infrigement sense, could I have problems with this? Imagine a question such as, "What was the currency used in game X?", or "Which company made game Y?".

Also, the same applied to screenshots of known games, and have a question near it, such as "What game is this image from?".

Toughts? Thanks

# Answer
> 8 votes
## tl;dr:

Tattoo the phrase *CITE WHAT'S NOT YOURS* on your arm, and you'll be happy forever.

## Some details:

Wikipedia says (emphasis added):

> Fair use is a limitation and exception to the exclusive right granted by copyright law to the author of a creative work. In United States copyright law, fair use is a doctrine that permits limited use of copyrighted material without acquiring permission from the rights holders. **Examples of fair use include commentary, criticism, news reporting, research, teaching, library archiving and scholarship.**

If your work falls under one of those categories, have some tea and go for a walk -- you have nothing whatsoever to worry about.

Otherwise, here are some general guidelines from having followed hobbyist game developers and news:

* **If you'll earn enough money out of it to live** (even if that money comes indirectly out of advertising on your site) do not use anyone else's licensed content. At all. Bob does work, Bob gets paid. If Bob gets paid for someone else's work, there's going to be trouble when that someone else finds out.
* **If you'll earn money, but not enough to live off of**, cite, make sure the licensed content is not the central core of your game and cooperate fully if someone asks their licensed content to be removed. Most likely, nobody will mind. Corporate types dig free advertising and indie types will just be flattered someone noticed them.
* **If you will make no money** (up to and including getting ad-revenue that just covers your server costs), cite what you use and you'll be good.

There will of course be exceptions, but this should cover almost all cases.

(ianal)

# Answer
> 3 votes
If this is a widely published commercial game, then you better get explicit permission for whatever you're using. Laws regarding this is not very well defined, you will want to take a look at this article and make your own conclusions.

# Answer
> 1 votes
My own gut feeling tells me that references are OK, that screenshots for the purposes of reviewing or demonstrating are OK, but screenshot use in another work is not.

But.

**I am not a lawyer and I am in no way qualified to give this advice**.

"Some random bloke on the internet said it was or wasn't OK" is not a sound basis for this decision. I'd suggest that if you want to continue with the idea you get the advise of someone who is qualified appropriately.

---
Tags: legal, copyright
---