title: Regulating Frames Per Second

text:
# Question
Title: Regulating Frames Per Second
I'm watching a video on regulating frames per second. I don't really fully understand the code.

```
public void run() {
    long lastTime = System.nanoTime();
    final double ns = 1000000000.0 / 60.0;
    double delta = 0;

    while(running) {
        long now = System.nanoTime();
        delta += (now - lastTime) / ns; // <--This line is confusing me.
        lastTime = now;                 //  Why is this divided by "ns"?
        while(delta >= 1) {
            update();
            delta--;
        }
        render();

    }
}

```

# Answer
Assuming the 60 is referring to the desired frames per second, the line

```
delta += (now - lastTime) / ns

```

is calculating, from the change in time, the amount of frames to process. `ns` contains the desired frequency (in nanoseconds) which is equivalent to 1 second per 60 frames. Dividing the change in time by this factor results in the conversion of nanoseconds to seconds and the amount of frames needed to calculate to 'catch up.'

For example, if 0.3 seconds had passed, you would need to process 0.3 seconds * 60 frames per second = 18 frames.

If the math is confusing at all, I suggest writing it out with the units to see how it works.
> 2 votes

---
Tags: java, frame-rate
---


# Question
Title: Fixed Function vs Programmable Pipeline performance with many batches
In OpenGL 2.0 I can easily make 10,000 draw calls per frame (with state changes in between each call). However, if i try to do this in either OpenGL ES 2.0 or DirectX9 with shaders, my peformance is 1Hz. Is there an inherent different between fixed function and programmable pipeline rendering that requires programmable pipeline to require much fewer draw calls per frame, or is it more likely that I'm just doing something stupid in my code? I thought that most fixed function pipelines were implemented in shaders nowadays anyway, so if it is the case that I have to batch, then how does the fixed function implementation get away with not batching if its really using shaders?

Any "official" resources you could point me to would be great.

# Answer
> 7 votes
The fixed function pipeline doesn't involve many changes to shaders (there may even be only a single "fixed function" shader in the driver's fixed-function emulation path; up to the driver how it handles legacy APIs) which are one of the more expensive things to change.

The driver also could be doing a bazillion different things to optimize or not depending on the specific function calls you're using (and even the order you're calling them in). The driver may be internally batching draw calls, for instance, which it doesn't do when shaders are being changed. It may even give you the same performance if you make a minor tweak to how you're doing things.

There are many other variables here, too, of course. You don't list your shaders. Perhaps you have some kind of very bad performance piece of code you've added to a shader that the default ones don't have. Maybe you're using vertex buffers inefficiently. Maybe you're doing one of dozen of things.

You should consider using a tool like Intel GPA or NVPerfHud to track this down.

# Answer
> 1 votes
I would add to this that using client memory to store your vertices is potentially more detrimental to performance than the number of draw calls. The reason for this is that if GL does not have full control over the vertex memory it has to either make a copy of your vertex array every time you draw or synchronize the pipeline (e.g. `glDrawArrays (...)` will not return until GL finishes using the data). When you use VBOs, GL manages the memory and it knows when the data changes so `glDrawArrays (...)` can safely be implemented asynchronously / without making an immediate data copy. Hundreds of draw calls using VBO-managed memory can be quicker than a handful of client memory draw calls as a result.

For this reason, immediate mode (which creates new vertex data each time it draws) can actually be more efficient in certain circumstances than using vertex arrays. Granted, using client memory to store vertex arrays has been deprecated for many years as has immediate mode, but since you brought up the fixed-function pipeline it was worth mentioning.

---

On the DirectX end of things, prior to Windows Vista issuing a draw call would invoke an expensive kernel-mode context switch. This was never an issue in OpenGL, because it always had a user-mode component to its driver, but D3D only gained a user-mode front-end with the introduction of WDDM. D3D10 also shifts the responsibility of resource validation from usage to load-time, so draw calls are even less expensive when you move from D3D9 to D3D10.

---
Tags: opengl, directx, performance, directx9
---


title: making rigid body stop using friction

text:
# Question
Title: making rigid body stop using friction
how am I suppose to apply friction to an object so that when I apply force it decelerates eventually to zero? Here are my physics objects:

Rigid Body "Sphere"

* Collision shape: btSphereShape(0.50)
* Mass: 1.0 kg
* Restitution: 0.5
* Friction: 10.0

Rigid Body "Platform"

* Collision shape: btBoxShape( btVector3(23.0, 0.5, 23.0) )
* Mass: 0.0 kg
* Restitution: 0.75
* Friction: 1.0

I apply central force of btVector3(0,0,-100) on key press 'W' to the sphere. The sphere moves but never stops. Is there anything else I should take into consideration? The sphere is not rolling (the force is to the center) and the damping cannot be used because it slows the object down on any force, even gravity.

What I have tried:

* Added mass to the platform. I set linear and angular factors to (0,0,0) so the platform didn't move by any applied force.
* Applied the negative of the total applied force. I get a working result but not how I wanted. If I had friction the object would slow down more realistically

# Answer
I created a little testbed to test this. With standard mass and friction, a ball rolling will not stop. Applying either linear -or- angular dampening will cause the ball to eventually stop. If you don't want things like gravity to be affecting it, then angular dampening used by itself should work just fine.

Likewise, replacing the sphere with a box in my simulation caused friction to work normally without any dampening.
> 1 votes

---
Tags: collision-resolution, bullet-physics, rigid-body-dynamics
---


# Question
Title: MiniMax where bots make simultaneous moves .
What is the correct approach for using miminax in a game where bots make simultaneous moves ?

# Answer
> 7 votes
Minimax works fine for simultaneous move games; the only modification required is that instead of enumerating an opponent's counter-moves to each possible move, you build a payoff matrix based on what you and your opponent play at the same time.

