title: LWJGL Camera Rotation Issues

text:
# Question
Title: LWJGL Camera Rotation Issues
I am quite new to LWJGL and OpenGL and I am trying to create an FPS camera. I had no problem with 2D stuff, so I decided to step things up and try and make some things in 3D. I have this 3D camera which I am working on, but for some reason my rotation doesn't seem to be working. The pitch and the yaw values are always 0.

Here is my code:

My3DGame.java

```
import static org.lwjgl.opengl.GL11.*;

import org.lwjgl.LWJGLException;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.util.glu.GLU;

public class My3DGame {

private static My3DGame instance;

private final int DISPLAY_WIDTH = 840;
private final int DISPLAY_HEIGHT = 480;
private final String DISPLAY_TITLE = "My 3D Game";

private final int FPS_CAP = 60;

public My3DGame() {
    try {
        Display.setDisplayMode(new DisplayMode(DISPLAY_WIDTH, DISPLAY_HEIGHT));
        Display.setTitle(DISPLAY_TITLE);
        Display.create();
    } catch (LWJGLException e) {
        e.printStackTrace();
    }

    init();
    initGL();

    while (!Display.isCloseRequested()) {
        render();
        update();
    }

    Display.destroy();
}

Camera camera;

private void init() {
    try {
        Mouse.create();
        Keyboard.create();
    } catch (LWJGLException e) {
        e.printStackTrace();
    }

    camera = new Camera(0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.15f, 2.4f);
    Mouse.setGrabbed(true);
}

private void initGL() {
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    GLU.gluPerspective(45.0f, ((float) DISPLAY_WIDTH) / ((float) DISPLAY_HEIGHT), 3.2f, 2.0f);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

private void update() {

    if (Keyboard.isKeyDown(Keyboard.KEY_ESCAPE) && Mouse.isGrabbed())
        Mouse.setGrabbed(false);

    if (Mouse.isButtonDown(0) && !Mouse.isGrabbed())
        Mouse.setGrabbed(true);

    if (!Mouse.isGrabbed())
        return;

    Mouse.setCursorPosition(DISPLAY_WIDTH / 2, DISPLAY_HEIGHT / 2);

    camera.update();
}

private void render() {
    glClear(GL_COLOR_BUFFER_BIT);

    glBegin(GL_QUADS);
    {
        glColor4f(3.2f, 23.1f, 0.2f, 1.0f);
        glVertex3f(100, 200, 1);
        glVertex3f(200, 200, 1);
        glVertex3f(200, 100, 1);
        glVertex3f(100, 100, 1);
    }
    glEnd();

    Display.update();
    Display.sync(FPS_CAP);
}

public static void main(String[] args) {
    instance = new My3DGame();
}

public static My3DGame getInstance() {
    return instance;
}

}

```

Camera.java

```
import static org.lwjgl.opengl.GL11.glLoadIdentity;
import static org.lwjgl.opengl.GL11.glRotatef;
import static org.lwjgl.opengl.GL11.glTranslatef;

import org.lwjgl.Sys;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.util.vector.Vector3f;

public class Camera {

private Vector3f position = null;
private float pitch = 0.0f;
private float yaw = 0.0f;

private float sensitivity = 0.0f;
private float moveSpeed = 0.0f;

public Camera(float x, float y, float z, float pitch, float yaw, float sensitivity, float moveSpeed) {
    position = new Vector3f(x, y, z);
    this.pitch = pitch;
    this.yaw = yaw;
    this.moveSpeed = moveSpeed;
}

public Camera() {

}

public void pitch(float amount) {
    pitch += amount;
}

public void yaw(float amount) {
    yaw += amount;
}

public void walkForward(float distance) {
    position.x -= distance * (float) Math.sin(Math.toRadians(yaw));
    position.z += distance * (float) Math.cos(Math.toRadians(yaw));
}

public void walkBackwards(float distance) {
    position.x += distance * (float) Math.sin(Math.toRadians(yaw));
    position.z -= distance * (float) Math.cos(Math.toRadians(yaw));
}

public void strafeLeft(float distance) {
    position.x -= distance * (float) Math.sin(Math.toRadians(yaw - 90));
    position.z += distance * (float) Math.cos(Math.toRadians(yaw - 90));
}

public void strafeRight(float distance) {
    position.x -= distance * (float) Math.sin(Math.toRadians(yaw + 90));
    position.z += distance * (float) Math.cos(Math.toRadians(yaw + 90));
}

float dx = 0.0f;
float dy = 0.0f;
float dt = 0.0f;
long lastTime = 0L;
long time = 0L;

public void update() {

    time = Sys.getTime();
    dt = (time - lastTime) / 1000.0f;
    lastTime = time;

    dx = Mouse.getDX();
    dy = Mouse.getDY();

    yaw(dx * sensitivity);
    pitch(dy * sensitivity);

    System.out.println("DT: " + dt);

    if (Keyboard.isKeyDown(Keyboard.KEY_W)) // Move forward
    {
        walkForward(moveSpeed * dt);
    }
    if (Keyboard.isKeyDown(Keyboard.KEY_S)) // Move backwards
    {
        walkBackwards(moveSpeed * dt);
    }
    if (Keyboard.isKeyDown(Keyboard.KEY_A)) // Strafe left
    {
        strafeLeft(moveSpeed * dt);
    }
    if (Keyboard.isKeyDown(Keyboard.KEY_D)) // Strafe right
    {
        strafeRight(moveSpeed * dt);
    }

    System.out.println("Position: " + position.toString() + ", Pitch: " + pitch + ", Yaw: " + yaw);

    glLoadIdentity();

    glRotatef(pitch, 1.0f, 0.0f, 0.0f);
    glRotatef(yaw, 0.0f, 1.0f, 0.0f);
    glTranslatef(position.x, position.y, position.z);
}

```

}

# Answer
> 0 votes
I have fixed this now. I forgot to set the mouse sensitivity value in the constructor of Camera, which meant the sensitivity float was equal to 0.

---
Tags: java, 3d, camera, rotation, lwjgl
---


# Question
Title: How can I implement the ability to combine items into new items?
I would like to understand how to be able to combine items in a player's inventory, producing new items. For example, the scenario I have in mind is that the user picks up three key fragments and combines them to create a complete key.

What properties should I model on my item classes to support this behavior, and what should my basic algorithms be?

# Answer
I would expand a bit on Philipp's answer. This is not a very efficient solution, but unless you have millions of items, it should not be too bad.

```
class Item {
  string Name                    // Item name (identifier)
  map(string, string) Properties // Properties of the item, whatever
  string[] Requirements          //Names of items required for creation
}

Item[] allItems                  // Array of all item templates in game

Item CombineItems(Item[] items)
{
    for item in allItems
    { // Loop through all possible items
        if (item.Requirements.Len() != items.Len())
            continue // Skip items with different number of requirements
        bool found = true
        for reqItem in items
        { // Loop through the items we wish to combine
            if (reqItem.Name not in item.Requirements)
            {
                found = false
                break
            }
        }
        if (found == true)
            return item  // We have found a match, create the item
     }
     return null // Not possible to combine!
}

```

This is a very rigid way of doing things, but should work (wrote this quickly so it probably has some bugs, but you get the idea). **EDIT for clarification**: The code is not C#, but rather pseudo code, but the *idea* should work.

If the function returns something else than null, you know that the merge has succeeded, and you can delete the "ingredients".

**Clarification:** Assume we have a number of template items. These items do not exist in the game world, but are used to create new items to the game world. The array *allItems* contains these templates. Each item has a name, e.g. "nails", "baseball bat". Each item also has a requirement on what items are needed to create it. So a "nailbat" requires \["nails","baseball bat"\].

When we wish to combine items, we call the function **CombineItems** with one argument, an array of items we wish to combine.

The function then searches through the array of template items. For each template item we check that the number required items match the number of items we wish to combine. If it does not match, continue with the next template.

Next, we check that the name of each item we wish to combine is in the requirements for the template item. To create a "nailbat", we search each template for the requirements "nails" and "baseball bat". If we get a match, we can combine the items, and return a new instance of the combined item!

Think of it as a restaurant menu: we have different ingredients, and with a handful of different ingredients we wish to see what dish from the menu we can make (if any at all).
> 2 votes

# Answer
A `CombineItems` method needs to do these things in pseudocode:

```
check if the items can be combined. when yes:
    remove the used items
    add the new item
when they can not be combined:
    throw an exception (which can obtionally carry the reason why)

```

The interesting part from the software architecture point of view is where to check which items can be combined with which. You basically have two options here:

1. You have a fixed list of all allowed combinations in your InventorySystem class and check if the provided items have a corresponding entry
2. Each InventoryItem would have its own list of other items it can be combined with. You could then add a method `public InventoryItem CombineWith(InventoryItem other)` to your InventoryItem class. This method would return the resulting item on a positive match or throw the exception when there is no match.
> 1 votes

---
Tags: c#
---


# Question
Title: What is the term for the level progression paradigm in Bejeweled?
Looking at the various level progression paradigms for my puzzle game, I decided to rule out the common ones such as 3-star per level, linear campaign-like story, etc. I like the idea of Bejeweled's classic mode where the player simply keeps on going.

What exactly is this paradigm called? I can't find any write-ups on it so I can't quite tell what its structure is like. Is it infinite? Does the difficultly increase with each level in some shape, way or form (more likely to get "No moves")?

# Answer
TVTropes used to call this the "Kobayashi Mario", but now they just call it an Endless Game. The old name was a reference to the "Kobayashi Maru" test in the Star Trek universe. This is a test all starfleet cadetes have to take and which can not be completed successfully. The candidate can only fail, and the actual purpose of the test is to see how they react to a hopeless situation.

Games with no win condition which get harder and harder the longer you play are just like this. You can't win, the challenge is to see how long you can hold out without losing.
> 4 votes

# Answer
I don't believe there is a specific term for it (but rather there are many that would likely apply); the gameplay is simply unending (infinite) and the presumably scales in some simple fashion so as to become more challenging over time, but never so far as to render a level technically impossible to complete.