Recall that in minimax, at each node you enumerate your (or your opponent's) possible moves, evaluate your opponent's (or your) counter-moves to get the best one corresponding to each of your moves, and then pick the move that maximises your payoff. That is, you may have this:

```
A's choice | B's choice | payoff
---------------------------------
    A1     |     B1     |   +3
    A2     |     B2     |    0
    A3     |     B3     |   +1

```

Then the choice is clear; A should pick A1 because it leads to the best payoff (because A expects B to play B1, which leads to A playing ... and B playing ... and so on and so on until it leads to a payoff of +3).

With simultaneous moves, you need to consider both players' moves together, in a payoff matrix:

```
             | B chooses B1 | B chooses B2 | B chooses B3
----------------------------------------------------------
A chooses A1 |      +3      |      -2      |      +2
A chooses A2 |      -1      |       0      |      +4
A chooses A3 |      -4      |      -3      |      +1

```

Then the choice is not always so obvious, as you need to formulate an effective strategy to pick the best move. For example, in the above example, the choice is not obvious: A may choose A2 since it maximises the minimum expected payoff (-1, when B1 is played), but knowing that A will play A2, B may play B1 to realise the -1 payoff, but knowing that B will play B1, A may play A1 to get the +3 payoff and so on.

---
Tags: algorithm
---


# Question
Title: Fragments never falling into spot light's cone
I am using GLSL version 1.20 with OpenGL 2.1 .

I am trying to compute when a fragment falls into the area of a spot light. I have already set all the light values with glLightfv and glLightf, also the material. This is how I initialize the spot direction and spot cutoff:

```
float spotCutoff= 5.0;
vector<GLfloat> spotDirection= vector<GLfloat>{0,0,0,1};
// I use [0,0,0,1] because the object is in the [0,0,0] position
// but I also have tried (in vain) many other values.
glLightfv(GL_LIGHT0,GL_SPOT_DIRECTION,spotDirection.data());
glLightf(GL_LIGHT0,GL_SPOT_CUTOFF,spotCutoff);

```

In the fragment shader I use a function to know if the fragment is inside this cone:

```
bool isRayInsideCone(vec3 Light)
{
    // Light is taken from the vertex shader and normalized.
    // It is exactly computed as normalize(lightPos - eyePos)
    // With lightPos= gl_LightSource[0].position.xyz ,
    // and eyePos= gl_ModelViewMatrix * gl_Vertex (re-normalized in
    // the fragment shader).
    vec3 D= normalize(gl_LightSource[0].spotDirection);
    return dot(-Light,D) > gl_LightSource[0].spotCutoff;
}

```

But the problem is that this function returns false for every fragment. I can test this by just doing something like this:

```
if(isRayInsideCone(Light))
{
    gl_FragColor= some_color;
}
else
{
    gl_FragColor= other_color;
}

```

I just guess what I'm doing of wrong.

# Answer
As stated by Iva Kuckir You are passing an invalid spot direction.

The direction \[0,0,0\] is no direction, you need to set it to some other value. For example\[1,0,0\] in which case your spotlight is facing the positive X axis.

This is basically because you cant normalize a zero-vector.
> 1 votes

---
Tags: c++, opengl, glsl, lighting, fragment-shader
---


# Question
Title: ASSIMP in my program is much slower to import than ASSIMP view program
The problem is really simple: if I try to load with the function aiImportFileExWithProperties a big model in my software (around 200.000 vertices), it takes more than one minute. If I try to load the very same model with ASSIMP view, it takes 2 seconds.

For this comparison, both my software and Assimp view are using the dll version of the library at 64 bit, compiled by myself (Assimp64.dll).

This is the relevant piece of code in my software

```
// default pp steps
unsigned int ppsteps = aiProcess_CalcTangentSpace | // calculate tangents and bitangents if possible
    aiProcess_JoinIdenticalVertices    | // join identical vertices/ optimize indexing
    aiProcess_ValidateDataStructure    | // perform a full validation of the loader's output
    aiProcess_ImproveCacheLocality     | // improve the cache locality of the output vertices
    aiProcess_RemoveRedundantMaterials | // remove redundant materials
    aiProcess_FindDegenerates          | // remove degenerated polygons from the import
    aiProcess_FindInvalidData          | // detect invalid model data, such as invalid normal vectors
    aiProcess_GenUVCoords              | // convert spherical, cylindrical, box and planar mapping to proper UVs
    aiProcess_TransformUVCoords        | // preprocess UV transformations (scaling, translation ...)
    aiProcess_FindInstances            | // search for instanced meshes and remove them by references to one master
    aiProcess_LimitBoneWeights         | // limit bone weights to 4 per vertex
    aiProcess_OptimizeMeshes           | // join small meshes, if possible;
    aiProcess_SplitByBoneCount         | // split meshes with too many bones. Necessary for our (limited) hardware skinning shader
    0;

cout << "Loading " << pFile << "... ";

aiPropertyStore* props = aiCreatePropertyStore();

aiSetImportPropertyInteger(props,AI_CONFIG_IMPORT_TER_MAKE_UVS,1);
aiSetImportPropertyFloat(props,AI_CONFIG_PP_GSN_MAX_SMOOTHING_ANGLE,80.f);
aiSetImportPropertyInteger(props,AI_CONFIG_PP_SBP_REMOVE, aiPrimitiveType_LINE | aiPrimitiveType_POINT);
aiSetImportPropertyInteger(props,AI_CONFIG_GLOB_MEASURE_TIME,1);
//aiSetImportPropertyInteger(props,AI_CONFIG_PP_PTV_KEEP_HIERARCHY,1);

// Call ASSIMPs C-API to load the file
scene = (aiScene*)aiImportFileExWithProperties(pFile.c_str(),
    ppsteps | /* default pp steps */
    aiProcess_GenSmoothNormals         | // generate smooth normal vectors if not existing
    aiProcess_SplitLargeMeshes         | // split large, unrenderable meshes into submeshes
    aiProcess_Triangulate              | // triangulate polygons with more than 3 edges
    //aiProcess_ConvertToLeftHanded    | // convert everything to D3D left handed space
    aiProcess_SortByPType              | // make 'clean' meshes which consist of a single typ of primitives
    0,
    NULL,
    props);

aiReleasePropertyStore(props);

if(!scene){
    cout << aiGetErrorString() << endl;
    return 0;
}

```

this is the relevant piece of code in assimp view code

```
// default pp steps
unsigned int ppsteps = aiProcess_CalcTangentSpace | // calculate tangents and bitangents if possible
        aiProcess_JoinIdenticalVertices    | // join identical vertices/ optimize indexing
        aiProcess_ValidateDataStructure    | // perform a full validation of the loader's output
        aiProcess_ImproveCacheLocality     | // improve the cache locality of the output vertices
        aiProcess_RemoveRedundantMaterials | // remove redundant materials
        aiProcess_FindDegenerates          | // remove degenerated polygons from the import
        aiProcess_FindInvalidData          | // detect invalid model data, such as invalid normal vectors
        aiProcess_GenUVCoords              | // convert spherical, cylindrical, box and planar mapping to proper UVs
        aiProcess_TransformUVCoords        | // preprocess UV transformations (scaling, translation ...)
        aiProcess_FindInstances            | // search for instanced meshes and remove them by references to one master
        aiProcess_LimitBoneWeights         | // limit bone weights to 4 per vertex
        aiProcess_OptimizeMeshes           | // join small meshes, if possible;
        aiProcess_SplitByBoneCount         | // split meshes with too many bones. Necessary for our (limited) hardware skinning shader
        0;

aiPropertyStore* props = aiCreatePropertyStore();
aiSetImportPropertyInteger(props,AI_CONFIG_IMPORT_TER_MAKE_UVS,1);
aiSetImportPropertyFloat(props,AI_CONFIG_PP_GSN_MAX_SMOOTHING_ANGLE,g_smoothAngle);
aiSetImportPropertyInteger(props,AI_CONFIG_PP_SBP_REMOVE,nopointslines ? aiPrimitiveType_LINE | aiPrimitiveType_POINT : 0 );

aiSetImportPropertyInteger(props,AI_CONFIG_GLOB_MEASURE_TIME,1);
//aiSetImportPropertyInteger(props,AI_CONFIG_PP_PTV_KEEP_HIERARCHY,1);

// Call ASSIMPs C-API to load the file
g_pcAsset->pcScene = (aiScene*)aiImportFileExWithProperties(g_szFileName,

    ppsteps | /* configurable pp steps */
    aiProcess_GenSmoothNormals         | // generate smooth normal vectors if not existing
    aiProcess_SplitLargeMeshes         | // split large, unrenderable meshes into submeshes
    aiProcess_Triangulate              | // triangulate polygons with more than 3 edges
    aiProcess_ConvertToLeftHanded      | // convert everything to D3D left handed space
    aiProcess_SortByPType              | // make 'clean' meshes which consist of a single typ of primitives
    0,
    NULL,
    props);

aiReleasePropertyStore(props);

```

As you can see the code is nearly identical because I copied from assimp view.

What could be the reason for such a difference in performance? The two software are using the same dll Assimp64.dll (compiled in my computer with vc++ 2010 express) and the same function aiImportFileExWithProperties to load the model, so I assume that the actual code employed is the same.

How is it possible that the function aiImportFileExWithProperties is 100 times slower when called by my sotware than when called by assimp view?

What am I missing? I am not good with dll, dynamic and static libraries so I might be missing something obvious.

## ------------------------------

**UPDATE**

I found out the reason why the code is going slower. Basically I was running my software with "Start debugging" in VC++ 2010 Express. If I run the code outside VC++ 2010 I get same performance of assimp view.

However now I have a new question. Why does the dll perform slower in VC++ debugging? I compiled it in release mode without debugging information.

Is there any way to have the dll go fast in debugmode i.e. not debugging the dll? Because I am interested in debugging only my own code, not the dll that I assume is already working fine. I do not want to wait 2 minutes every time I want to load my software to debug.

Does this request make sense?

# Answer
> Why does the dll perform slower in VC++ debugging? I compiled it in release mode without debugging information.

This is because windows use debug heap whenever you run your code from a debugger, note that this is different from CRT heap that is set in your project settings as Debug/Release.

In order to disable system heap debug you need to use \_NO\_DEBUG\_HEAP=1 in your Windows environment settings, keep in my mind that such a huge difference in performance is caused by the library (Assimp) doing a huge number of allocations and de-allocations. For more info you can check this and this.
> 4 votes

# Answer
There can be multiple reasons for the Debug mode being slower.

One of the most likely ones(that affect performance the most) is that you are still linking with a dll that has **Optimization** off(you can still generate debug info, but make sure to turn Optimization on)

The second is because when debugging there is a special memory allocator used, that is somewhat slower, tough that shouldn't have such a high impact on performance, unless the application is extremely memory-intensive.

Edit: In my experience the algorithm that parses large sets of vertices and optimizes them for vertex locality is extremely memory intensive, so much, that it takes 20x longer in the debugger even in release builds.
> 2 votes

---
Tags: c++, assimp
---


title: Random terrain generation with caves

text:
# Question
Title: Random terrain generation with caves
I am currently working on a small game that will generate a world with caves and entrances to the caves, something like Terraria if you will. Today I reached some trouble on the world/cave generation code. I want to use Perlin Noise but I am not so sure how to implement it into my code. Could someone point me in the right direction for a reference or even code samples?

# Answer
> 2 votes
Here's something to get you started; for organic structures such as caves I've found that random walk works fine, and it's great because it's dead simple.

This sample code does the following:

* Create a basic 2d terrain (any method will do)
* Choose a cave entrance
* Starting from that cave entrance, do a 2D random walk and "carve" out the interior of the cave, making sure that we don't break through the surface

http://ideone.com/CJhzhm

```
using System;
using System.Collections.Generic;

public class Test
{
    static Random rand = new Random();
    static int width = 79;
    static int height = 24;
    static char[] cells = new char[width * height];
    // Cells are ordered left-to-right, top-to-bottom

    public static void Main()
    {
        GenerateRandomTerrain();

        // pick a point on the surface as the cave entrance
        int caveX = 35;
        int caveY = 0;
        while (cells[caveY * width + caveX] == ' ')
        {
            caveY++;
        }
        // drill down until we are deep underground
        while (cells[caveY * width + caveX - 1] == ' ' ||
            cells[caveY * width + caveX + 1] == ' ')
        {
            cells[caveY * width + caveX] = '.';
            caveY++;
        }

        // starting from the entrance, walk randomly within the terrain,
        // "carving out" the cave
        // make sure we do not create new entrances; the carving must not go
        // adjacent to an "open air" cell
        for (int i = 0; i < 1000; i++)
        {
            // "carve out" the current cell
            cells[caveY * width + caveX] = '.';

            // Get random direction:
            // 0: up
            // 1: right
            // 2: down
            // 3: left
            int dir = rand.Next(4);
            switch (dir)
            {
                case 0: // up
                    if (IsValidCaveCell(caveX, caveY + 1))
                    {
                        caveY++;
                    }
                    break;
                case 1: // right
                    if (IsValidCaveCell(caveX + 1, caveY))
                    {
                        caveX++;
                    }
                    break;
                case 2: // down
                    if (IsValidCaveCell(caveX, caveY - 1))
                    {
                        caveY--;
                    }
                    break;
                case 3: // left
                    if (IsValidCaveCell(caveX - 1, caveY))
                    {
                        caveX--;
                    }
                    break;
            }
        }

        // Show our results
        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                System.Console.Write(cells[y * width + x]);
            }
            System.Console.WriteLine();
        }
    }

    static void GenerateRandomTerrain()
    {
        for (int x = 0; x < width; x++)
        {
            int elevation = rand.Next(height * 4 / 5, height);
            for (int y = 0; y < height; y++)
            {
                if (y < height - elevation)
                {
                    // Open air
                    cells[y * width + x] = ' ';
                }
                else
                {
                    // Ground
                    cells[y * width + x] = 'X';
                }
            }
        }
    }

    static bool IsValidCaveCell(int x, int y)
    {
        // a cave cell is valid if:
        // - it doesn't exceed the world boundaries
        // - it isn't adjacent to an "open air" cell
        if (x < 0 || x >= width || y < 0 || y >= height)
        {
            // out of world bounds
            return false;
        }
        for (int dx = -1; dx <= 1; dx++)
        {
            if (x + dx < 0 || x + dx >= width)
            {
                continue;
            }
            for (int dy = -1; dy <= 1; dy++)
            {
                if (y + dy < 0 || y + dy >= height)
                {
                    continue;
                }
                if (cells[(y + dy) * width + (x + dx)] == ' ')
                {
                    // adjacent to "open air" cell
                    return false;
                }
            }
        }
        return true;
    }
}

```

Sample output:

```
          X   XX  XXX     X                    X       X   XX   X  XX X  X
        X XX  XX XXXX     X             X      X  X  X X X XX   X  XXXXX X X X
   X XXXXXXXX XXXXXXX  XXXXX X X    X   XX XX  X  X  X X X XX  XXXXXXXXXXX X X
XX X XXXXXXXXXXXXXXXXXXXXXXXXX X XX.XXXXXXXXXX X  X XX X X XX XXXXXXXXXXXX X XX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX........XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.........XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX...........XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX..XX........XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.............XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX..........XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.......X.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX..............XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX..............XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX...............XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXX...............XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXX.X.XXXXXXXXXXXXX..X.........X.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXX.....XXXXXXXXXXX...........XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXX......XXXXXXXXXXXXX....X.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXX.X......XX...X....XXX.X.XX.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
.XXXXXXX.........X........XXX...XX.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
......X..X.XX..X.X.............XXX.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
...........XXXXX...................XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
..........XXXXXX........X.....X....XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

```

You can play around with the number of iterations (it's set to 1000) to see what results you prefer.

Note that for platformers (you mentioned terraria) you would want to make sure players can't get stuck, that is there are no platforms for the player to jump out of. Platformers also prefer caves that are flatter than they are deep; you can modify the random walk to bias horizontal movements more than vertical for instance.

---
Tags: xna, c#, 2d, procedural-generation, perlin-noise
---


title: Indexed UV mapping problem

text:
# Question
Title: Indexed UV mapping problem
I am trying to map UV coordinates to indexed vertices with this code. I am using a vertex buffer, texture buffer, and index buffer (note the vertex and texture buffers are indexed in the same order)

```
glBindTexture(GL_TEXTURE_2D, staticTexture);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);

glBindBuffer(GL_ARRAY_BUFFER, textureBuffer);
glTexCoordPointer(2, GL_FLOAT, 0, 0);

glBindBuffer(GL_ARRAY_BUFFER, staticVertexBuffer);
glVertexPointer(3, GL_FLOAT, 0, 0);

glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);

glDrawElements(GL_QUADS, indices.size(), GL_UNSIGNED_INT, 0);

glBindBuffer(GL_ARRAY_BUFFER, 0);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
glBindTexture(GL_TEXTURE_2D, 0);

```

but when I run the code I get this (compared to the actual image that is supposed to appear on each face)

My code for setting the indices and uv coords (one face of the cube)

```
uv.push_back(Vector2(0, 1));
uv.push_back(Vector2(1, 1));
uv.push_back(Vector2(1, 0));
uv.push_back(Vector2(0, 0));
indices.push_back(vertexIndexFromCoordinates(x, y, z));
indices.push_back(vertexIndexFromCoordinates(x, y, z + 1));
indices.push_back(vertexIndexFromCoordinates(x, y + 1, z + 1));
indices.push_back(vertexIndexFromCoordinates(x, y + 1, z));

```

The only thing I can think of is that the UV's are being mapped by the vertices not the indices.

# Answer
Yes, your UVs are being mapped to the vertices, not to the indices -- that's the way that vertex buffers work.

Your vertex isn't just the position -- it's also the color, normal, texture coordinate, and any other attributes which you've attached to it.

In a case like the one here, you'll actually need a separate copy of each vertex for each face, because they don't share texture coordinates.
> 4 votes

---
Tags: opengl, vbo
---


# Question
Title: Is the Key Bindings delay unavoidable in Java when pressing different directional keys quickly?
I've read just about every tutorial I can on why to use Key Bindings instead of implementing the KeyListener interface, including all the examples that show using a field to track the key event because of the repeating delay when holding down the same key. No matter what I do though I simply can't get past a keyboard delay when alternating quickly between directions (i.e. - 'W','D','S','A'). I've read some comments that state this is very dependent on your keyboard OS settings, and in some cases is just unavoidable. Some of the registry editing suggestions for keyboard speed seem to indicate there is some truth in that. Is there a posted solution somewhere that guarantees a "hardware independent" Java solution for handling quick key presses without delay?

# Answer
> 2 votes
You might consider using JInput, you won't suffer the same problem.

---
Tags: java, 2d, events
---


title: portal cutoff effect

text:
# Question
Title: portal cutoff effect
I want a 3D Mesh to come out of a flat portal. Only the part of the mesh that's coming out of the portal should be rendered, so the mesh should be cut off or sliced until it's fully outside the portal.

I thought about using discards in a fragment shader, but since I work on iOS OpenGL ES 2.0 I'd like to avoid that for performance reasons. Is there a performant way to do this?

# Answer
You can implement the clipping plane functionality using vertex and fragment shaders and using discard fragment.

The other option is described in this paper, where it introduces a technique that modifies the projection matrix so the near and far planes are re-positioned to become a general purpose clipping plane. This way you can implement that without developing extra shaders. Also quoting from the paper's introduction:

> The plane chosen to represent the image is simply the plane that naturally separates the image from the rest of the environment, such as the plane of a mirror, portal,or water surface.
> 4 votes

---
Tags: ios, opengl-es2, graphic-effects, portals
---


# Question
Title: How can I optimize this flood fill algorithm?
I'm creating a sprite and animation editor like this one. I'm having performance issues with my flood-fill algorithm.

Basically, I open an image with the different modules that are part of a frame of an animation. When I double-click a module I run a depth-first search algorithm that checks all the pixels of that part of the image that are surrounded by transparency. From that I get the rectangle of said module (the position and size). With large images, when I double-click that part of the image the application freezes.

How can I improve my algorithm?

Right now what I do is maintain an array of already-checked pixels and a list of pixels to check. I start with the pixel that I double-clicked and check if the surrounding pixels have transparency. If they do not, I check for the surrounding pixels of *those* pixels and so on until all the surrounding pixels are transparent. Then I can get the minimum and maximum position in the X-axis and Y-axis and use that to construct the bounding rectangle of the frame.

This is my code:

```
private Rectangle widthSearch(int posX, int posY)
{
    Rectangle result = new Rectangle();
    int leftX, topY, rightX, botY;
    leftX = rightX = posX;
    topY = botY = posY;

    List<Point> closedList = new List<Point>();
    List<Point> toProcessList = new List<Point>();

    Point processingNode;
    Color colorAux;
    int alphaAux;
    int offsetX = 0;
    int offsetY = 0;

    toProcessList.Add(new Point(posX, posY));

    int[] dx = { 1, 1, 0, -1, -1, -1, 0, 1 };
    int[] dy = { 0, -1, -1, -1, 0, 1, 1, 1 };

    while (toProcessList.Count > 0)
    {
        processingNode = toProcessList.ElementAt(0);
        closedList.Add(processingNode);
        toProcessList.Remove(toProcessList.ElementAt(0));

        for (int i = 0; i < dx.Count(); i++)
        {
            offsetX = dx[i];
            offsetY = dy[i];
            try{
                if (!closedListContains(closedList, processingNode.X + offsetX, processingNode.Y + offsetY) && !closedListContains(toProcessList, processingNode.X + offsetX, processingNode.Y + offsetY))
                {
                    colorAux = bmp.GetPixel(processingNode.X + offsetX, processingNode.Y + offsetY);
                    alphaAux = (colorAux.ToArgb() >> 24) & 0xFF;
                    if (alphaAux > 0)
                    {
                        toProcessList.Add(new Point(processingNode.X + offsetX, processingNode.Y + offsetY));
                    }
                }
            }
            catch (Exception e)
            {
                Console.Write(">>>>>>>>\n" + e + "\n>>>>>>>>>");
            }
        }
    }

    for (int i = 0; i < closedList.Count(); i++)
    {
        if (closedList.ElementAt(i).X > rightX)
            rightX = (int)closedList.ElementAt(i).X;
        if (closedList.ElementAt(i).X < leftX)
            leftX = (int)closedList.ElementAt(i).X;
        if (closedList.ElementAt(i).Y < topY)
            topY = (int)closedList.ElementAt(i).Y;
        if (closedList.ElementAt(i).Y > botY)
            botY = (int)closedList.ElementAt(i).Y;
    }

    result.X = leftX;
    result.Y = topY;
    result.Width = rightX - leftX;
    result.Height = botY - topY;

    return result;
}

private Boolean closedListContains(List<Point> closedList, int posX, int posY)
{
    Point pointer = new Point(posX, posY);
    for (int i = 0; i < closedList.Count(); i++)
    {
        if (closedList.ElementAt(i).Equals(pointer))
            return true;
    }
    return false;
}

```

I only call the `widthSearch()` method when I double-click a `PictureBox`. It is not inside a loop.

# Answer
> 5 votes
I suspect you are using an inefficient implementation of the flood fill algorithm especially that the application freezes when applied on large images.

By looking quickly at your code I can identify few problems

It seems your code has a **Big O( N^2 * K )** and might even be **O(N^3)**, which translates to your code like this:

```
toProcessList.Count // Looping through that O(N)
closedListContains  // That's O(N), also called twice.
dx.Count            // This is K

```

Keep in mind that I didn't do exact analysis, and this is only a rough estimate. Three nested loops isn't really fast (unless you have a very small data set) This will be the biggest speed improvement.

I also suspect that `widthSearch` ~~is being called inside a loop. Which makes things even worse. But I don't have enought info about.~~

Second the chosen data structure (List) is not ideal, to be more clear:

* Your `closedListContains` implementation clearly runs in O(N) time.
* You also have two expensive operations which you are using liberally. `List<T>::RemoveAt is O(N)` unless it was from the end of the list. `List<T>::Add` I suspect this is O(N). Actually according to the documentation:

> If Count is less than Capacity, this method is an O(1) operation. If the capacity needs to be increased to accommodate the new element, this method becomes an O(n) operation, where n is Count.

### Now my suggestions for improvement

* Use some kind of `Dictionary` for `closedPoints` instead of `List`s where `Searching` is faster (or any other data structure with fast search but I think dictionaries will perform better here).
* Use a linked list/vector doubling or any data structure where `Adding/Removing` could be faster (static array could also be great if you know the maximum size previously).

(the above points depend on the size of data and the underlying implementation of data structure).

* Other enhancements could be done by making iterating over the image more cache friendly especially when accessing it using `GetPixel`. But I won't go that path unless I am done with the above and did't get a decent result.

---
Tags: algorithm, path-finding, optimization, image
---


title: Ways to describe resouces

text:
# Question
Title: Ways to describe resouces
I have one way - *xml* and code like this:

```
<Texture file="file_name.jpg">
  <Sprite id="ID_SPRITE_1" coordinates="0 0 64 64"/>
  <Sprite id="ID_SPRITE_2" coordinates="64 0 64 64"/>
  <Sprite id="ID_SPRITE_4" coordinates="128 0 64 64"/>
</Texture>

```

then parse and load it, when application starts, then use resources by *id*.

What another ways to describe paths and propeties of resources used by developers and why?

# Answer
> 1 votes
Commonly game resources, menus (GUI), levels, etc will all be handle offline using a set of tools, usually developed in-house for an exact purpose. These tools will then often export to a bespoke format designed to allow the game to quickly load in these files with little overhead. To do this the files will typically be in a binary format and so every tweak must be performed in the tool and then re-exported for the game.

Tools are an important part of game development. They reduce the responsibilities of the programmers and allow all members of the team to edit resources without the knowing how to read through a code file. Most importantly though, the more that can be pre-prepared offline to reduce overhead in game, the better.

# Answer
> 1 votes
This is going to depend entirely on each kind of resource. There are many ways to manage your resources, too.

An example of how I do this with one of my projects, is I separate resources into packages. so a package may consist of 5-10 files that define a map, or a couple of hundred of precompiled shaders. Then when I want to a resource I call `Cache->Load<Map>("Map1.pak", "Map.xml");`

Of course, every project that I've worked with has used a different system. For example, you may want to check Ogre3d to see how resource management is done there.

---
Tags: assets, resource-management
---


# Question
Title: Including slick2d or slick-util in maven build?
I'm converting a project to lwjgl and trying to use slick-util as well. There's no slick-util maven repo anywhere (nor slick2d itself anymore). I've included local dependancies before using

```
    <dependency>
        <groupId>org.newdawn</groupId>
        <artifactId>slick</artifactId>
        <version>237</version>
        <scope>system</scope>
        <systemPath>${project.basedir}/lib/slick-util.jar</systemPath>
    </dependency>

```

The maven package process runs without issue, but when I try to run the jar, it errors out with a `ClassNotFoundException`. There's no mention of slick-util in the manifest and I can't find out how to make my game load that jar properly.

Side question: how do I ensure when I distribute my applications, the game properly installs these libraries?

# Answer
Your seem to be missing the dependency for slick at runtime. Hard to tell without knowing Class was not found. Is it a class from the slick dependency? Using scope compile instead of system should fix it.
> 0 votes

---
Tags: java, slick
---


# Question
Title: opengl offscreen rendering in linux is slow
My opengl application runs at about 110 fps. The moment I add off-screen rendering, it slows down to 15 fps. I am using frame buffer objects and glReadPixels to render off-screen. I have searched on net and found that GPU memory to CPU memory data transfer is slow and vice versa is fast. I have ATI Mobility Radeon™ X2300 with 128MB video memory.
So my questions are
1) Is there is way to increase VRAM to CPU ram data transfer speed?
2) Are there any GPUs in market optimized for better read speed?

# Answer
> 4 votes
glReadPixels is going to naturally be slow. There really isn't any magic that will make this any faster than it is. I would suggest using glReadPixels to read your buffer to a PBO, and then read those PBOs asynchronously.

Depending on what you're trying to accomplish, Render to Texture might be a better fit.

---
Tags: opengl, rendering, gpu, linux
---


# Question
Title: Are there multiple valid definitions for what translate, rotate and scale do?
Are there multiple valid definitions for what translate, rotate and scale do to the 4x4 matrix?

I bring up this question, because I have a simple webgl program that draws a square and does a few translate, rotate, and scale transformations. When I originally wrote the program I was using glMatrix v0.9.5. I upgraded the glMatrix to v2.2 and now the square is in a different position and rotation.

I'm fairly certain I correctly upgraded the program to use the new version, since the program was so small to begin with.

Regardless of what is happening to my program, I'm very interested to know if translate, rotate, and scale have a single universal definition or if different graphics engines / matrix libraries can have different definitions for what the transforms do.

Further details:

No transformations (origin is at the top left corner)

The square program with the following transformations:

**translate** x: 250, y: 250, z: 0

**rotate around Z axis** angle: -90

Finally the square program with the following transformations:

**translate** x: 250, y: 250, z: 0

**rotate around Z axis** angle: -90