(Unless it does render levels impossible to complete, I've never played the game long enough to tell.)
> 0 votes

# Answer
How bejeweled does it doesn't really matter. It only depends on how you want to implement it for your game. Call it what you like: infinite, continuous, unending and so on.

Increasing the difficulty is up to you. If you want to do that is a design decision you need to make on your own.
> -1 votes

---
Tags: game-design, level-design, progression
---


# Question
Title: Does `SetResourceArray` copy the data into the GPU?
I am trying to create multiple textures, and only several of them change every few frames. I don't want to have to copy in the whole array via `SetResourceArray` for just a few textures that change, which brings me to my quesiton: Does `SetResourceArray` copy the data into the GPU?

# Answer
It will most likely call a flush and then copy the stuff to the gpu since you are updating textures. I Cant say that IT IS like this, since DX never gives details about what their drivers do. But since it is the Effect framework it might also do so that it calls the PSSetShaderResourcer(), and then sets all of them at the same time.

But if you want to update a pair of textures each frame, consider having a smaller buffer for those explicitly. Otherwise calling UpdateResource per each might give you a desired effect for less performance loss.
> 2 votes

---
Tags: c++, textures, directx, shaders
---


title: Changing the maxDepth of viewport

text:
# Question
Title: Changing the maxDepth of viewport
Whenever I change the `maxDepth` of the `viewport` from `1.0` to say `300.0f` (just for kicks), everything on my screen disappears. Why is that? Is there anywhere else I have to account for this change in depth i.e. rasterizer?

PS: I tried values like `2.0` and `3.0` and still nothing.

Additionally, does this mean that the `projectionMatrix` is limiting my Z values to between `0` and `1.0` if the `viewport#maxDepth = 1.0`?

# Answer
The Max depth in a view port is 1, and cant be changed after that. And if the desired effect is to change the max "view distance" this should be done via a projection matrix. The Depth usage is very restrict and limited in directx where the driver takes care of most of the usage of it. so modifying it to own values will have serious consequences.

This link to msdn explenation of the transformation pipeline is good and will explain most everything about why it handles the depth for you.MSDN LINK
> 1 votes

---
Tags: c++, directx, depth-buffer, viewport
---


# Question
Title: How can I adapt "random walk" generation to very large maps?
The random (or drunkard's) walk is a great, simple algorithm that can generate very organic-looking maps, such as this:

Unfortunately it seems to have poor scalability, making it unsuitable for generating large maps in a reasonable amount of time. For example, a test I performed looking at how many iterations are required to generate a desired range for a 1D random walk yielded what looked like quadratic complexity:

```
Range | Iterations
------+-----------
10    | 81
100   | 7309
1000  | 585352
10000 | 30656784

```

For higher-dimension walks I imagine this would be even worse.

How can improve the efficiency of random walk, whilst preserving the overall look of the result, for large maps? I'm hoping for a solution with sub-quadratic complexity.

# Answer
"Divide and conquer" is a good first step towards reducing the complexity of any such algorithm.

Use some heuristics based on your previous metrics gathering to define some number *n* based on the size of the map to be generated, where *n* indicates how many independent random walks to run in parallel. Choose *n* random starting locations, possibly weighted towards the center of the map to avoid the likely-hood of smashing up against the borders, and run the walks.

If you keep track of the walks only as a set of coordinate pairs you can, once the walks are complete, attach them all to eachother. There are several ways you could go about this. Two I can think of offhand are to:

* compute the bounding regions of the walk (possibly breaking a walk into multiple regions if it's total bounding region is too long in one dimension or another), consider them "rooms" and attach them using one of several typical techniques for connection rooms in Roguelike games.
* select random points within the walks, pairwise, and translate the results of one walk into the frame of the other walk at that point. Optionally rotate the translating walk by some amount.

As Nathan suggested in the comments, a hierarchical approach is also a good place to explore: use a walk that consumes chunks of your grid to define a rough layout, and after each chunk is consumed start a smaller, fine-grained walk within that chunk.
> 5 votes

# Answer
Your observation is perfectly accurate. The dependence of the map size of a random walk on the number of iterations is well known to have a power of 1/2, i.e., R~N^(1/2), and R is usually called the radius of gyration.

You could try a self-avoiding random walk, which grows "faster" R~N^(3/(d+2)), i.e., in two-dimensional d=2 it will grow with a power of 3/4. This will still take more than linear-time, but I believe this is unreachable (Best case is a 1d-linear chain, visiting every point once will still take linear time). The results will differ, because (as the name suggests), a point will only be visited once. But if your goal is simply an organic looking map, you can probably recreate a similar look by additional means. As suggested, you work out a hierarchical approach. First a self-avoiding random walk on a course grid, then replacing each point with a dense, filled structure.
> 1 votes

---
Tags: algorithm, procedural-generation
---


# Question
Title: How to compute tangent and bitangent vectors
I have a texture loaded in three.js, then passed to the shaders. In the vertex shader I compute the normal, and I save into a variable the uv vector.

```
<script id="vertexShader" type="x-shader/x-vertex">

                varying vec3 N,P;
                varying vec2 UV;

                void main() {
                    gl_Position= projectionMatrix * modelViewMatrix * vec4(position,1.0);
                    P= position;
                    N= normalMatrix * vec3(normal);
                    UV= uv;
                }
            </script>
            <script id="fragmentShader" type="x-shader/x-fragment">

                varying vec3 N,P;
                varying vec2 UV;
                uniform sampler2D texture;

                void main() {
                    gl_FragColor= texture2D(texture,UV);
                }

            </script>

```

How do I compute the T and B vectors?

# Answer
> 35 votes
First of all, for every 3D vertex there is infinite tangent and bi-tangent vectors. The below image explains why there is an infinite number of tangent spaces for each vertex, the tangent and bitangent can have any direction in the shown plane.

So in order to properly calculate the most useful1 tangent space, we want our tangent space to be aligned such that the x axis (the tangent) corresponds to the u direction in the bump map and the y axis (bitangent) corresponds to the v direction in the bump map, we should already have normal of the vertex which already corresponds to the Z direction in tangent space.

 (1) most useful because in the end we want normal vectors to be sampled from the texture

That best be explained with pictures, we want our tangent space to be aligned like `(u, v)` shown below.

Source of the image though not strictly related to computer graphics

In computer graphics developers usually use `(u,v)` also known as texture coordinates. We will assume T is the tangent and B is the bitangent, and `P0` is our target vertex, that is part of the triangle `(P0,P1,P2)`.

First remember what we wanted to do, is to calculate tangent and bitanget that:

1. T aligned with u and B aligned with v.
2. T and B lays in the plane with the vertex normal (the plane shown in the above image).

The point is we already assumed that T and B lays in the same plane and corresponds to U and V now if we can know their values we can cross product and the third vector to construct a transformation matrix from world to tangent space.

Given that we know that any 2D vector can be written as a linear combination of two independent vectors2 and since we already have the triangle points (edges), shown in the above image. We can write:

> E1 = (u1-u0)T + (v1-v0)B
>
> E2 = (u2-u0)T + (v2-v0)B

(2) actually that's is how basis matrix is derived

The above equation can be written in a matrix form,

```
| E1x E1y E1z |   | deltaU1 deltaV1 | * | Tx Ty Tz |
| E2x E2y E2z | = | deltaU2 deltaV2 |   | Bx By Bz |

```

By solving the matrixs equation we can determine T and B values we can construct a transformation matrix.

The full source code in C++

```
#include "Vector4D.h"

struct Triangle
{
    unsigned short  index[3];
};

void CalculateTangentArray(long vertexCount, const Point3D *vertex, const Vector3D *normal,
        const Point2D *texcoord, long triangleCount, const Triangle *triangle, Vector4D *tangent)
{
    Vector3D *tan1 = new Vector3D[vertexCount * 2];
    Vector3D *tan2 = tan1 + vertexCount;
    ZeroMemory(tan1, vertexCount * sizeof(Vector3D) * 2);

    for (long a = 0; a < triangleCount; a++)
    {
        long i1 = triangle->index[0];
        long i2 = triangle->index[1];
        long i3 = triangle->index[2];

        const Point3D& v1 = vertex[i1];
        const Point3D& v2 = vertex[i2];
        const Point3D& v3 = vertex[i3];

        const Point2D& w1 = texcoord[i1];
        const Point2D& w2 = texcoord[i2];
        const Point2D& w3 = texcoord[i3];

        float x1 = v2.x - v1.x;
        float x2 = v3.x - v1.x;
        float y1 = v2.y - v1.y;
        float y2 = v3.y - v1.y;
        float z1 = v2.z - v1.z;
        float z2 = v3.z - v1.z;

        float s1 = w2.x - w1.x;
        float s2 = w3.x - w1.x;
        float t1 = w2.y - w1.y;
        float t2 = w3.y - w1.y;

        float r = 1.0F / (s1 * t2 - s2 * t1);
        Vector3D sdir((t2 * x1 - t1 * x2) * r, (t2 * y1 - t1 * y2) * r,
                (t2 * z1 - t1 * z2) * r);
        Vector3D tdir((s1 * x2 - s2 * x1) * r, (s1 * y2 - s2 * y1) * r,
                (s1 * z2 - s2 * z1) * r);

        tan1[i1] += sdir;
        tan1[i2] += sdir;
        tan1[i3] += sdir;

        tan2[i1] += tdir;
        tan2[i2] += tdir;
        tan2[i3] += tdir;

        triangle++;
    }

    for (long a = 0; a < vertexCount; a++)
    {
        const Vector3D& n = normal[a];
        const Vector3D& t = tan1[a];

        // Gram-Schmidt orthogonalize
        tangent[a] = (t - n * Dot(n, t)).Normalize();

        // Calculate handedness
        tangent[a].w = (Dot(Cross(n, t), tan2[a]) < 0.0F) ? -1.0F : 1.0F;
    }

    delete[] tan1;
}

```

Full source code and derivation can be found here.

---
Tags: textures, glsl, uv-mapping, three.js
---


# Question
Title: Animation workflow between Blender and Mecanim
I've recently started learning Unity. Not being able to add custom animations to the standard FBXs you get from Unity's app store is really really slowing me down. When I import one into Blender, it brings none of the animations with it. I also purchased 3D Studio Max and, while a little better, it's still a steep learning curve.

Can I create an animation in Blender or 3D Studio Max and apply it to an existing Mecanim model?

Do I need to manually create and rig a basic model, import it, then move its animation to another character, or is there an easier way?

# Answer
You are on the right track with the rig needing to be the same. If you are using one character mesh and model you can reassign textures in Unity3D as needed.

One thing to check is the Unity documentation: http://docs.unity3d.com/Documentation/Manual/HOWTO-ImportObjectMax.html

It covers importing and exporting from MAX including "Exporting Bone-based Animations" which may be of use. I'm not sure how you would go about applying that to the existing models in Mecanim but if you can apply them in blender/MAX then it should import nicely into Unity3D.

**Edit:** It looks like others have had the same issue:

How do I import asset and maintain textures

To quote:

> Make sure you have the textures imported otherwise the model can't find even if it wanted too.
>
> But even then, you may have to manually assign the proper textures to the materials after importing. Select each material and see if the texture is missing... if so, find/guess what texture goes with it and drag it in ther

In Unity when you import the objects make sure your import settings (available by selecting the object in your project view and revealing in the Inspector) are set to import the models textures. See if this helps.
> 3 votes

# Answer
Right thanks for Blue for helping me figure this out, if you want to add extra animations to the stock humanoids from the Unity Asset store the following worked for me:

1) Start a new project in 3d Studio Max

2) Click Animation-\>Bone Tool

3) From the right hand pane select "Biped", click in the viewport and size accordingly.

4) Animate the biped anyway you like(lots of tutorials on youtube), Note you do not need to add a mesh.

5) Click on the viewport and press Ctrl-A to select everything

6) Click file-\>export and save the FBX anywhere you like

7) Drag the resulting file into the Assets in unity

8) Click the imported file and in the right pane in unity click Rig then select the animation type as humanoid, click Apply.

9) Click the little play button on the icon for the asset you just imported.

10) You should see something like take 001 - thats your animation

I managed to get this to play with lots of different asset store bipeds and all seem to work fine, please note i'm by no means an expert in either pieces of software but I needed a quick way to add animations to existing characters so I can get on with learning unity rather than 3ds Max etc.