**translate** x: 150, y: 0, z: 0

# Answer
I have discovered that the matrix library I am using (glMatrix) did in fact change how its mat4.translate works.

It seems that different people do have different ideas about what the transforms definitions are.

I opened up an issue on the glMatrix github page where it is being discussed more for those who are interested.
> 1 votes

---
Tags: graphics, transformation, mathematics
---


# Question
Title: Suitability of ground fog using layered alpha quads?
A layered approach would use a series of massive alpha-textured quads arranged parallel to the ground, intersecting all intervening terrain geometry, to provide the illusion of ground fog quite effectively from high up, looking down, and somewhat less effectively when inside the fog and looking toward the horizon (see image below).

Alternatively, a primarily shader-based approach would instead calculate density as function of view distance into the ground fog substrate, and output the fragment value based on that.

*Without having to performance-test each approach myself*, I would like first to hear others' *experiences* (not speculation!) on what sort of performance impact the layered alpha texture approach is likely to have. I ask specifically due to the oft-cited impacts of overdraw (not sure how fill-rate bound your average desktop system is). A list of games using this approach, particularly older games, would be immensely useful: if this was viable on pre DX9/OpenGL2 hardware, it is likely to work fine for me.

One big question is in regards to this sort of effect:

(Image credit goes to Lume of lume.com)

Notice how the vertical fog gradation is continuous / smooth. OTOH, using textured quad layers, I can only assume that layers would be mighty obvious when walking through them -- the more sparse they were, the more obvious this would be. This is in contrast to where fog planes are aligned to face the player every frame, where this coarseness would be much less obvious.

# Answer
> 15 votes
Since you've asked for experiences, here are mine.

Back in the days when I was programming PS2 games, the "layered alpha quads" approach was a way that we often implemented fog. Occasionally as ground fog, but much more commonly as full-screen fog. And it worked just fine in either case. So yes, it was viable in the pre-fragment-shader days.

Well, sort of. The problem, as you've noted, was that if you want smooth fog such as that seen in the screenshot, you need a rather absurd number of alpha quads.

On the PS2, we could usually afford somewhere between three and five layers. Which definitely did look like "walls" of fog floating in front of you. More than that and the fill rate began to kill our frame rate.

Normally, these quads would be drawn at fixed distances in front of the camera, so you never got the situation that you mention, "walking through" one of them. On the other hand, by using those fixed distances, everything else in the world *does* pass through those planes as the player moves around, which is a pretty obvious graphical glitch. Almost everyone did it back then, but it wouldn't be acceptable now (unless you were doing it for stylistic reasons). (Exception: some folks calculated fog values as part of the PS2's equivalent of a vertex shader. That worked and was much faster, but required your models to be highly tesselated. You couldn't have long walls, for example, because fog was only being calculated at the corners of the wall, and then being smeared around over the whole face of the wall. The wall appeared fully fogged if you were standing right next to its middle, for example, since it was only testing the fog levels at its endpoints)

Note that if you place fog quads statically in the world (as you mention as a possibility), then you won't be able to get the appearance of extremely smooth fog, as in the image you provide -- there will be odd overlaps between adjacent quads depending on the viewer's orientation. Those overlaps may appear as stripes or trapezoids (if the quads are untextured) or as clumps (if they're textured).

But let's assume that we're using wide, screen-facing quads to do this ground fog and do some calculations for how to make really smooth fog using this method, on flat ground, with a camera looking straight forward -- that's our ideal situation. Let's assume HD resolution: 1920x1080, which puts our horizon at scanline 540. Let's also assume that we have visibility all the way to the horizon (that is, assuming that you don't have the fog reaching full opacity before reaching the horizon). With one fog quad starting and one stopping at each scanline (in order to get smooth fog), we need (540 * 2 ==) 1080 fog quads. Each of these 1080 fog quads will cover the whole horizontal expanse of the screen, and some vertical portion of the screen (the closest fog planes will touch just a couple rows of pixels at the bottom of the screen. The middle ones will cover more rows of pixels, the furthest ones will cover a smaller number of rows of pixels, due to perspective).

Let's estimate low, and say that on average, a fog plane will cover about 300 rows of pixels. The closest ones will cover less, the furthest ones will cover less, the middle rows will cover a lot more.

With that estimate, we get (1920x300 ==) 576,000 pixels being touched by the average fog quad. In total, that's (576,000 * 1080 ==) 622,080,000 pixels being touched in total for the whole "smooth fog via rendering lots of translucent geometry" effect. And that number will go up for people running at a higher resolution. And what's more, we get that same number of tests against the z-buffer, and nearly that same number of pixel blend operations, since all these transparent layers are drawing over each other again and again. That's a *lot* of pixels.

And that's the best case scenario -- you'll get far more screen coverage of the fog quads if the user looks down or crouches.

Note that since we're overlapping 1080 quads, we probably want an alpha value of about (1.0 / 1080 ~=) 0.0009 set on each, so that our fog reaches full opacity if you look through all 1080 quads. (We could go higher than that, but this is the value assuming that we want to spread the range around as much as possible). Note that this value can't be represented as the alpha component of a 32-bit color value (256\*0.0009 ~= 0.237 and so will be rounded down to 0 if you try). You'll need to provide the 0.0009 value to OpenGL as a floating point value for this to work at all. (Also note that you won't actually want to set this same value on each -- while we defined that we wanted one quad to start and one to finish on each scanline below the horizon in order to give us smooth fog, you actually want the close quads to have lower opacity and the distant ones greater opacity, since the distance covered by a scanline is greater further away, and thus those distant fog quads represent more space than do the closer ones)

Also note that the fog blends won't work quite correctly using this approach, as they would with a modern shader -- instead of getting one calculation of "blend between the base object color and the fog color using this percentage", you get 1080 calculations of "blend between the color so far and the fog color by the fog percentage". Which means that the fog is going to affect objects following a logarithmic falloff. (That is, an object affected by 20 fog quads will appear less than twice as fogged as something affected by 10 fog quads, because the first fog quads have more of an impact in the blending operation).

All of which is to say: **Please just use a fragment shader.**

No, really. It's simpler and cheaper and faster and quicker to implement and less error-prone and lets you get back to actually making your game and is better in every possible way. We totally would have done it back in the PS2 era if it was even vaguely possible at the time.

---
Tags: opengl, 3d, textures, shaders
---