It should be noted also that the standard 3ds Max biped comes with hands but not fingers so thats something extra to figure out but all in all its actually not that hard!
> 3 votes

---
Tags: unity, animation, blender, 3dsmax
---


# Question
Title: How can I ensure field of view symmetry in a Roguelike?
I'm working on a Roguelike, and for it I've created a ray-tracing/casting field-of-view (FoV) algorithm that consists of plotting Bresenham lines to every point in a solid circle. It's artifact free (and reasonably efficient), but it is missing an important requirement of mine: symmetry (if you can see a monster, it must also be able to see you).

Here's an example of the non-symmetric behavior of my code. In the left image I'm standing in a corner (red 'X' blocks = wall). I'm able to see the top right tiles. However, if I move to one of those tiles (right image), I can no longer see the tile from which I came from.

I think I might be after a form of Permissive Field of View, but only because the Roguebasin article suggested it allowed for symmetry. Are there alternative means to get symmetry?

# Answer
It seems you include a square when you can see any point in it while the eye is at the single fixed point.

However, you should only include a square when you can see the middle of it (assuming the "eye" is also in the middle). Or you can draw rays from each corner of the starting square to the corners of the tested square, if you can see any from any then include.

The key point is that the hitbox of a square should also be all the locations where the eye must be.
> 8 votes

---
Tags: raycasting, roguelikes
---


# Question
Title: Using System Time to compute delay times that correctly deal with app pauses?
In my Android app I have the requirement to introduce small (for slowing down animation) and larger delays (for the purpose of delaying the appearance of a character for example).

I've experimented with 2 different ways, those being:

```
long grabTime;
int delayInMillis;

public void doStuff(){

//Initialise timeGrab variable
    if (grabTime==0)
        grabTime = System.currentTimeMillis();

//Has the desired number of Milliseconds passed?
    if (System.currentTimeMillis()>timeGrab+delayInMillis)

//If so, then do something here

//And re-grab the time ready for the next time
    grabTime = System.currentTimeMillis();

}

```

Where I have a batch of sprites (where each one will have a different delay) I find it easier to do this

```
long grabTime;
int spritesDelay = new int[numberOfSprites];
int forLoopCounter;

//Populate the array with desired delays (in seconds)
spritesDealay[0]=1;
spritesDealay[1]=2;
spritesDealay[2]=3;
spritesDealay[3]=4;

public void doStuff(){

    //Initialise timeGrab variable
    if (grabTime==0)
        grabTime = System.currentTimeMillis();

    //Has 1 second second passed?
    if (System.currentTimeMillis()>(timeGrab+1000)){

    //If so, reduce delay counters by 1

    for (forLoopCounter = 0;forLoopCounter<spritesDelay.length;forLoopCounter++){

        spritesDelay[forLoopCounter]--;
    }

    //And re-grab the time ready for the next 1 second count
        grabTime = System.currentTimeMillis();
    }

    //Now run through all the sprites and check to see if any of the timers have expired

    for (forLoopCounter = 0;forLoopCounter<numberOfSprites;forLoopCounter++){

        if (spriteDelay[forLoopCounter]<=0){

    //Do stuff here

    //If action has completed then reset the delay

    if (*Some criteria has been met*){

    spriteDelay[forLoopCounter]=4; //put in either explicit value for all sprites or restore previously backed up spriteDelay array (Not shown here)

            }

        }

    }
}

```

In my app (a game) - I am using the second method to have some sprites moving in an up/down motion, each successive one with a slight delay on the previous one (think of a wave like motion).

**The problem**