# Question
Title: How to centralize stat/feat/equipment related changes in an RPG?
I have a game with an RPG system where derived stats, like HP,armor, etc depend on a variety of components: armor, stats and feats. I'm running into an issue where the code to change derived metrics gets spread throughout the game - some is in the inventory module, another in stats module, another in buffs module.

**How can I centralize and ensure accuracy of all my stat/equipment related changes to the character?**

I thought that I can just create a "mega method" within the character class that would recalculate everything any time I change anything within the formula, but I don't know **if this recalculate everything is a good practice**, or if there are potential pitfalls with this approach down the road.

One of the complications with the complete rebuild that I see is that I will have to keep track of the player's HP and properly restore it after rebuild is complete.

# Answer
This also largely depends on how your character class is setup.

Assuming we're using direct references here, I would actually refrain from storing your stats directly. Instead I might have the following:

```
int Player::GetStrength() { return _stats.strength + equipment.GetStrength() + buffs.GetStrength(); }
int Equipment::GetStrength() { return _head.strength + body.strength + gauntlets.strength + leggings.strength + feet.strength }
int Buffs::GetStrength() { int strength = 0; foreach(Buff buff in Buffs) { strength += buff.strength; } return strength; }

```

Then any time you need to reference this, whether for UI purposes, combat calculations, etc... you have a realtime value with minimal performance cost.
> 3 votes

---
Tags: architecture, rpg, objective-c, character, methodology
---


title: Starting game development on linux

text:
# Question
Title: Starting game development on linux
So I'm considering beginning doing some game development using Ubuntu, however I'm a bit lost when considering how I'm going to start.

When I begun doing it on Windows, the choice was kind-of obvious: XNA/C# or Unity (again C#). UDK and CryEngine was simply too much for my lonely horse, and other options seemed not as good as the ones I just mentioned (for one reason or another).

But now, on linux, I'm kind of overwelmed by the amount of choices. However I've caught my eyes on SDL, due to its similar nature with XNA, and support for C# with Language Bindings.

So, how would you guys recommend I started with SDL, and which tools would you recommend?

Thanks in advance.

João Borrego

# Answer
> 1 votes
> However I've caught my eyes on SDL, due to its similar nature with XNA

These are probably fairly different. SDL draws graphics (at a fairly low level) and handles input but things like asset loading and game loops will be your stuff, in particular for 3D graphics you will be looking at raw OpenGL.

You could have a look at MonoGame for an XNA clone. Unity builds for Linux but I'm not sure that the tools work on it. SFML would be an alternative to SDL.

---
Tags: c#, sdl, linux
---


title: Fight with creativity burnout

text:
# Question
Title: Fight with creativity burnout
I have big creativity burnout :/ Do you have any ideas how can I fight with it ??

# Answer
* Force yourself. The best creative works are 5% inspiration, 95% perspiration. If the ideas aren't flowing, still, keep working. Get your mind into the habit of getting work done and that is half the battle right there.
* Seek out interesting stimuli. If you're making games, stop looking to other games for inspiration: Watch films, visit a museum, read a book, attend a talk.
* Improve your skills. Often what we call burnout is really frustration, perhaps because we're having trouble fleshing out an idea or implementing a design. If this is true, ask other designers how they overcome problems, or read books such as The Art of Game Design to gain a fresh perspective on your game, or scour a few blogs to gain inspiration from published games.
* Improve or change your tools. Related to the skills issue is the tools issue. Sometimes you just need to use different tools to see the work in a different light and perhaps discover new ways to make progress. If you normally write linear design docs, try a mind-map, or a Wiki. If you make maps in a 3D editor, try sketching them on paper or using a 2D tile editor. Try a different graphics app, audio app, programming language, game engine or library, or game-maker environment. A subtly different approach can often result in a massively different result.
* Work with artificial constraints and starting points. Pick 2 random nouns from a dictionary and try to combine them into some sort of gameplay. Go for a walk and try to think of games based around things that you see. Look up a film on IMDB.com and see how you would make a game out of it. Take a game you know well and see if you could rework the essence of its gameplay to work with one button, or two colours, or audio only.
* Rediscover your original motivation. If you care about burnout, that implies that you feel unable to do something which you really wish to do. Why do you wish to design games? Think back on what originally caught your interest, imagine the context and the possibilities that you saw, and recapture the feeling.
* Back to the first one - force yourself. If you can follow Chris's suggestion and take 3 months off to recharge your batteries then that is great, but most of the time you can't afford to only work half the time. Get used to making those first marks on an intimidatingly blank canvas, and don't worry about failure - you can revise and improve your work later, as long as you do the work in the first place. Even the greatest novels consist 1/3rd of words like "the", "and", "is", and so on - and there's no reason why that requires inspiration or creativity. Keep designing - you can improve it later.
> 34 votes

# Answer
Help others with their problems. You will naturally seek creative solutions for them and the juices will start flowing again.
> 9 votes

# Answer
I've found this helpful, and it can also be found in *"If you want to write"* by Brenda Ueland.

Take a walk.

A long walk. At least 45 minutes. With no specific destination. Don't try to think about anything specific. At some point, things just start to pop in your head.
> 6 votes

# Answer
I've been finding side projects help a lot. I went and got a job at an actual game studio, and somehow, spending forty hours a week plowing through game bugs makes me *more productive at home*, even discounting the fewer hours I work on my own projects.

If I end up leaving this studio I'll probably contract myself out as an indie game coder. You provide art and design and money, I make your game, and on the side, I make my game.

Another trick I've found is that, if you start getting bored with writing a game, start a different game. You have to be *really careful with this one* so you don't just leave a trail of abandoned games behind, but as long as you keep going back to them, juggling two or three dev projects can leave you more productive on all of them than you'd be individually.
> 3 votes

# Answer
Another thing to try is tidy your workspace. Clean the whole space from top to bottom. Get rid of everything you don't need - even if that is into a box to deal with later.

You may find that the clearing of space also has a clearing of mind effect.
> 3 votes

# Answer
There is some good tips HERE and more info.

1. Do Something You Love Doing / Spending Time On Your Hobbies
2. Take a Break
3. Spend Time with Others
4. Change Surroundings
5. Read Magazines, Books, Websites
6. Inspirational Websites and Galleries
7. Browse Portfolios
8. Visit a Creative Showcase (art, theatre, etc)
9. Travel
10. Work Out / Stay Active
11. Evaluate
> 2 votes

# Answer
Make a strict schedule for your project. Don't spend too much time on a single aspect of a game or you'll end up with filler content that just makes your game harder to make in the long run. Using a role playing game as an example, making a ton of classes means making more equipment and skills, which in turn means more work when balancing the gameplay. This is an example of Parkinson's Law. I'm just getting over game design burnout myself by following this principle.

http://en.wikipedia.org/wiki/Parkinson's\_law
> 0 votes

---
Tags: game-design
---


# Question
Title: How do I make a more or less realistic water surface?
I want to make a similar water surface like in this picture:

I need the water surface in the same view than in the picture. Is it possible to work without shaders? I want to develop a little game for Xbox Live Indie Marketplace, Windows Phone and maybe later iPhone/iPad.

How should I make the water surface, so that it works on multiple platforms?

# Answer
> 3 votes
There are several things going on in that picture. But it definitely needs a specialized shader if you want any kind of interactivity (such as looking at the water from various different angles).

1. Animated Mesh (probably)
2. Animated Surface Normals
3. Blending Between the following colors:
4. Reflection (Solid color or cubemap)
5. Water Color (Possibly using refraction, depth fog, and other effects depending on complexity)

The most basic shader you could use for this would use a simplified 'Fresnel term' to blend between a reflection and the 'water color'. The water color could be a solid color. But for more realistic water you can change it depending on several different things.

For example, if there are objects that should be visible under the water, you can blend between their color and the water fog color, using a depth map of objects that are behind the water. If you don't mind some more complexity, you could use techniques like 'sub surface scattering' to simulate the effect of light shining through the waves.

The reflection can also be a solid color, but you probably want to sample a cubemap instead. For example, the cubemap that you might already be using for your skybox. That way you can see the sky reflected in the water.

Unfortunately it becomes a bit more complex when your water isn't a static mesh. You could either generate a new mesh on the CPU and send that to the GPU each frame, or you could use a Vertex Texture Fetch (VTF) in the vertex shader you use for the water surface. This might not be supported on all the platforms you want to target.

It's also worth noting that if your mesh is animated, you also need to update the normals of the mesh each frame, which can be quite expensive (not really a problem for desktop computers, but I wouldn't recommend it for the ipad).

You can learn more about most of what you need at this GPU Gems article about refraction.

A full simulation would probably be overkill, and my guess is that you're probably best off using the classic 'flat plane with animated normal map' approach. But I also wrote some words that you might find interesting about a Water Simulation I created with DirectX11 in Unity. My current version is cross platform, but only for desktop computers, and I haven't looked into creating versions that would work on the mobile devices.

---
Tags: xna, c#, shaders
---


# Question
Title: Cant get a Farseer Physics body’s rotation to follow the mouse
Here is what’s in my HandleKeyboard() method that is called from the Game1 Update method.

```
        MouseState mState = Mouse.GetState();
        // the Vector2 that will hold the angle from the player to the mouse pointer.
        Vector2 mDirection = new Vector2(0, 0);

            // Get the current mouse position from the state update in the beginning of this method.
            Vector2 mPosition = new Vector2(mState.X, mState.Y);
            // Subtract the potsition of the player fromthe mouse pointer to get the exact angle in a vector2
            mDirection = mPosition - arrow.Position;

            // Control Rotation
            arrow.FixedRotation = true;
            // display the arrow in the rotation gathered above.
            arrow.Rotation = (float)Math.Atan2(mDirection.Y, mDirection.X);

```

From what I have read, this seems like the exact right thing to have the arrow look at my pointer. However when I rotate the mouse around the pointer it really doesn’t work properly.

It's hard to explain so here is a youtube video displaying what’s happening

I really hope you can tell me what’s going wrong.

# Answer
> 1 votes
This happens because Farseer (now named VelcroPhysics) works with the KMS (Kilo, Meter, Second) system (as explained in the section "Drawing the World" of this slightly outdated documentation). Because of that, the arrow's position is a really "small" vector (something close to (0, 0)) if you interpret it directly in pixels (which is what you're doing).

In order to get the correct position in pixels, you have to obtain a new Vector2 by calling this function provided by Farseer:

```
Vector2 arrowPositionInPixels = ConvertUnits.ToDisplayUnits(arrow.Position);

```

Only then, you can continue with your code of obtaining `mDirection` and calculating the rotation.

Alternatively, you can obtain the position of the mouse in the unit system used by Farseer with:

```
Vector2 mousePositionKMS = ConvertUnits.ToSimUnits(mPosition);

```

And work in the KMS system. Both approaches should give the same rotation result. Just make sure you're always working in the same metric system (Farseer's KMS or pixels).

---
Tags: xna, c#, farseer-physics-engine
---


# Question
Title: Was my horizontal drag performed from left to right or from right to left?
I want to determine if a horizontal drag was performed from left to right or from right to left. In addition, I want to do the same with the vertical drag.

How can I do that?

How can I check if the horizontal drag was performed from left to right or from right to left?

```
protected override void Update(GameTime gameTime)
    {
        while (TouchPanel.IsGestureAvailable)
        {
            GestureSample gs = TouchPanel.ReadGesture();
            switch (gs.GestureType)
            {
                case GestureType.HorizontalDrag:
                //from left to right
                Count += 1;
                //from right to left
                Count -= 1;
                break;
                case GestureType.VerticalDrag:
                //downwards
                Count += 1;
                //upwards
                Count -= 1;
                break;
            }
        }
        base.Update(gameTime);
    }

```

# Answer
> 2 votes
Mark the starting position of the drag. Then compare against the end position. The difference between them will tell you the direction.

With XNA, this is provided for you in the form of `GestureSample.delta`

The delta is a Vector2 that contains the difference for each axis. For example:

If you moved up and to the right, your delta vector might look like (10, 10). If you moved down and to the right it could look like: (14, -9).

So, the easy way to tell the direction of the swipe is:

```
if(gs.delta.x > 0)
  //moved right
else if(gs.delta.x < 0)
  //moved left
else
  //didn't move left or right

if(gs.delta.y > 0)
  //moved up
else if(gs.delta.y < 0)
  //moved down
else
  //didn't move up or down

```

---
Tags: xna, c#, windows-phone-7, windows-phone-8
---


# Question
Title: Automatically triggering standard spaceship controls to stop its motion
I have been working on a 2D top-down space strategy/shooting game. Right now it is only in the prototyping stage (I have gotten basic movement) but now I am trying to write a function that will stop the ship based on it's velocity. This is being written in Lua, using the Love2D engine.

My code is as follows (note- object.dx is the x-velocity, object.dy is the y-velocity, object.acc is the acceleration, and object.r is the rotation in radians):

```
function stopMoving(object, dt)
    local targetr = math.atan2(object.dy, object.dx)
    if targetr == object.r + math.pi then
        local currentspeed = math.sqrt(object.dx*object.dx+object.dy*object.dy)
        if currentspeed ~= 0 then
            object.dx = object.dx + object.acc*dt*math.cos(object.r)
            object.dy = object.dy + object.acc*dt*math.sin(object.r)
        end
    else
        if (targetr - object.r) >= math.pi then
            object.r = object.r - object.turnspeed*dt
        else
            object.r = object.r + object.turnspeed*dt
        end
    end
end

```

It is implemented in the update function as:

```
if love.keyboard.isDown("backspace") then
    stopMoving(player, dt)
end

```

The problem is that when I am holding down backspace, it spins the player clockwise (though I am trying to have it go the direction that would be the most efficient at getting to the angle it would have to be) and then it never starts to accelerate the player in the direction opposite to it's velocity.

What should I change in this code to get that to work?

**EDIT :**

I'm not trying to just stop the player in place, I'm trying to get it to use it's normal commands to neutralize it's existing velocity.

I also changed math.atan to math.atan2, apparently it's better. I noticed no difference when running it, though.

# Answer
> 2 votes
*I would strenuously urge you to give the player's ship retro-rockets to be used during braking.*

You really need to do that, because the alternative is for the computer to take over and automatically turn the ship to face away from its direction of travel whenever it decides that the player should stop. That'll be intensely annoying to the player, having their ship start turning every time they take their fingers off the controls.

But with that said, the code to do so (say, for AI-controlled ships) would basically consist of a two-stage process; first the ship would try to turn to face away from its direction of travel. And once it's facing far enough away from its direction-of-travel, it thrusts to counteract its velocity, thrusting harder the more directly away from its direction of travel it might be. Commented pseudocode (which assumes that angles are expressed in radians) follows:

```
float pi = 3.141593;
float two_pi = pi * 2.0;
float half_pi = pi / 2.0;

void do_stop()
{
    // These are the values which we'll calculate.  We can then
    // use these values as if they were controller inputs.

    outval float steer, thrust;

    float angle_of_travel = atan2f(object.dy,object.dx);
    float angle_of_desired_braking = atan2f(-object.dy,-object.dx);
    float angle_of_facing = object.r;

    // Now calculate how many radians between the direction we're
    // currently facing and the direction we want to face for braking.

    float delta_angle = angle_of_desired_braking - angle_of_facing;

    // now normalise delta_angle back into [-pi .. pi], since the
    // above subtraction could have resulted in a value anywhere
    // in [-two_pi .. two_pi].

    delta_angle = fmod(delta_angle, two_pi) - pi;

    // use a multiplication factor to control steering strength.

    const float c_steering_sensitivity = 0.5;
    steer = clamp( delta_angle * c_steering_sensitivity, -1.0, 1.0 );

    // Note that if you have rotational inertia, you'll need to
    // further modify the steering value here, to try to slow down
    // the rotation rate as you approach the desired orientation.
    // The sample code for this question doesn't imply the presence
    // of rotational inertia, so I'm leaving that out of this code.

    // Now if we're reasonably close to pointing the right
    // direction, let's start thrusting.  c_thrust_threshold
    // states how close to correctly-aimed we need to be before
    // we'll start thrusting.

    const float c_thrust_threshold = half_pi;

    if ( fabs(delta_angle) <  c_thrust_threshold )
    {
        // modulate how hard we thrust based on how close we
        // are to pointing in the correct direction.

        thrust = 1.0 - fabs(delta_angle / c_thrust_threshold);
    }
    else
    {
        // don't thrust if we aren't pointing close enough
        // to the desired direction for slowing down.

        thrust = 0.0;
    }
}

```

# Answer
> 0 votes
If I could get it, the matter is that when you press the button, the speed of the object starts decreasing until it stops. You wantt to create a "break distance" (a distance between the X,Y place of pressing the button and the X,Y place of the place where the object stops) to create some kind of realistic breaking.

Don't really get the stuff doing with degrees, though.

So here's my suggestion for solving this problem: simply create a function (let's call it `stopMoving` as you did too) that runs an iteration that closes `dx` and `dy` to 0, and call it `love.update`.

Something like `for i = object.dx, 0, -1 do` in case of `dx>0` and same code **without** `-1` in case of `dx<0`. And same for `dy`.

If you want to be precise, try to iterate with the greatest common divisor of x and y. `-1/+1` is also a common divisor for any whole x and y, but that may result a very small speed decreasing.

All above are just ideas, but may be worth a try. Good luck!

# Answer
> -1 votes
The problem you're running into is the fact that when your player has stopped, there's no angle to work with so the game can't know which way to move backwards.

You either need to add one more variable that keeps track of the angle your `dx`/`dy` variables are on or two more variables to store `dx`/`dy`, leaving them alone when your real `dx`/`dy` variables don't change (and they can be safely left when their *magnitude* alone changes), but updating them when their *direction* changes.
(I think it would suffice to keep your "backup" `dx`/`dy` variables updated everywhere else save for your `stopMoving()` function)

---
Tags: lua, love2d
---


# Question
Title: Architecture - how to refer to skills/abilities internally within code?
I have about 60 skills within my game, which are loaded from a `JSON` file. Each skill is a subclass of a skill object and has attributes like range, cost, target type, etc. Currently each skill has an integer index to identify the skill. Warrior skills begin at 100, wizard at 200, rogue at 300, etc.

Now I'm at a point where I'm implementing the mechanics of what these skills actually do, I have created an enumerated type with 60 integers corresponding to the indices from within a JSON file. And what I have right now is a `switch` statement with 60 cases:

```
enum SkillsEnum
{
    sPowerAttack = 100,
//59 more enums with skill names
}

-(void)doSkillActionWithTarget:(CharacterModel*)target
{
    DLog(@"Skill activated");

    switch (self.skillIndex) {
        case sPowerAttack:
        {
            //apply skill effect here
            break;
        }
     //59 more skills
     }
}

```

I'm working in Objective-C, an object oriented language and am interested **if there's a better or more flexible to refer to skills within the game engine?**

In other words, would there be any benefit from creating more specialized separate class hierarchies for skills, or passing them around as Maps/Dictionaries?

# Answer
> 2 votes
General advice is to start with the switch statement.

At some point you may notice that you're writing a lot of very similar code in different 'case' blocks within the switch statement. If and when you notice that, that's the time to refactor the code so that those similar cases can be coalesced into a single block.

Until then, go with the switch statement. It will get you back to coding your game more quickly than trying to do something clever at this point.

# Answer
> 2 votes
One alternative that avoids lengthy switch statements all over the program would be to define inside your Skill interface additional components that define its behavior. These components would be implementing an interface as well.

For example, all skills might contain an attack behavior, which could look like:

```
IAttackBehavior attackBehavior;

```

Creating an actual instance to put inside the `attackBehavior` can be done via a factory method, for example:

```
attackBehavior = attackBehaviorFactory::createAttack( /* relevant parameters here */ );

```

The parameters can be supplied by a JSON file as well. You would probably see some switch statements inside this factory method, but they would be contained to one place.

Once your `attackBehavior` is implemented, you could call it with:

```
mySkill.attack(target); // calls mySkill::attackBehavior(target)

```

I'm not sure if this answers your question perfectly, so let me know if you have any questions.

---
Tags: architecture, objective-c
---


# Question
Title: Radiometric quantities and time in rendering
Often in papers people use various radiometric quantities, mostly radiant flux, radiant intensity, radiance and irradiance.

It seems to me that all of these quantities are dependent on time. For example, radiant flux is defined as the amount of radiant energy per span of time (emitted by a light source). The other quantities contain radiant flux in some measure so they seem to depend on time as well.

Yet when reading papers, people don't go into time at all. For example, some papers say "the radiant flux diffusely reflected by this area of the surface is x" and then they go on to explain that x is just light\_colored\_intensity * surface\_color or something (depending on the illumination model used, of course), not factoring in any kind of time at all.