This does work, however, when I pause my game (which simply halts game updates and continues rendering with a 'paused' graphic over the screen), on resuming play, things are out of sync slightly (because obviously the system time doesn't stop when the game is paused, so the first check after un-pausing to see if the second has elapsed will always be true providing the game was paused for longer than 1 second).

After the sprites have all moved through one motion, then they do sync up again and everything is OK.

However I'm not happy with the remainder of the current cycle being out of sync.

**Alternatives?**

Another way I've thought of doing this is hold an **int** that counts up each time my game update method is run (my game is 'limited' to 60 logic updates per second), then when it reaches 60, I would know a second has passed. This has the advantage that the counting will stop when the game is paused.

However, if the game were ever to be run on a device that couldn't handle 60 logic updates per second then it would slow down counting and throw everything off. (My ticks per seconds are separated from my rendering per second which runs flat out so although the FPS may drop, the logic updates per second *should* carry on at 60. I find it unlikely that a device wouldn't be able to handle 60 game updates per second (as I've tested this on a Galaxy Ace version 1 and that was fine at 60) but I'd like my app to be as robust as possible and don't really want to risk the timings being thrown off by a slow device however unlikely.

So I'm a bit stuck. Is there another system timer I can use which can be controlled? (switched off when required) or would my 'logic-updates-per-second' method be the best bet?

# Answer
Try keeping track of elapsed time instead of having a target time to accomplish something. This way, when the game is paused you can capture the time it was paused and unpaused so you know how much elapsed time to ignore.

If I got my math right this might look something like the code below:

```
//Normal gameplay update
currentTime = System.currentTimeMillis();
elapsedTime += currentTime - previousTime;

if (elapsedTime > 1000)
{
    //dostuff
    elapsedTime = 0; //reset so we can do it again
}

previousTime = currentTime;

//On Pause
pauseTime = System.currentTimeMillis();

//On Unpause
pauseDuration = System.currentTimeMillis() - pauseTime;
previousTime = previousTime + pauseDuration;

```
> 1 votes

# Answer
I do not like the vague language used to describe this particular part of Java. It appears to be layered on top of an operating system provided method for acquiring system time (e.g. time relative to January 1st 1970), and thus the granularity may be as poor as 1 second. But my actual concern is that there is no guarantee of monotonic return value - that is, it may produce a paradoxical situation where the returned value in a later call actually indicates a time earlier than the first call. This will happen if it reads the "wall clock" and the user or a system service (e.g. periodic internet time server sync.) decides to change the time.

I would strongly suggest that you consider using `nanoTime (...)` instead. While this also makes no guarantee that the returned value will be monotonic, it will give better granularity than `currentTimeMillis (...)`. And since this timer is not based on the wall clock, sources of non-monotonic returned values are fewer. There is still the possibility that this timer could be implemented using something stupid like a CPU `rdtsc` instruction (which varies depending on which CPU/core the executing thread is scheduled on), but most platforms provide high-precision monotonic timers these days and Oracle is probably smart enough to use them instead.
> 0 votes

---
Tags: java, android, timer, timing
---


# Question
Title: How do you create an input layout for passing a uint4 to a vertex shader in D3D10?
I am trying to pass in a uint4 into the shader but my input layout keeps failing when trying to load the shader.

**shader.fx**

```
uint4  values : UINT4_0;  // VertexInput

```

**Input layout**

```
{ "UINT4", 0, DXGI_FORMAT_R32G32B32A32_UINT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 }

```

Does that seem right?

I am a bit confused why there is an error here.

# Answer
I found a way to do this and I thought I will post it here since it will help others. In order to pass in a `UINT4` into an HLSL, you must have the following:

**1. InputLayout**

```
{ "UINT4_", 0, DXGI_FORMAT_R32G32B32A32_UINT, 0, D3D10_APPEND_ALIGNED_ELEMENT, D3D10_INPUT_PER_VERTEX_DATA, 0 }

```

**2. InputVertex**

```
 uint4 valuesUnsigned: UINT4_0;

```

**3. Input Data Structure**

```
struct UINT4__
    {
        unsigned int a1;
        unsigned int a2;
        unsigned int a3;
        unsigned int a4;

        UINT4__(){};

        UINT4__(unsigned int x, unsigned int y, unsigned int z, unsigned int w)
        {
            a1 = x;
            a2 = y;
            a3 = z;
            a4 = w;
        }
    };

```

*EDIT: Added what NathanReed has said in one of his comments on this question.*
> 0 votes

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


# Question
Title: How would one outline an alpha transparency layer in javscript and/or php?
I simply want an outline/edge detection of the character/item/object that is selected or doing something.

I'm seeing lots of versions of this question for different languages, but I would appreciate an approach that can be implemented in a web context. I don't know if this is better dealt with in the server or can be done on the client side. I have no idea of how to access the alpha transparency layer in any language. Please advise. Sorry for the lack of specificity, just getting a handle on what I want. This would be in a 2d context.

This picture outline object effect shows what i'm going for. Not sure if answers in that question apply to my problem.

# Answer
> 1 votes
Neither JS nor PHP are very suitable for what you're trying to do. You can define transparency in PHP (http://www.php.net/manual/en/function.imagecolortransparent.php), but I'm not sure if you can actually read it out. Also understand that PHP is a server side language, so for any real-time interaction of on-screen elements it's not very suitable.

You bets bet is probably looking at WebGL HTML5 & "canvas" tag

Pixel manipulation: http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#pixel-manipulation

MDN ImageData reference: https://developer.mozilla.org/en-US/docs/DOM/ImageData

---
Tags: javascript, webgl, php, three.js, outline
---


# Question
Title: How can I regulate update and event frequency?
I'm trying to create a small 2D RPG-type engine using C++, SDL/OpenGL and Tiled. My little demo looks very similar to a Pokemon or Zelda game.

I was curious how to go about regulating FPS and how many times a certain event action is processed. For example, each iteration of my main loop handles events (such as if an arrow key is pressed, move the character up one tile, et cetera), then draws, and then updates then screen.

If I wanted the game to draw 24 frames every second, but only run the keyboard actions 6 times per second, how would I go about doing that? Is this even reasonable? Should I regulate everything to process 6 frames per second? Or would it make sense to create two threads, one for drawing and one for event handling?

This is my main game loop:

```
    while (!theGame->getQuit()) {
        fps.start();

        handleEvents();

        while (SDL_PollEvent(&event)) {
            switch (event.type) {
                case SDL_QUIT:
                    theGame->setQuit(true);
                    break;
                case SDL_KEYDOWN:
                    handleKeyDown(event.key.keysym.sym);
                case SDL_KEYUP:
                    handleKeyUp(event.key.keysym.sym);
                    break;
                default:
                    break;
            }
        }
        update();

        render();

        // FRAMES_PER_SECOND = 6 OR 24
        if (fps.get_ticks() < 1000 / FRAMES_PER_SECOND) {
            SDL_Delay((1000 / FRAMES_PER_SECOND) - fps.get_ticks());
        }
    }

```

# Answer
> 1 votes
To run things at different frequencies -- commonly used for reducing costly processing like AI so that it is intermittent -- maintain a counter that persists between game loop iterations, and on every frame, increment the counter by `1`. Check if it has reached `4`; if so, call your input function, and reset the counter to `0`. It will then recount up to `4` and repeat this logic, till the game loop stops cycling.

The number is `4` because `24 / 6 == 4`. I assume that your game loop runs at 24 fps: Set your main loop frequency to be that of whatever task you need to do most frequently, in your case, drawing; and from there you may divide up this, your highest frequency, into lower ones, using counters, for other tasks. No multithreading required.

**EDIT** To regulate how quickly your character moves, there'd be two ways:

* For real-time / continuous motion, pick the velocity (say half a tile per second) and apply that based on the delta time, e.g. `velocityTilesPerSec = 0.5; player.position.x += velocityTilesPerSec * deltaSec;` `deltaSec` may be fixed or variable timestep, see Fix Your Timestep for an introduction to these.
* For turn-based motion, ensure that you move your character in `x` and/or `z` one half-tile per key hit, e.g. `player.position.x += velocityTilesPerSec`

N.B. there is another concept involved here, i.e. how do you want to deliver the input? Continuous input (key / button held down with ongoing response) is normal for controlling characters using keyboard or gamepad. Single-hit input is the other approach: You hit a key but it doesn't create continuous response, it has a single-frame response; e.g. hitting F1 for help in-game.

# Answer
> 0 votes
The following is an example solution that will provide a frame rate independent event fire:

```
const int SECONDS_TO_WAIT = 5
DateTime eventLastFiredTime = null;

public void myEvent()
{
    if (eventLastFiredTime + SECONDS_TO_WAIT < DateTime.Now()
        || eventLastFiredTime == null)
    {
        eventTimeLastFired = DateTime.Now();

        // movement code here
    }

}

```

Please not that this code in not syntactically correct, it is just a basic C# style solution to give you an idea.

---
Tags: opengl, c++, 2d, events, frame-rate
---


# Question
Title: Code to generate a color gradient within a texture using a diagonal line
I want to generate a color gradient between two colors from x1,y1 to x2,y2. I'm unsure how to do this though. I can use Color.Lerp to get all of the color steps, but the problem is that I don't understand how to then apply that to a plane (the texture pixels) when the line would be at an angle.

If it was a horizontal/vertical line, that would be easy, because it's just plotting the same color along the appropriate axis. But if it's a diagonal line of any degree, that seems way more complicated and I'm unsure how to do calculate it.

As an example, here is a gradient from a picture editor program. It goes from green-to-red. The actual start and end positions are the circles. Therefore, the solid start/end colors continue solid outside of the gradient area.

# Answer
Here is one way to do it, the idea behind this method is rotating the whole image to make the line straight while working on it. I am only using half of the matrix because the line is flattened horizontally and so the Y coordinate doesn't matter to us then.

*0.* Convert your startPoint and endPoint into vectors:

```
float x1 = (startPoint.X / (float)width)  * 2.0f - 1.0f;
float y1 = (startPoint.Y / (float)height) * 2.0f - 1.0f;
float x2 = (endPoint.X / (float)width)  * 2.0f - 1.0f;
float y2 = (endPoint.Y / (float)height) * 2.0f - 1.0f;

```

*1.* Find the angle between (x1,y1) and (x2,y2):

```
float angle = atan2(x1 - x2, y1 - y2);

```

*2.* Create half of a rotation matrix (We only need half for this)

```
float rx = cos(angle);
float ry = sin(angle);

```

*3.* Calculate start and end points in rotated space:

```
float start = x1 * rx + y1 * ry;
float end =   x2 * rx + y2 * ry;

```

*4.-.* For each pixel:

```
for(int x=0;x<width;x++) {
    for(int y=0;y<height;y++) {

```

*4.1.* Rotate the pixel so the line is horizontal

```
        // but we need vectors from (-1, -1) to (1, 1)
        // instead of pixels from (0, 0) to (width, height)
        float u = (x / (float)width)  * 2.0f - 1.0f;
        float v = (y / (float)height) * 2.0f - 1.0f;

        float here =  u * rx + v * ry;

```

*4.2.* Find the ratio between start and end

```
        float lerp = (start - here) / (start - end);

```

*4.3.* Interpolate between your colors and finish the pixel

```
        SetPixel(x,y, Color.Lerp(color1, color2, lerp));
    }
}

```
> 2 votes

# Answer
You can project each point of the canvas on the (x1,y1)—(x2,y2) line and get a value between 0 and 1 that you then use for lerping. Here is some pseudocode:

```
for (y = 0; y < height; ++y)
    for (x = 0; x < width; ++x)
    {
        float A = (x - x1) * (x2 - x1) + (y - y1) * (y2 - y1);
        float B = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
        float U = Clamp(A / B, 0.0, 1.0);

        SetPixel(x, y, Color.Lerp(Color1, Color2, U);
    }

```
> 2 votes

# Answer
To be honest, I wouldn't even start trying to create a texture and update all the pixels. This is far from being efficient, unless you want to do more complicated patterns than just a simple gradient.

Basically, for me there are two valid approaches:

* Draw a quad with colored vertices (fixed pipeline rendering).
* Draw a quad and color it using a fragment shader.

To render the quad in both cases, you can just look at this question and answer. Then just add colors to the vertices or enable shader usage.
> 0 votes

---
Tags: xna, c#, mathematics, monogame
---


# Question
Title: How can I support a background more complex than a flat color?
I'm a beginner at making 2D games. Up until now, I always created my games with a black background, or a fixed color. This is because my sprites always have a black (or a solid color) background, and I have to set the background of the game black so the sprites won't be moving around with a black box surrounding them.

Now I want to be able to set the background of the game to an image or texture.

What do I need to do in order to achieve that? Is it possible to design sprites without a background in the first place? Currently if I need a sprite of a guy standing, I would draw the guy on a black rectangle. Is it possible to set the rectangle to be transparent instead of black?

# Answer
> 2 votes
This is very possible. Most graphics APIs support a concept known as alpha blending, a process of combining two images in such a way as to make it look like one of them is transparent.

This is generally accomplished by adding an additional color channel to the standard red, green and blue channels: *alpha*, which represents how opaque a pixel is. Zero indicates a fully transparent pixel, and the maximum value (usually 1 or 255 depending on how the color channels are represented indicates full opacity).

Thus, to accomplish your goal of a game with a background other than solid black, you need:

* To author your sprites such that the "background" parts of the sprite is transparent (has an alpha of zero) and the foreground parts aren't (full alpha, or partial alpha to give a "see-through" effect to part of a sprite). Most image editors support this, consult your editor's documentation.
* To save your sprites such that the alpha is preserved (i.e., in a format that supports it). `.png` is widely-supported and has alpha-channel support.
* To load your sprites into RGBA textures. Often this will be handled implicitly by your graphics API, if you are using utility functions of the form "load texture from file." If you do have to manually specify a format, make sure you specify one that has four components ("RGBA" for example).
* To enable alpha-blending support in your graphics API. This is the part where you will have a lot of variability depending on what you are doing. You can consult your API's documentation on alpha-blending to learn how to enable it, it's usually only a few calls to enable the function and describe the blend factors. For example, in OpenGL you need to make calls to `glEnable` and `glBlendFunc`.
* To make sure your shaders, if you are using them, correctly output alpha values from the fragment shader. Since the alpha is stored in your texture (if you did the previous steps above), this means you just need to make sure you sample the full color from the texture, and aren't doing any masking to just the `rgb` components or anything.

You may also run into a technique called color key transparency. This is a similar technique, often used when for whatever reason alpha channels aren't available or are undesired. It's less common these days, it was used more often before hardware accelerated rendering was so common and we would blit our sprites by hand. It works, essentially, by selecting a color meant to be transparent (usually something like a hot pink or full blue, something unlikely to be used for "real" pixels) and simply not copying those pixels when blitting an image. These days it is often easier to simply use the alpha-based methods, or at least translate color-keyed sprites into ones with alpha by the time you get to rendering via the graphics card.

---
Tags: 2d, sprites
---


# Question
Title: Light Space and Light Texture Space in shaders
I'm looking into material translucency and I'm working through some GPU Gems documentation (http://http.developer.nvidia.com/GPUGems/gpugems\_ch16.html).

In Example 16-4 it references matrices for both light space and light texture space.

```
   // Given a point in object space, lookup into depth textures
   // returns depth

   float trace(float3 P,
            uniform float4x4  lightTexMatrix, // to light texture space
            uniform float4x4  lightMatrix,    // to light space
            uniform sampler2D lightDepthTex)
{
  // transform point into light texture space
   float4 texCoord = mul(lightTexMatrix, float4(P, 1.0));

  // get distance from light at entry point
   float d_i = tex2Dproj(lightDepthTex, texCoord.xyw);

  // transform position to light space
   float4 Plight = mul(lightMatrix, float4(P, 1.0));

  // distance of this pixel from light (exit)
   float d_o = length(Plight);

  // calculate depth
   float s = d_o - d_i;

  return s;
}

```

Can anyone explain to me what light texture space iS and how exactly I'd calculate a matrix for it? I think I'm OK getting the light matrix and it's projection matrix but a 4x4 light texture space matrix is blowing my mind.

I can't find anything else that specifically references those terms, but I'm well aware that terminology for shaders changes depending on who you speak to. They may well be better known as something else, though I'd hope Nvidia would be using well recognised terminology.

# Answer
> 2 votes
From quickly perusing the article, it sounds like the texture they're talking about is simply a shadow map for the light, although it stores linear world-space distance in a color channel rather than using the nonlinear post-projective depth. In any case, `lightTexMatrix` here is the same matrix you'd use for calculating the position to sample a shadow map—namely, it transforms the point to light space, then applies the shadow map projection matrix, then remaps the result from the \[-1, 1\] of NDC to the \[0, 1\] of texture coordinates.

---
Tags: shaders, matrix
---


title: DXUT getters are always null using DLL

text:
# Question
Title: DXUT getters are always null using DLL
I'm struggling with a problem for a while and I hope some of you can help me out. The title for this question is vague, so I will try to explain my problem as best as I can!

I'm am creating a project (in C++ using Visual studio 2012) with a DLL that has the DirectX toolkit and `DXUT` as references. I initialize `DXUT` (the device and all that kind of stuff) in the DLL and create a `GameScene` (`GameScene` is in the executable) after `DXUT` is initialized. The `GameScene` derives from its base class `BaseScene` (`BaseScene` is in the DLL project).

When I call `DXUTGetD3D11Device()` to get the DirectX device in the `GameScene` (in the executable) it is all fine, but when I call `DXUTGetD3D11Device()` in the `BaseScene` it returns null.

Note: This counts for all the `DXUT` functions! Note: The executable has the same references as the dll + the dll!

If you need more information to answer my question, ask me! I find it really hard to explain my problem and I will try my best to make it more clear!

# Answer
> 1 votes
DXUT is a static library by default, IIRC. If that's the case, when you link DXUT into both your .exe and your .dll, you actually get two separate copies of it. Any internal state will not be shared between the two, so if you initialize DXUT in one module, that device/window/etc. will not automatically be available in the other module.

You could work around this by hacking the two DXUTs to share states. Inside DXUT all the state is in the `DXUTState` class, and there is a global pointer `g_pDXUTState` that gets set up when you initialize the library. You could copy this pointer from one module to the other. However, it's possible this could cause problems because DXUT wasn't designed for this use case and it might violate some of its internal assumptions.

Another possibility is to modify DXUT into a .dll instead of a static library, which would result in just one copy of it existing in your application; but that sounds like it would probably be a lot of work.

Probably the cleanest solution is to use DXUT from only one of the modules. If you use it in the .exe, don't use it in the .dll; just pass the device pointer, window handle, etc. from the .exe to the .dll through function parameters.

---
Tags: directx, visual-studio, dll
---


# Question
Title: Why is my vertex buffer filled with random, incorrect data?
I've been using the Graphics-Debugger of VS2012 to see why my triangle is not drawn. It seems to be a problem with my VertexBuffer since all other Buffers show the data I fed them, however, the VertexBuffer contains random data every time I restart the application:

```
The buffer format used is specified in the 'Graphics Object Table'.

---------------------------------------------------------------------------------------------------------------------------------
Types:  bool, int, xint (an unsigned hex int), uint (unsigned int), int64, xint64, uint64,
        byte, xbyte, ubyte, 2byte,  x2byte, u2byte, 4byte, x4byte, u4byte, 8byte, x8byte, u8byte,
        half (a 16-bit float), half2, half3, half4, float, float2, float3, float4, double
Usage:  'float' or 'float3 xint half half xint'
---------------------------------------------------------------------------------------------------------------------------------
Currently used format:  float
---------------------------------------------------------------------------------------------------------------------------------

0   [0x00000000-0x00000003] |       +0.070048094
1   [0x00000004-0x00000007] |    +3.0548307e-043
2   [0x00000008-0x0000000b] |       +0.069985747
3   [0x0000000c-0x0000000f] |    +3.0548307e-043
4   [0x00000010-0x00000013] |       +0.069986284
5   [0x00000014-0x00000017] |    +3.0548307e-043
6   [0x00000018-0x0000001b] |       +0.069986284
7   [0x0000001c-0x0000001f] |    +3.0548307e-043
8   [0x00000020-0x00000023] |       +0.070065737
9   [0x00000024-0x00000027] |    +3.0548307e-043
10  [0x00000028-0x0000002b] |                 +0
11  [0x0000002c-0x0000002f] |                 +0
12  [0x00000030-0x00000033] |                 +0
13  [0x00000034-0x00000037] |                 +0
14  [0x00000038-0x0000003b] |                 +0
15  [0x0000003c-0x0000003f] |                 +0
16  [0x00000040-0x00000043] |    -4.3159552e+008
17  [0x00000044-0x00000047] |    -4.3160208e+008

```

Or

```
0   [0x00000000-0x00000003] |           +1.#QNAN
1   [0x00000004-0x00000007] |    +1.2331426e-043
2   [0x00000008-0x0000000b] |           +1.#QNAN
3   [0x0000000c-0x0000000f] |    +1.2331426e-043
4   [0x00000010-0x00000013] |           +1.#QNAN
5   [0x00000014-0x00000017] |    +1.2331426e-043
6   [0x00000018-0x0000001b] |           +1.#QNAN
7   [0x0000001c-0x0000001f] |    +1.2331426e-043
8   [0x00000020-0x00000023] |           +1.#QNAN
9   [0x00000024-0x00000027] |    +1.2331426e-043
10  [0x00000028-0x0000002b] |                 +0
11  [0x0000002c-0x0000002f] |                 +0
12  [0x00000030-0x00000033] |                 +0
13  [0x00000034-0x00000037] |                 +0
14  [0x00000038-0x0000003b] |                 +0
15  [0x0000003c-0x0000003f] |                 +0
16  [0x00000040-0x00000043] |    -4.3159552e+008
17  [0x00000044-0x00000047] |    -4.3160208e+008

```

As you can see, the last 8 lines are identical (this is always the case) whereas the rest varies randomly. However, even the last 8 entries are not entirely correct.

My InputLayout is set correctly according to the debugger:

```
SemanticName SemanticIndex Format                      InputSlot AlignedByteOffset InputSlotClass              InstanceDataStepRate
POSITION     0             DXGI_FORMAT_R32G32B32_FLOAT 0         0                 D3D11_INPUT_PER_VERTEX_DATA 0
COLOR        0             DXGI_FORMAT_R32G32B32_FLOAT 0         12                D3D11_INPUT_PER_VERTEX_DATA 0

```

Here is the Vertex-Struct

```
struct VERTEXPOSITIONCOLOR
{
    DirectX::XMFLOAT3   position;
    DirectX::XMFLOAT3   color;

    static D3D11_INPUT_ELEMENT_DESC* GetVertexLayout()
    {
        static D3D11_INPUT_ELEMENT_DESC layout[] =
        {
            { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT,
                0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
            { "COLOR", 0, DXGI_FORMAT_R32G32B32_FLOAT,
                0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
        };
        return layout;
    }

    static UINT GetNumElements(){ return 2; }
};

```

Here I fill my Vertex-Vector:

```
VERTEXPOSITIONCOLOR p;
p.position = XMFLOAT3( -1.0f, 0.0f, 0.0f );
p.color    = XMFLOAT3(  1.0f, 0.0f, 0.0f );
m_vVertices.push_back( p );

p.position = XMFLOAT3( 0.0f, 1.0f, 0.0f );
p.color    = XMFLOAT3( 0.0f, 1.0f, 0.0f );
m_vVertices.push_back( p );

p.position = XMFLOAT3(  1.0f, 0.0f, 0.0f );
p.color    = XMFLOAT3(  0.0f, 0.0f, 1.0f );
m_vVertices.push_back( p );

```

with `m_vVertices` being of type `std::vector<VERTEXPOSITIONCOLOR>`.

And here I create the VertexBuffer:

```
D3D11_BUFFER_DESC bufferDesc;
bufferDesc.ByteWidth = static_cast<UINT>( m_vVertices.size() * GetStrideSize() );
bufferDesc.Usage = D3D11_USAGE_DEFAULT;
bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
bufferDesc.CPUAccessFlags = 0;
bufferDesc.MiscFlags = 0;

D3D11_SUBRESOURCE_DATA InitData;
InitData.pSysMem = &m_vVertices;
InitData.SysMemPitch = 0;
InitData.SysMemSlicePitch = 0;

HRESULT hr = m_spDevice->CreateBuffer( &bufferDesc, &InitData, &m_spVertexBuffer );

```

with `bufferDesc.ByteWidth` having the value `72` and `hr` having the value `S_OK` at the end. `m_spVertexBuffer` is of type `CComPtr<ID3D11Buffer>`.

Finally I call:

```
UINT Strides[1];
UINT Offsets[1];
Strides[0] = GetStrideSize();
Offsets[0] = 0;
pd3dImmediateContext->IASetVertexBuffers(0, 1, &m_spVertexBuffer.p, Strides, Offsets );

```

With `Strides[0]` having the value `24`. Here I also set all other buffers.

So what did I do wrong with the VertexBuffer?

# Answer
You don't want to set `InitData.pSysMem` to `&m_vVertices`. That is setting the system memory pointer to the address the `vector` object; you want to point instead to the actual data *stored* in the vector object:

```
InitData.pSysMem = &m_vVertices[0];

```
> 1 votes

---
Tags: c++, directx11
---


# Question
Title: How can I test if an object will "fit" during pathfinding?
I'm tinkering around with a 2d game where obstacles are polygons of arbitrary shapes, sizes and locations, and movable entities (players/enemies) can also be of arbitrary sizes.

What's a good general approach for detecting whether a given entity can "fit" between two obstacles during pathfinding? Basic graph-based pathfinding algorithms like Dijkstra's or A\* typically involve merely a boolean (and possibly a weight). It's not immediately clear to me what's the best way of extending that to restrict narrow passages to small entities.

Presumably each entity size would need to have its own graph of the map?

I'm not familiar with the literature on this subject but I'm sure it exists - any pointers would be welcome.

# Answer
Typically the process is something like this...

1. Determine the object's motion vector
2. Mass-project the object's vertices onto a line (2D) or plane (3D) along the motion vector to see whether they intersect the obstacles.

(There may be cheaper ways to rapidly reduce the object's vertices to two points which represent the maximal profile of the polygon, but I doubt it would be less than O(n) anyway, unless of course you aim for the bounding circle of sphere instead.)

This is the simple case, where we assume that the object will not twist or turn back and forth to fit through the gap; this is essentially just the same as checking whether the convex hull could fit, but only at a single orientation. For instance, an ellipsoid might jam going in broadside-first, but going head-on, it might fit through. So you may at least want to check the profile of the object at multiple orientations to see if it might fit. Then if your object were smart, it could calculate the time taken to reach the obstacles at current velocity, and lerp to that orientation before then.
> 2 votes

---
Tags: physics, ai, path-finding, computational-geometry, collision-avoidance
---


# Question
Title: Creating a textured object infront of the current character in unity 3d
I've spent about half a day trying to get my head round this and I'm not having too much luck, essentially what I want to do is play an animation and then once the animation has finished create a flat disk shaped object in front of the current player, the code I have is as follows, please see my comments below for a list of problems:

Note this is cut down code to make the example easy.

```
static int idleState = Animator.StringToHash("Base Layer.idle");
static int portalState = Animator.StringToHash("Base Layer.Portal");

private RenderTexture portal_texture = Resources.Load("Portal") as RenderTexture;

void Start () {
    portal_texture = Resources.Load("Portal") as RenderTexture;
    anim = GetComponent<Animator>();
    if(anim.layerCount ==2){
        anim.SetLayerWeight(1, 1);
    }
}

void Update () {

    if(Input.GetKey("p")){
        anim.SetBool("cast_portal", true);
    }

    if(Input.GetKeyUp("p")){
        sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
        sphere.transform.position = transform.TransformPoint(Vector3.zero);
        sphere.transform.localScale = new Vector3(3,3,1);
        Vector3 temp = sphere.transform.localScale;
        temp.x = (sphere.transform.localScale.x + 12.0f) * 0.5f;
        sphere.transform.localScale = temp;
        sphere.renderer.material.mainTexture = portal_texture;
    }
}

```

Problems

1. The render texture doesn't appear on the object
2. I need to have the object appear about 10 meters infront of where the character is facing, note I'm using a third person controller so camera position won't cut it.
3. How come in the inspector I can set any of the scaling options to 0.001 but if I try it in vector3 it throws an exception when compiling?
4. Where do I need to put this code so it only adds the sphere once the animation has finished?

I only started with unity this week so I'm probably missing something very obvious, I'm just having a bit of a brain freeze so any help would be greatly appreciated.

Thanks

# Answer
You can utilize prefabs and public fields on a MonoBehaviour to make this a lot easier:

```
public class YourObject : MonoBehaviour {

    // The prefab we want to instantiate when we press p.
    // This needs to be set in the inspector; you'll see a field pop up in
    // the inspector where you can select the prefab to instantiate.
    // Always be sure to make this public so the inspector can see it.
    public GameObject myPrefab;

    void Start() {
        // Animation stuff
    }

    void Update() {

        if (Input.GetKey("p")) {
            // Play the animation
        }

        if (Input.GetKeyUp("p")) {
            // Here we just instantiate our prefab.
            // We can use transform.forward to get the direction our character is facing.
            // In this case, we mulitply it by 10 to create the prefab 10 units away.
            GameObject.Instantiate(myPrefab, transform.forward * 10, Quaternion.identity);
        }
    }
}

```

This makes your code much simpler and you can modify the prefab however you want.

I sadly do not know a whole lot about animation in Unity, so I cannot answer that part of your question. However, something tells me you might want to try using `Animation.Play()` instead of setting some kind of value to play an animation :)
> 2 votes

---
Tags: unity, c#
---


# Question
Title: OBB Collision Resolution: Jittering with Long Rectangles
I have been working on a physics simulation module. Almost everything works properly, but I am having an issue, which I have demonstrated in the following video.

http://youtu.be/2L17y9Lme0Q

As you can see in the video, if an object doesn't have an angular velocity, everything is OK. But once an angular velocity (even just a little) is applied to the object and it collides with the ground, it begins to shake.

I check for collision and get the normal and MTD (Minimum Translation Distance) using SAT (Separating Axis Theorem).

To get the contact point, I check for intersections between the two polygons. If there is more than one point of intersection, I then find the point in between the two intersection points.

Then I resolve overlapping objects by using the normal, MTD, and mass factor. To solve the collision, I use the Impulse theory.

Do you have any idea what might be causing this shaking effect? Could it be caused by a wrong choice of contact points?

# Answer
> 2 votes
This is because you only have a single point of contact. During the first solve you apply a huge torque, which forces the other side of the object downward -repeating the cycle.

One way is to keep both points of contact. You can solve this issue by solving two different resolution contacts, one for each point, and spread out the impulse scalar over each point of contact based upon depth.

```
for each scalar impulse j and associated contact depth
{
  ApplyImpulse( objectA, j, depth );
  ApplyImpulse( objectB, -j, depth );
}

```

This will provide multiple angular responses, of which will cancel each other out leaving only the upward linear impulses.

Please also be sure to allow objects to penetrate slightly with a slop factor, and do not resolve collision with separating velocity.

---
Tags: collision-detection, physics, collision-resolution
---


title: GLSL pack floats into an RGBA texture

text:
# Question
Title: GLSL pack floats into an RGBA texture
I want to compose conventional triangle-based models and particles with a ray-traced scene at a reasonable frame-rate.

webGL does not let you write the `gl_FragDepth` in the fragment shader. You cannot have multiple render targets, but you can render to an RGBA texture and then use that texture as input to another draw-op. So I can render my ray-traced scene and store the depth as input to the next stage. This is obviously far from ideal, but workable.

I'd love to be wrong about this, and this is gathered from trial and error rather than any definitive source; please correct any flawed assumptions

How can you pack/unpack a float and, ideally, some flag bits and such, into an RGBA texture efficiently in a GLSL fragment shader?

# Answer
> 5 votes
Here are pack and unpack functions that will work on WebGL and OpenGL ES 2.0, this is only for values in the 0...1 range so you should take care your depth calculation is in the correct space.

Encoding Floats to RGBA

---
Tags: textures, glsl, webgl
---


title: Reducing Spherical Harmonic Ringing

text:
# Question
Title: Reducing Spherical Harmonic Ringing
I've generated some 2nd order SH light-probes from cube-maps in my scene and I was surprised how strong artifacts are around the back of the dominant lights. I switched to a Lambert source plus ambient and got a result just like in the image below. Stupid SH Tricks (http://www.ppsloan.org/publications/StupidSH36.pdf) suggests a technique called Han Windowing for reducing the artifacts, which I'm guessing is a convolution filter similar to a Gaussian blur, but I'm unable to tell much from the description or find an example.

I've also read some sources that say Gaussian might be best when using a HDR source.

# Answer
> 1 votes
Hmmm. With regular Fourier transforms, window functions like the Hanning window are used to isolate a snippet of a signal (such as a 128-sample snippet out of a continuous audio signal for instance). Multiplying the snippet by a window function before taking the Fourier transform can improve the ability to distinguish different frequencies in the resulting spectrum.

However, I can't make sense of how this would apply to spherical harmonics. While they're a spherical analog of Fourier transforms, it doesn't make sense to me to apply a window function, because you're not snipping out a portion of a larger signal; your input is a cubemap that covers the whole sphere of directions.

Also, the article seems to suggest *blurring* the cubemap using a Hanning window function as the blur kernel, before projecting to the SH basis. In the usual use of window functions, you *multiply* the signal by them, rather than blurring (convolving) with them.

However, even if blurring the cubemap is the right thing to do (which it may well be—I just don't understand why), it sounds expensive, especially considering the blur ought to be done in angular space, across the cube edges and corners, and is non-separable. But on a small enough cubemap it could be OK. The open-source CubeMapGen tool can do this sort of thing—it doesn't have a Hanning window setting, but it has various other blurs you can apply. It's not fast, though.

---
Tags: mathematics, graphics, lighting, spherical-harmonics
---


# Question
Title: Height map renders upside down and/or backwards
After following the tutorial found here:http://www.riemers.net/eng/Tutorials/XNA/Csharp/Series1/VertexBuffer\_and\_IndexBuffer.php

The code at the bottom of this page is what I am using. (I have changed some things in attempt to fix the issue already, so my code and this are not exactly the same).

I noticed that the height map was actually being rendered upside down. For example, if I wrote "hello" in the height map, when drawn the letters would appear upside down. After fiddling with this for a while I cannot see the problem, and the letters would always appear backwards or upside-down or both.

Basically I am just trying to get the top of the height map to be drawn in the north (either +z or -z, final direction does not matter to me).

```
    private void LoadHeightData(Texture2D heightMap)
    {
        terrainWidth = heightMap.Width;
        terrainHeight = heightMap.Height;

        Color[] heightMapColors = new Color[terrainWidth * terrainHeight];

        heightMap.GetData(heightMapColors);

        heightData = new float[terrainWidth * terrainHeight];

        for (int i = 0; i < heightData.Length; i++)
                heightData[i] = heightMapColors[i].R;
    }

    private void SetUpVertices()
    {
        vertices = new VertexPositionColorNormal[terrainWidth * terrainHeight];
        //for (int y = terrainHeight - 1; y > -1; y--)
        for (int z = 0; z < terrainHeight; z++)
        {
            //for (int x = terrainWidth - 1; x > -1; x--)
            for (int x = 0; x < terrainWidth; x++)
            {
                vertices[x + z * terrainWidth].Position = new Vector3(x, heightData[x + z * terrainWidth], -z);
                vertices[x + z * terrainWidth].Color = Color.White;
            }
        }
    }

    private void SetUpIndices()
    {
        indices = new short[(terrainWidth - 1) * (terrainHeight - 1) * 6];
        int counter = 0;

        for (int y = 0; y < terrainHeight - 1; y++)
        {
            for (int x = 0; x < terrainWidth - 1; x++)
            {
                int lowerLeft = x + (y * terrainWidth);
                int lowerRight = (x + 1) + (y * terrainWidth);
                int topLeft = x + ((y + 1) * terrainWidth);
                int topRight = (x + 1) + ((y + 1) * terrainWidth);

                indices[counter++] = (short)topLeft;
                indices[counter++] = (short)lowerRight;
                indices[counter++] = (short)lowerLeft;

                indices[counter++] = (short)topLeft;
                indices[counter++] = (short)topRight;
                indices[counter++] = (short)lowerRight;
            }
        }
    }

    private void CalculateNormals()
    {
        for (int i = 0; i < vertices.Length; i++)
            vertices[i].Normal = new Vector3(0, 0, 0);

        for (int i = 0; i < indices.Length / 3; i++)
        {
            int index1 = indices[i * 3];
            int index2 = indices[i * 3 + 1];
            int index3 = indices[i * 3 + 2];

            Vector3 side1 = vertices[index1].Position - vertices[index3].Position;
            Vector3 side2 = vertices[index1].Position - vertices[index2].Position;
            Vector3 normal = Vector3.Cross(side1, side2);

            vertices[index1].Normal += normal;
            vertices[index2].Normal += normal;
            vertices[index3].Normal += normal;
        }

        for (int i = 0; i < vertices.Length; i++)
            vertices[i].Normal.Normalize();
    }

    public void Draw(GraphicsDevice device, Effect effect)
    {
        foreach (EffectPass pass in effect.CurrentTechnique.Passes)
        {
            pass.Apply();

            device.DrawUserIndexedPrimitives(PrimitiveType.TriangleList, vertices, 0, vertices.Length, indices, 0, indices.Length / 3, VertexPositionColorNormal.VertexDeclaration);
        }
    }

```

With that code:

Any ideas what the bug could be? I can always post more code but this is everything involved except for the camera. Thank you for your time!

# Answer
Figured it out.

```
int lowerLeft = x + (y * terrainWidth);
int lowerRight = (x + 1) + (y * terrainWidth);
int topLeft = x + ((y + 1) * terrainWidth);
int topRight = (x + 1) + ((y + 1) * terrainWidth);

```

The code above creates upside down triangles relative to the height map. (It is very easy to see after drawing it out on paper.) This code should become:

```
int topLeft = x + (y * terrainWidth);                     // was lower
int topRight = (x + 1) + (y * terrainWidth);             //was lower
int lowerLeft = x + ((y + 1) * terrainWidth);            // was top
int lowerRight = (x + 1) + ((y + 1) * terrainWidth);     //was top

```

And thus draws the triangles exactly as they should appear. Since the lower left was marked as the upper left, etc., the triangles were being formed upside down.
> 1 votes

---
Tags: xna-4.0, terrain, terrain-rendering, heightmap
---


# Question
Title: Tower defense endless levels logic sprite kit
I am making a tower defense game for iOS using Sprite Kit. I would like for my game to support an endless number of levels, like in Bloons TD 5. What approach should I take to implement this?

# Answer
By "endless levels" do you mean that there is no limit to the number of waves i.e. the waves keep coming until game-over?

If so then you need to develop an algorithm that takes the wave number as an input and returns an set of enemies suitable for that wave.

The most trivial of these would be to take the wave number and return a number of enemies or as peudocode:

```
function CreateWave(waveNumber)
    enemyList = new list
    for i = 1 to (waveNumer * 5)
       enemyList.add(grunt)
    return enemyList

```

A more interesting approach would be to determine a difficulty rating for the wave, and a difficulty rating for each enemy type. Then you could add different enemies to the `enemyList` until you have reached the desired difficulty.
> 1 votes

---
Tags: ios, iphone, cocos2d-iphone, objective-c, architecture
---


# Question
Title: How do we enable the swapping of function definitions, at runtime?
I am developing a cross-platform game-engine with a friend, using C++, OpenGL 2 and 4, and some other low level API provided by the platform. Recently, we had an idea to adapt function definition at runtime. For example, Machine 1 provides only OpenGL 2; the engine will see that, and use only OpenGL 2 functions. Machine 2 provides OpenGl 4 ,as well, so the engine will use OpenGL 4, instead.

Our problem with this is the implementation, and how we should approach it. On first thought, we decided to use function pointers, but after trying for a bit, it led us into problems with the code. The code was hard to understand, and hard to both fix and extend. The second approach we thought about was to replace the .DLL (Windows) or .SO (Linux) file (or hot swapping). So far, we can not implement a working, stable build.

How do we enable the swapping of function definitions, at runtime?

# Answer
A common approach is to write separate renderers or renderers with "feature gates."

That is, you can make separate files for each API (GraphicsGL2.cpp, GraphicsGL4.cpp, etc.). You can then make some kind of `IRenderer` interface each implements or you can simply have one header and conditionally compile the renderer .cpp files for each platform (compile-time static polymorphism of a kind).

Alternatively, if you're sticking with one API family (GL), then you would have code like so in your renderer:

```
draw():
  begin_frame()

  if has_instancing:
    draw_instanced()
  else:
    draw_batched()

  end_frame()

```

You could use function pointers as well as set them up during initialization.

Yes, this can be messy. That is one of the many "joys" of using OpenGL. After having to select the right version, find extensions, and work around the myriad of vendor bugs you end up with a hodge-podge of code.

Using shared libraries offers little benefit over just embedding the different renderers, assuming you again are sticking to one API family.

If you end up using completely different APIs (Direct3D vs OpenGL vs GL|ES etc.) then your best bet is the compilation method I first mentioned. There's zero reason to use OpenGL on Windows if you already have D3D, you need a very specific implementation of GL for OSX, mobile platforms need GL|ES, and Linux needs to be kept at an old low-level version of GL if you want to support the standard FOSS drivers.

If you're looking to maximize portability with the least amount of code then write everything with GL|ES (which is compatible with sufficiently new versions of desktop GL for the most part, given the `ARB_es2_compatibility` and `ARB_es3_compatibility`) and don't worry too much about fallbacks to old versions (and hence limit your conditional code to the narrowest cases).
> 4 votes

---
Tags: architecture, software-engineering
---


# Question
Title: JOGL runs extremely slow from a jar file on other machines.
I am currently messing around with JOGL and JBullet, with some success. I'd like to share what I've created with my friends. I created a jar file and a .bat to open it with the argument -Dsun.java2d.noddraw=true. The jar runs perfectly on my machine. It opens and runs on my friends system and my laptop, but at an **extremely** low frame rate. What is the cause of this and how can I fix it?

Also for some reason it loads the wrong textures for an object, again only when ran on another system. They are both Windows 8.1 x64 systems. The graphics drivers of all systems are up to date as well. This is really disconcerting because i want to be able to distribute this program, even if only amongst friends. .

# Answer
> 0 votes
The problem was using GLJpanel as opposed to using GLCanvas. GLJpanel is lightweight and doest support the complexity as does GLCanvas.

# Answer
> 0 votes
Check the specifications of each machine. Even brand matters here. Update all the drivers , Java , use the latest versions of your libraries. Do some benchmarking tests. Check for any overclock settings , sometimes it may be hard to find out. Check out the temperatures(including coolers and case ventilation). Check out any 3rd party software used to accelerate stuff (indeed , some of them work). Check out the antivirus software , it can cause trouble too . Check out the OS , (even the small updates) , finally , be sure that there are no other processes running (than the basic ones.)

Check again drivers and OS , it may be not what you think.

---
Tags: java, performance, jogl
---


title: game maker stop overlapping buildings

text:
# Question
Title: game maker stop overlapping buildings
I'm trying to make a game with real time strategy elements, where you can build several different buildings.

The problem is that I can't seem to make the buildings stop overlapping. That is too say, if try to build while my mouse is hovering over a building, it won't build, which is good.

But the moment that my mouse is no longer over a building, I can build again. And since the buildings have a centered origin, the building is build around the coordinates where the mouse is. This causes overlap between buildings, which is bad.

I have the following code in a step event of a control object:

```
if (mouse_check_button_pressed(mb_left)) {
  if (!position_meeting(mouse_x, mouse_y, all)) {
      instance_create(mouse_x, mouse_y, obj_shed);
      player_money -= 100;
  }
}

```

Any help would be greatly appreciated.

EDIT: The code now follows the suggestions of Despicable and looks as follows:

```
var object, width, height;
object = obj_shed; //Change to your desired object
w = object.sprite_width;
h = object.sprite_height;

if (mouse_check_button_pressed(mb_left)) {
  if (!collision_rectangle(mouse_x-w/2,mouse_x+w/2,mouse_y-h/2,mouse_y+h/2,all,0,1)){
    instance_create(mouse_x,mouse_y,obj_shed);
    player_money -= 100;
  }
}

```

However, w and h give an error, so now i need to find a way how to get the width and heigh of an object that is not the calling instance (because the calling instance is a control object, in which is code is situated)

EDIT: Solution

I was able to change the solution so that the buildings won't overlap, even if the buildings aren't circular:

In the control object, in the step event, write the following:

```
if (mouse_check_button_pressed(mb_left)) {
      instance_create(mouse_x, mouse_y, obj_shed);
}

```

And in the create event of your building (shed in my case):

```
if (!place_meeting(mouse_x, mouse_y, all)) {
      global.player_money -= 100;
}
else {
    instance_destroy();
}

```

So on creation of the building, it checks if there is a collision. If so, it destroys itself. If not, it stays there and deducts the cost of the building. This works with any shape of building.

# Answer
I'll assume that all the buildings occupy space in rectangular shape.

Instead of checking if the mouse is hovering over other buildings, you can check if the building supposed to be built collapses with any other existing buildings at the position of the mouse cursor. So this...

```
if (mouse_check_button_pressed(mb_left))
{
    if (!collision_rectangle(mouse_x-w/2,mouse_x+w/2,mouse_y-h/2,mouse_y+h/2,all,0,1)
    {
        instance_create(mouse_x,mouse_y,obj_shed);
        player_money -= 100;
    }
}

```

where **w** and **h** are the width and the height of the space building occupies, should work.

Note that you must have the mask of the building sprites set correctly, but unless you've changed something there, it should all just be fine.

Read more about the `collision_rectangle()` function in the documentation.
> 3 votes

---
Tags: rts, game-maker
---


# Question
Title: How to handle simultaneous mouse and keyboard input with sdl?
I'm making a game in SDL2 that so far is basically just a top down shooter, where the player aims at the mouse. When I run the game, you can move properly and shoot properly, and shoot and move the mouse at the same time properly, but you cannot shoot while moving. For example, if I'm using the gatling gun which is fully automatic (as long as I hold the mouse down it keeps on shooting), and I start shooting, then press the w key to move, it stops shooting right away, and doesn't start again until I click again. Here is my code:

```
void Main::handleInput2(void)
{
double xcomponent,ycomponent,xVel,yVel,angle;
SDL_GetMouseState(&mouseX,&mouseY);
xcomponent = mouseX - (player.getBarrelX() + xOffset);
ycomponent = mouseY - (player.getBarrelY() + yOffset);
angle = atan2(ycomponent,xcomponent);
xVel = cos(angle);
yVel = sin(angle);

if(screen->getEvent()->type == SDL_KEYDOWN)
{
    if(screen->getEvent()->key.keysym.sym == SDLK_a)
    {
        player.setVelX(-1 * player.getSpeed());
    }
    if(screen->getEvent()->key.keysym.sym == SDLK_d)
    {
        player.setVelX(player.getSpeed());
    }
    if(screen->getEvent()->key.keysym.sym == SDLK_w)
    {
        player.setVelY(-1 * player.getSpeed());
    }
    if(screen->getEvent()->key.keysym.sym == SDLK_s)
    {
        player.setVelY(player.getSpeed());
    }
}
if(screen->getEvent()->type == SDL_KEYUP){
    //if(screen->getEvent()->key.keysym.sym = SDLK_8) player.setVelocity(-2,-2); TEST PASSED
    if(screen->getEvent()->key.keysym.sym == SDLK_a)
    {
        player.setVelX(0);
    }
    if(screen->getEvent()->key.keysym.sym == SDLK_d)
    {
        player.setVelX(0);
    }
    if(screen->getEvent()->key.keysym.sym == SDLK_w)
    {
        player.setVelY(0);
    }
    if(screen->getEvent()->key.keysym.sym == SDLK_s)
    {
        player.setVelY(0);
    }
    if(screen->getEvent()->key.keysym.sym == SDLK_1) //Paintball Gun
    {
        player.setWeapon(0);
    }
    if(screen->getEvent()->key.keysym.sym == SDLK_0) //Glock
    {
        player.setWeapon(1);
    }
    if(screen->getEvent()->key.keysym.sym == SDLK_2) //Skorpion
    {
        player.setWeapon(2);
    }
    if(screen->getEvent()->key.keysym.sym == SDLK_3) //Ballistic Knife
    {
        player.setWeapon(5);
    }
    if(screen->getEvent()->key.keysym.sym == SDLK_4) //Spas 12
    {
        player.setWeapon(4);
    }
    if(screen->getEvent()->key.keysym.sym == SDLK_5)
    {
        player.setWeapon(3);
    }
}
if(screen->getEvent()->type == SDL_MOUSEBUTTONDOWN || screen->getEvent()->type == SDL_MOUSEMOTION&SDL_MOUSEBUTTONDOWN)
{
    if(screen->getEvent()->button.button == 1)
    {
        player.Shoot(1,xVel,yVel,screen);
    }
    if(screen->getEvent()->button.button == 3)
    {
        player.Shoot(3,xVel,yVel,screen);
    }
}
}

```

This was originally all in switch statements, but I thought it might work in if statements. I also tried handling SDL\_KEYDOWN and SDL\_MOUSEDOWN the same way as I did with SDL\_MOUSEDOWN and SDL\_MOUSEMOTION. I tried stuff like

```
if(screen->getEvent()->type == SDL_KEYDOWN|SDL_MOUSEDOWN)
{
    ...
}

if(screen->getEvent()->type == SDL_MOUSEDOWN|SDL_KEYDOWN)
{
    ...
}

if(screen->getEvent()->type == SDL_MOUSEDOWN&SDL_KEYDOWN)
{
    ...
}

if(screen->getEvent()->type == SDL_KEYDOWN&SDL_MOUSEDOWN)
{
    ...
}

```

But none of those helped, each one in fact made it worse. Seeing as that SDL is meant for making games, I would imagine there must be a way around this. Does anyone know how?

# Answer
> 3 votes
SDL events are *events*. They are fired in response to the user doing something, not fired continuously. The mouse down event is only called when the button is first pressed. The key down events are only called when a key is pressed down. They keydown events *may* get repeatedly called if you have key repeat enabled (which exists to easily simulate the behavior you get in most text-oriented input interfaces). This will never happen with the mouse down event, however.

In particular, this kind of thing can never ever happen:

```
screen->getEvent()->type == SDL_MOUSEDOWN&SDL_KEYDOWN

```

Each event is only one kind of event. Either it's a key down event or it's a mouse down event. It cannot be both. If the player does both in the same frame then you will get two separate events.

You need to query the state of the input devices rather than rely on events or use the events to manage your own state data. A key being pushed down has nothing to do with whether the mouse was pressed, released, or held, and vice versa. Likewise there is no event for "still being held down."

You can set some flag to `true` when you get a key/mouse down event and then set it to `false` when you get the appropriate key/mouse up event. Use the event handling only for managing these flags. Then in a separate piece of code set movement and firing based on the state of those flags. Or you can use the state in SDL using things like `SDL_GetKeyboardState` or `SDL_GetMouseState`.

---
Tags: c++, sdl, input, mouse
---


# Question
Title: need help in implementing KeyListener for 2D game in Java
i stated coding my first game in java, i need some help in imlementing KeyListener to fit my game. after some search in tutorials i've imlemented it like this :

```
frame.addKeyListener(new KeyAdapter(){

private boolean[] keys = new boolean[120];
public boolean up , down , left , right;

public void tick() {
    up =  keys[KeyEvent.VK_UP] || keys[KeyEvent.VK_W];
    down =  keys[KeyEvent.VK_DOWN] || keys[KeyEvent.VK_S];
    left =  keys[KeyEvent.VK_LEFT] || keys[KeyEvent.VK_A];
    right =  keys[KeyEvent.VK_RIGHT] || keys[KeyEvent.VK_D];
}

public void keyPressed(KeyEvent e) {
    if(e.getKeyCode() != KeyEvent.VK_F5) keys[e.getKeyCode()] = true;
    tick();
    if (up){
        yMap+=4;
        direction='n';
        xInd=0;
    }
    else if(down){
        yMap-=4;
        direction='s';
        xInd=2;
    }
    else if(right){
        xMap-=4;
        direction='e';
        xInd=1;
    }
    else if(left){
        xMap+=4;
        direction='w';
        xInd=3;
    }
    wait++;
    if(wait==5){
        yInd++;
        wait=0;
    }
    if(yInd==3)
        yInd=0;
    cha=sprites[xInd][yInd];
    panel.repaint();
}

public void keyReleased(KeyEvent e) {
    keys[e.getKeyCode()] = false;
    tick();
    yInd=0;
    cha=sprites[xInd][yInd];
    panel.repaint();
}

public void keyTyped(KeyEvent e) {
}
});

```

however every thing is fine in this code, the character is moving correctly the sprites are perfect but it is missing only one thing, the only thing i need is when i move the character in a direction, lets say for exemple UP, with a simple click on the up button (which normaly should make it move with only 4 pixels to up), the character should complete walking to the next square automaticaly (each square is 32\*32 pixels). i hope i explained well my question and sorry for bad english !

# Answer
> 1 votes
Do not put your movement code in the key event handler. The event is fired once, when the key is pressed or released. If you want to continually move you need to put your actual movement code somewhere outside of the key event handler, presumably in your `update` method (or some idle function handler that is called every frame).

---
Tags: java
---


# Question
Title: How to draw many identical quads in WebGL efficiently?
I have recently been trying to develop a more basic one of those 'falling sand'/'powder game' style games (See here) the past few months, and after prototyping on a plain canvas, then trying PIXI.js, I decided to try and roll my own WebGL based solution so I could control the whole pipeline.

Currently I am just iterating over a 2D array representing the pixels of the canvas (500x500) then calling glDrawElements to draw a pixel sized quad at a specified location. Obviously things get pretty heavy pretty quickly in a game like this, and the frame rate drops to unusable very quickly.

I can't find examples online of drawing batches of quads in different locations with one DrawElements call in OpenGLES/WebGl, as there is no instancing support, but people seem to mention having done it. Can anyone give any pointers?

Here is my extremely simple vertex shader:

```
attribute vec2 position;

uniform mat3 modelViewProjectionMatrix;

void main() {
    gl_Position = vec4(modelViewProjectionMatrix * vec3(position, 1.0), 1.0);
}

```

And here is my relevant rendering code Javascript side:

```
this.setSandBuffers();
material = this.materials.sand;
this.gl.vertexAttribPointer(this.positionAttribute, 2, this.gl.FLOAT, false, 0, 0);
this.gl.uniform4fv(this.uColor, material.uColor);

for (var x = 0; x < this.grid.length; x++) {
    for (var y = 0; y < this.grid[x].length; y++) {
        var cell = this.grid[x][y];

        switch(cell) {
            case 0:
                break;
            case 1:

                this.mvTranslate(x, y);

                mvpMatrix = matrixMultiply(this.modelViewMatrix, this.projectionMatrix);

                this.gl.uniformMatrix3fv(this.uModelViewProjectionMatrix, false, mvpMatrix);

                this.gl.drawElements(this.gl.TRIANGLE_STRIP, 4, this.gl.UNSIGNED_SHORT, 0);

                break;
            default:
                break;
        }
    }
}

```

Any other relevant code is here.

Thanks

# Answer
An individual draw call per quad is not a good idea.

Try putting all the quads into a Float32Array, and issuing one draw call. Something like this, assuming the vertex data only contains 2D positions:

```
var vertices = new Float32Array(500 * 500 * 2 * 6);
var count = 0;

for (var x = 0; x < this.grid.length; x++)
{
    for (var y = 0; y < this.grid[x].length; y++)
    {
        var cell = this.grid[x][y];

        switch(cell)
        {
            case 1:
                var offset = count * 2 * 6;
                vertices[offset + 0] = x;
                vertices[offset + 1] = y;
                vertices[offset + 2] = x + 1;
                vertices[offset + 3] = y;
                vertices[offset + 4] = x;
                vertices[offset + 5] = y + 1;

                vertices[offset + 6] = x;
                vertices[offset + 7] = y + 1;
                vertices[offset + 8] = x + 1;
                vertices[offset + 9] = y;
                vertices[offset + 10] = x + 1;
                vertices[offset + 11] = y + 1;

                count++;
                break;

            default:
                break;
        }
    }
}

gl.enableVertexAttribArray(position);
gl.vertexAttribPointer(position, 2, gl.FLOAT, false, 16, 0);
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
gl.drawArrays(gl.TRIANGLES, 0, count * 6);

```
> 1 votes

---
Tags: javascript, html5, html-canvas, webgl
---


# Question
Title: A Sensor’s ContactList Keeps Old / Ignores New Contacts, When That Contact Is still
Okay this is a hard one to explain so I’ll try my best.

Basically every time my enemy class updates, it runs a SightCone Sensor Contact List test, so this is every single frame it checks for all the possible contacts in it’s sensor.

What I’m finding is that if I’m moving my player character around, the contact list updates perfectly, when the player is in the enemy’s sight, it’s true, when it is out of sight its false,

However if I keep my player still, The contact list always ignores it.

Here is a video showing the behaviour. (the true and false flag is in the top left.)

Here is the code I have. Basically in the Enemy’s update method I run the check (the sightcone is a supplemental body within the enemy class that follows the position and rotation of the enemy body every frame.)

```
List<Body> coneClip = GetBodiesInContactWithBody(SightCone.Body);

private List<Body> GetBodiesInContactWithBody(Body body)
        {
            var bodiesInContact = new List<Body>();
            var c = body.ContactList;
            while (c != null && c.Next != null)
            {
                if (c.Contact.IsTouching)
                {
                    bodiesInContact.Add(c.Other);
                }
                c = c.Next;
            }
            return bodiesInContact;
        }

```

I am not sure why this is happening. I don’t know why the contact list isn’t seeing the player, even though the body is still, it still exists, has a shape and position, and 100% exists in the physics world.

Truly hope you can help.

# Answer
> 2 votes
This was solved by setting my body's IsSleepingAllowed variable to false. So the body stays active even when totally still.

Thanks for the help Mr Andrew Russell.

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


# Question
Title: How do you do FlashPunk-style animation in libGDX?
In FlashPunk, you can have multiple animations set, and then choose which one to play at any time, and it'll do it.

Example: animatedSprite.add("running", \[0, 1, 2, 3\], 50); animatedSprite.add("falling", \[4, 4, 4, 5, 1\], 50); animatedSprite.play("running");

How do you accomplish this in libGDX?

I can only make it play one animation, looping, and I have no idea how to add multiple.

# Answer
I don't think you can do it out of the box with libGDX.

I don't know how you structure your game but personally i would simply load all the animations for a particular sprites has `Animation` instance and store them in a map where i associate a name to each one of them.

So basically:

```
Map<String, Animation> animations = new Map<>();
animations.put("walk", /*...*/);
animations.put("run", /*...*/);

```

And then just write a simple method that takes the name of animation, fetch the corresponding in the animations map and set this animation as the current animation.

```
public void play(String name) {
    this._currentAnimation = animations.get(name);
}

```

Then in your rendering method, you just need to refer to the `_currentAnimation` field of your `Sprite` class or whatever and play this animation as explained here.

EDIT: libGDX provides create tools for game development but sometimes you'll need to write some higher level code that wraps libGDX concepts to do what you want. libGDX is not a game engine, it's a framework, this way, it provides a lot of flexibility on how you want to implement things.
> 2 votes

---
Tags: 2d, animation, libgdx
---


# Question
Title: Why do I get 'Input Assembler: "No mesh available for stage"' error?
My question is basically why VS2012 tells me that there is no mesh available for the Input Assembler stage because if I click on the DeviceContext next to the Draw call in the Grahics Event List the Input layout is set correctly, the vertex buffers, too, the index buffer is `NULL` as I do not call DrawIndexed and the primitive topology is set correctly. My background color is drawn using `g_pImmediateContext->ClearRenderTargetView( g_pRenderTargetView, Colors::MidnightBlue );`. Only the mesh does not appear. What did I miss?

If anything maybe this file which can be opened using VS2012 may help, it is the ~~Graphics Experiment.vsglog file~~ <sup>(*link no longer available*)</sup>.

Here is my InputLayout struct:

```
struct VERTEXPOSITIONCOLOR
{
    DirectX::XMFLOAT3   position;
    DirectX::XMFLOAT4   color;

    static D3D11_INPUT_ELEMENT_DESC* GetVertexLayout()
    {
        static D3D11_INPUT_ELEMENT_DESC layout[] =
        {
            { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT,
                0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
            { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT,
                0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
        };
        return layout;
    }

    static UINT GetNumElements(){ return 2; }
};

```

# Answer
> 1 votes
From looking at your (no longer available) vslog it would appear you have the first and second parameter in your draw call mixed up as it says `Draw(0, 3)`.

The first parameter is the vertex count and the second parameter is the start offset. See the documentation about ID3D11DeviceContext::Draw method.

---
Tags: directx11, visual-studio
---


# Question
Title: Farseer: How can I calculate the needed velocity in this case?
I have two platforms and one ball. The ball should fly from the red platform to the blue platform. The ball should land somewhere in the purple rectangle of the blue platform.

How can I know how fast the linear velocity of the ball should be to accomplish the jump of the ball? Is there a mathematical formula to calculate the linear velocity(x,y) which should be added to the ball so that the ball can jump to the blue platform?

The ball should always land in the purple area.

Distance(width) from the ball to the target: 212 pixel

Distance(height) from the ball to the target: 52 pixel

The distances were measured from the center of the ball to the center of the purple rectangle.

The gravitation of my world is world(0,3).

**Upadte** I use the following formula for the impulse:

> impulse = Vector2(distance.x / time * mass + gravity.x / 2 * time * mass, distance.y / time * mass + gravity.y / 2 * time * mass);

mass: mass of the ball

It's working with this formula, but only if the value of the time is not too low. time = 2.0f(or higher) is working but if I use time = 1.0f, then the ball is touching the left side of the blue platform.

Why is the formula not working with low time values? I don't understand that.

# Answer
> -1 votes
**Short answer:**

```
impulse = (gravity * time*time + distance * 2.0) / (time * 2.0);

```

(or optimized for the specific numbers you asked for)

```
impulse = Vector2(212.0/time, 52.0/time + 1.5*time);

```

(although, I think maybe you wanted this one that accounts for gravity but can be used to calculate any possible jump)

```
impulse = Vector2(distance.x/time, distance.y/time + 1.5*time);

```

---

**Long answer:** *(pre-calculus required)*

First express your problem mathematically:

Integrate to find that:

Solving this for impulse yields:

Which is our answer, notice that time is still unknown in this system. This means there are infinite trajectories that will land on the purple rectangle. You have to decide how long it should take.

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