Is this because the time frames observed are assumed to be 1 second? Is the time factored out somewhere (perhaps when defining the light intensity, which may be defined as radiant flux)? What am I misunderstanding here?

# Answer
> 2 votes
Time is involved in radiometric quantities fundamentally because light is always moving, flowing through space. It's like describing traffic on a road - the relevant quantity is usually not the number of cars on the road, but number of cars that pass a given point per unit time. Or think of water flowing through a pipe, which you'd measure in volume per unit time. Light is energy flowing through space and gets measured in the form of power (watts), which is energy per unit time.

Suppose you look at a "static" scene - no lights or objects are moving, no pixel values are changing on screen. The light in the scene is not static; it's just in radiative equilibrium. Light energy is constantly being emitted from all the light sources in the scene, and constantly being reflected, scattered, and absorbed by all the surfaces and media in the scene. What is static is the rate of each of these energy flows, i.e. their power. In any given region, the power of incoming light equals the power of outgoing and absorbed light, so the amount of light is not changing over time. This includes your eyeballs or your video camera - you see a steady image because the amount of light arriving per unit time is constant.

When you switch the lights on in a room, it takes some time for it to come to this equilibrium, but that happens in just microseconds due to the speed of light. So in rendering we typically assume the scene is always in radiative equilibrium - even if the scene is changing, it's usually not changing significantly on the scale of microseconds. Rendering algorithms try to calculate that equilibrium, so they naturally work in units of the flow of energy (power) rather than energy itself.

# Answer
> 2 votes
Yes, all these radiometric quantities should be considered per unit of time. But no, they are not summed over 1 second. In theory, the **radiant flux should be integrated over the whole frame length** (*e.g.* 1/60 seconds) in order to compute the **radiant energy** sent to the viewer’s eye during that frame length. However, such an integration is usually too complex to compute accurately.

The most common approximation is to simulate a camera with an infinitely fast shutter speed, meaning the whole scene is static. In this case, there is no need to integrate the flux: it is considered constant (that’s why your papers use intensity and flux instead of energy). Then if you want to know the approximate energy received during the frame, you simply multiply the final flux by the frame length.

Another method is to perform multiple renderings of the frame, at regularly spaced intervals, and compute their average. This leads to the effect known as motion blur. Mathematically, it is akin to integrating the radiant flux using the rectangle method.

In the end, it does not matter *much* whether the data stored in an image is the radiant flux or the radiant energy. But I think it’s more mathematically rigourous to:

* perform light computations for a single, instantaneous frame, using flux and intensity values (*i.e.* per unit of time)
* consider the data in the final image is an energy value, because when *e.g.* motion blur has been applied, the instantaneity of the frame is lost.

---
Tags: physics, rendering
---


# Question
Title: How to rotate model, around its own center?
I have a 3d Model that it wasn't made from the origin of the 3d program, lets say that it was built at `(100, 100, 100)`, I know how to rotate a model, but around the model origin point, `(0, 0, 0)`, now how can I rotate the model around its own center? In this example the `(100, 100, 100)` so that instead of going around the origin point (like the earth around the sun) it will rotate around its own center (like the earth rotation around its center) so I can create an effect of the earth rotating around the sun and rotating around its own center.

Here's my code:

```
modelTransform = (Matrix.CreateScale(3f, 3f, 3f) * Matrix.CreateRotationX(rotation) * Matrix.CreateTranslation(myModel.Position));
effect.World = transform[mesh.ParentBone.Index] * modelTransform;

```

with this code my earth is rotating around the sun, but I have no idea how to rotate it around its own center.

# Answer
> 5 votes
Translate the model back to the origin, rotate it, then translate it back. In XNA, you can do something like that with the following:

```
public Vector2 RotateAboutOrigin(Vector2 point, Vector2 origin, float rotation)
{
    return Vector2.Transform(point - origin, Matrix.CreateRotationZ(rotation)) + Origin;
}

```

Choose `CreateRotationY` or `CreateRotationZ` depending on what you're using for "up".

That will translate the object to back to the origin, rotate it, then translate it back.

---
Tags: xna, c#, 3d
---


# Question
Title: What are the pros. and cons. of different representations a custom geometry format for a mobile based engine?
I am trying to create 3D model importer for my mobile based engine.

These are what I am considering:

1. Convert .obj file to text based structure like JSON or custom.

* So, basically, convert .obj file to structure to fit my engine, so, it could be a little bit faster for loading time.
    * **Pros**: Easy, and cross platform.
    * **Cons**: This is text file, and maybe could be slow for parsing and string manipulation?
2. Convert .obj file to Binary that fits to my engine.

* Use serialization and save with specific structure to binary format
    * **Pros**: Faster
    * **Cons**: It may painful for multi-platform like Java and Objective-c?
3. Convert .obj file to .java or .h(.m) file, and attach to source code.

* Export .obj file as .java and .h(.m), so I can use inside of code
    * **Pros**: Easy and Faster(?)
    * **Cons**: (?)

First time, I didn't know about #3 method, but I found some article that people doing this for simple small game. And my game is also small too, so I am considering more #3 method.

Which method is popular and is there more pros and cons ?

# Answer
First of all I think it's best to build a converter from your source format to your custom format. I suggest you use Assimp library because it supports multiple types of files, this way you can build a converter that uses Assimp to read multiple file formats and convert it to your file format without the need to write multiple converters for each file format, Assimpt will save you alot of time.

Now regarding your custom file formats, it really depends on your requirements:

> Convert .obj file to String based structure like JSON or custom.

* It is easy to read and manipulate (This is more useful in testing and debugging).
* String files are usually slower to parse, on mobiles you usually need every bit of processing power (I assume but I don't have on-hand experience with it).
* You will usually end up with large file sizes this is bad especially on Mobiles where storage is usually limited.

In general I don't recommend this for mobile platforms, could be only for testing, if you are going to go that way, consider a compressed XML or JSON this way you will save alot of space. But I don't know if performance will be good, you need to test and profile.

> Convert .obj file to Binary that fits to my engine.

* This is good for performance and size.
* Will be hard to edit manually
* You need to make sure you handle endianess correctly on multiple platforms

> Convert .obj file to .java or .h(.m) file, and attach to source code.

Never do this, unless you are building a basic prototype or a small test case, where you don't need to go through the trouble of writing a custom parser (but eventually you will need to write one).

This is bad because it couples your input data to your source code, so if you want to change anything you need to recompile.
> 3 votes

# Answer
concept3d gave a good reason not to use option *3. Convert .obj file to .java or .h(.m) file, and attach to source code.* Another reason is that Java doesn't support this approach well, because Java bytecode format cannot store arbitrary byte arrays. If you have `private static byte[] DATA = {0x50, 0x2F, ...};` in your class, the compiler generates code for a static initializer that allocates the byte array and assigns each element of the array separately.

The only non-primitive data that .class files can hold is UTF8 encoded strings. It is possible to abuse this to hold your data in strings, but it's not pretty or efficient.
> 0 votes

---
Tags: android, ios, models, opengl-es2, mobile
---


title: Perlin Noise Variations

text:
# Question
Title: Perlin Noise Variations
Currently I'm making a voxel survival game. About a month ago I embarked on procedurally generating terrain using Perlin noise. I understand how to use and apply it for the most part. However I do not understand how to vary terrain structure. Let me say that in a way you probably can understand because "me no grammar good".

By changing frequency and amplitude I know I can change the resulting terrain, varying it from rolling hills to jagged peaks. However the end result will always be the same: either never ending hills or never ending mountains. I don't understand really how I would mix those two "terrain structures" together to get area's of hills and area's of mountains.

# Answer
> 0 votes
My suggestion would be to modify the Perlin noise parameters based either on formulae, interpolation from known points, or a (much simpler) map texture. For example, you could modify the amount you scale each octave, and/or the amount you distort the pseudo-random function.

As an example of each of the three approaches:

1. Apply a simple function: Increase the amplitude of the higher frequencies and/or the Perlin noise function as a whole by the x co-ordinate to have smooth hills going to mountains.
2. Interpolation: Choose known points that should have certain properties, e.g. hilly/smooth/low/hi, set parameters appropriately at those points, then interpolate the parameters between them using some sort of distance function from the nearest neighbours or a spline.
3. Map: Set the exact parameters to use for every point on the map, and then generate. Easier than it sounds, this "map" would likely have simple blocks of colour or smooth gradients that even a developer can draw. Still allows variation by changing the pseudo-random seed for the Perlin noise.

# Answer
> 0 votes
The way I(And I believe many others) do it is to have not only one noise generator, but multiple ones, configured differently, and then interpolate between them based on some value(perhaps chunk type, perhaps just another noise function). Also generating a specific terrain type is more feasible by combining multiple noises too.

The website of libnoise has some nice information about all this, and also about the various noise generation and mixing techniques.

Some basic generators are:

* Perlin
* Simplex
* Ridged Multi
* Constant
* Gabor Noise (less common)
* Voronoi (less common)

Some manipulators:

* Add
* Multiply
* Scale

Some interpolators/selectors:

* Select( if control \> 0.5 A else B )
* Blend ( blend A with B based on control )

---
Tags: procedural-generation, terrain, lua, perlin-noise
---


# Question
Title: How do I create curved ground in a 2D runner game?
If I use tiled based map I can have only rectangular objects.

What is a strategy for creating slanted or curved ground in that case? Should I use a tile-based map, or should I define corner points in the map and create the ground programmatically?

# Answer
> 4 votes
There is an easy way to fake this in a 2D tile game. First you create a tile that contains the curved shape (using alpha 0 for the "empty space"). Then for each **pixel** on the **x-axis** you store the height of the highest point that has a non-zero alpha. While your character is over one of these curved tiles, your collision routine then checks the character's **x-axis position relative to the tile** and uses the height value you stored to determine the appropriate **y-axis** position for the character. You could also store an **angle** for each x-axis unit if you want your character to rotate based on the current slope.

This implementation is very easy to do and runs very fast since your calculations are done at design time (or at load time if you choose to do it in code) and the collision detection only requires a look-up.

Here is a (very simple) example image:

At **x=5** the height is **10 pixels** (so y=10), and at **x=15** the height is **30 pixels** (you should store this for every value of **x**).
Also, because of the (mostly) even slope the angle is about 45 degrees for ALL values of x - this will obviously vary based on the type of tiles you have, and you can easily calculate it, or just approximate it visually.

**EDIT:** As requested, some basic code:

Here it is important that both the `player` and `tile` positions are in the same "space" (ex. both are in world space) so that the array index look-up value results in a value in the range `[tile.left, tile.right]`. Also, the test for whether the player is over a tile should probably be something more scalable in a real implementation, but this will do to illustrate the idea.

```
// check if player is within the bounds of the tile and find their height
if ( player.x >= tile.left && player.x <= tile.right &&
     player.y >= tile.top && player.y <= tile.bottom )  {
   player.y = LookupY[player.x - tile.left];  // Set Player Y from X Relative to Tile
}

```

Generating the `LookupY` table will be highly dependent on the API used for graphics, so I will leave the technical details out, but the basic algorithm would look something as follows:

```
LookupY[x-axis size];   // Array sized to each x-axis pixel
for ( x = each x-axis pixel )  {  // Loop for each x-axis pixel (left->right)
    for ( y = each y-axis pixel )  {  // Loop for each y-axis pixel (top->bottom)
       /* extract the pixel's ALPHA value here (API specific code) */
       if ( alpha != 0 )  {  // Stop when first non-zero alpha is found
          LookupY[x] = TileHeight - y;  // Calculate Height from Bottom of Texture
          break;  // Stop testing on y-axis; height is found
       }
    }
}

```

This is a very basic implementation and since the question does not specify any specific language and/or API I really can't elaborate much more, but feel free to ask if anything is still unclear.

# Answer
> 0 votes
I would suggest that you have a look at tile collision detection. You could easily have a slope shaped tile and make the bounding box triangle shaped.Its true that you can only have rectangle shaped objects as far as graphics go but for collisions depending how you write it you could have any shape.

If you haven't really looked into collision detection (and i don't blame you, its not the first thing you think of in a tile game) then i found a good article on it for Java using quad trees.

http://gamedev.tutsplus.com/tutorials/implementation/quick-tip-use-quadtrees-to-detect-likely-collisions-in-2d-space/

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


title: Tennis game algorithm and maths

text:
# Question
Title: Tennis game algorithm and maths
Tennis courts are real dimensions and game is 3D

Ball has position (x,y,z), speed(vx,vy,vz) and acceleration (ax,ay,az)

Game has 30 fps and on each update (1/30sec) it has these properties

```
vx +=ax;
vy +=ay;
vz +=az;

ball.x += vx;
ball.y += vy;
ball.z += vz;

function hitBall(destinationx, destinationy=0, destinationz) {
    // calculate vx, vy, vz, so ball imapcts  the point (destinationX, 0, destinationZ)
    // destinationY = 0 = bounce on floor
    vx = ....
    vy = ....
    vz = ....
// I guess this problem has infinite solution, so we must intersect with 1 point
// intersection line is (x,1,12)
// 12 is middle of the tennis court and 1 is 1 metter above the ground.
// ball passes there 1 meter above the ground.

}

```

Any clue on how to resolve that math problem ?

regards

Google doc : https://docs.google.com/presentation/d/1EiUYpalDXlJUgjg8aIxLiWENgZJW7fnH4bGHsj1jb9I/edit?usp=sharing

# Answer
So what I understand from you description is that you have a destination point and you want to shoot a projectile so it hits that point, in other words to reach specific coordinates.

Now this can be done using basic projectile equations.

The following equation gives the initial angle that is needed to hit specific coordinate.

Where:

* g: the gravitational acceleration—usually taken to be 9.81 m/s2 near the Earth's surface
* θ: the angle at which the projectile is launched
* v: the velocity at which the projectile is launched
* y0: the initial height of the projectile
* d: the total horizontal distance traveled by the projectile

Now the problem is that the distance depends on the initial velocity vector (direction, and speed). So in order to calculate this using the above equation you need to fix one of them. So you assume you are shooting at fixed angle (e.g.45 degree), and then calculate the speed of the vector or vice versa.
> 2 votes

---
Tags: algorithm, intersection, mathematics
---


# Question
Title: How to implement expiring and self-refreshing buffs in an RPG?
I have a turn based RPG with buff system where buffs are always on, and the player has an option to cancel them at any time.

An exception to this system is buffs like **"Effect lasts until the end of this turn"** or **"Absorbs first x points of damage"**. And I'm thinking of a good way to implement them.

Currently I have these types of effects in game:

```
enum {
    kBuffOnTurnStart,
    kBuffOnAttack,
    kBuffOnEffect,
    kBuffAlwaysOn
};

```

I think that I can implement the recharging or expiring buffs as two part buffs - one is the "always on" portion and another a worker portion that will do it's action on turn start. For example, a shield buff has 8 points of damage it can absorb. After it does so, it can no longer absorb damage. At the start of next round the "worker" buff/action would find the linked shield buff and recharge it.

Alternatively, an "always on" buff has some action or behavior associated with it, which is executed on turn start.

**What is a simple and clean way to implement auto refreshing or expiring buffs?**

# Answer
Treat the buffs as components. So you have a "always on" buff object, and you add it to your player. Each turn you fire an OnBeginTurn event to each buff, and they each manage their own behavior.

Examples: A buff that needs to expire will have an internal ticker that it will increment and remove itself when necessary. A buff that is always on will apply some effect to its parent player. A buff that triggers on an attack could receive an OnHandleAttack event, and apply some effect to the player or any sub-components of that player.

Of course I'm just basing this off my current component architecture, but the concept translates fairly easily.
> 3 votes

---
Tags: architecture
---


# Question
Title: Using latest TiledMap, how do you get a specific tile from x and y index?
Seems basic enough, but I can't seem to find the answer: I am trying to implement collission detecton and for that I need the properties of the tile the player is currently entering. I am using `gdx.maps.tiles.TiledMap`, which does not have a `getCell(int x, int y)` like the older TileMap had. Any help on this specific issue or just some general advice on how to do this will be much appreciated!

# Answer
With the new libGDX tiled maps implementation, you need to request the concerned layer before being able to request for a particular tile.

So:

```
TiledMapTileLayer layer = (TiledMapTileLayer) currentMap.getLayers().get("layer_id");

```

And then i can do:

```
layer.getCell(x, y);

```

Which will return a `Cell` instance.

Here is the new documentation about tile maps: https://github.com/libgdx/libgdx/wiki/Tile-maps
> 4 votes

---
Tags: collision-detection, libgdx, tilemap
---


title: Does Steam support Shared Libraries?

text:
# Question
Title: Does Steam support Shared Libraries?
I know steam has nothing to do with whether the game has dynamic libraries or not, but a lot of games should be using the **same** dynamic libraries.

Does Steam currently have a way to **reuse 1 dynamic library across multiple games**, without creating copies of said library of course? I've taken a look into my own Steam library by taking 2 Source games and wild picking a few dynamic libraries and checking if the other one has them. I didn't really find a lot of matches, but I did find matches and I did find similar libraries. (`valve_bink.dll` and `binkw32` for example)

# Answer
It's not something you should really *want* to do. Consider what Steam has to do with DirectX. Getting into the mess of shared dynamic libraries isn't likely to be worth the trouble.

I haven't seen any scenarios where Steam games will share DLLs between each other. As Grimshaw said in his comment, it adds a lot of complexity for nothing other than saving a little disk space.
> 5 votes

---
Tags: steam
---


title: DirectX error with older XP systems

text:
# Question
Title: DirectX error with older XP systems
I am a blind programmer, working on an audio game for the blind. I am using SlimDX, and it has been tested on dozens of systems from XP to Win 8.1. My code works on most systems just fine, but I am getting the following error at runtime on a handful of older XP systems:

> vupgraderacer.wav SlimDX.DirectSound.DirectSoundException:
>
> DSERR\_INVALIDCALL: This call is not valid for the current state of this object (-2005401550)
>
> ```
> at SlimDX.Result.Throw[T](Object dataKey, Object dataValue)
> at SlimDX.Result.Record[T](Int32 hr, Boolean failed, Object dataKey, Object dataValue)
> at SlimDX.DirectSound.SecondarySoundBuffer..ctor(DirectSound device, SoundBufferDescription description)
> at RR.Sound..ctor(String fileName)
>
> ```

The same error is repeated for each sound it is trying to use. Here is the code I am using to setup the DS device:

> dsDevice = New SlimDX.DirectSound.DirectSound
>
> dsDevice.SetCooperativeLevel(OGw.Handle, SlimDX.DirectSound.CooperativeLevel.Normal)

I realize there are other flags that can be set, but this basic setup has worked well thus far, minus the older XP systems. This is my first post, so hope I am entering it properly, if not, please let me know, it is sometimes difficult to tell where you are or should be with a screenreader on forums.

# Answer
> 1 votes
You should check the result of SetCooperativeLevel().

According to the documentation of the DirectSound8 version, these are the possible return values:

* DS\_OK DSERR\_ALLOCATED
* DSERR\_INVALIDPARAM
* DSERR\_UNINITIALIZED
* DSERR\_UNSUPPORTED

Find out which one you get first. Maybe you just forgot to initialize the sound device?

Also, in the remarks section it says: "Do not call this method if any buffers are locked."

Docs: http://msdn.microsoft.com/en-us/library/windows/desktop/microsoft.directx\_sdk.idirectsound8.idirectsound8.setcooperativelevel%28v=vs.85%29.aspx

---
Tags: directx, sound, slimdx
---


# Question
Title: Should I delete the textures I use in OpenGL ES 2 (Android)?
Say I have a skybox and the user can choose out of 2 sets of 6 textures (one for each face of the cube) to use on that skybox. For example if user selects set A, I load the textures (`GLES20.glGenTextures` etc) and put them on the cube.

However, if the user then selects set B, should I delete the textures I previously created? Or what's the standard way of dealing with textures that are (at least temporarily) no longer needed? Also, is texture deletion an expensive operation?

My app will include other scenarios similar to the above, so I might end up having 10-15 (or more) textures in memory with only a few of them displayed, therefore I expect deleting them is the way to go.

# Answer
I know that in AndEngine (which is also for Android) that you can load/unload resources like textures whener you want.

When you're in this kind of situation be sure to unload ALL textures you don't need or aren't using because this would otherwise take up a lot of memory (if you're doing this with multiple textures).

If you're making a mobile game be sure that you always only load what you need and unload what you don't. It might take some practice to get it right. A game I made had a Resource manager where we could load the resources per scene of the game. That might be a good solution for you too.

I hope this helps you out.
> 0 votes

---
Tags: textures, opengl-es2
---