title: Texture Stretching on VBO cube

text:
# Question
Title: Texture Stretching on VBO cube
I'm using JOGL and I'm trying to render a textured VBO cube with glDrawArrays. The cube renders, but the texture is stretched and stripy as seen in the picture above.

It seams that changing my texture coordinate array has no effect, and perhaps the same with my shaders, I couldn't really tell.

I've tried using different methods for my texture coordinate pointers and switching up the parameters in glBufferData but to no avail.

The biggest difference is when I mess with my texture pointer parameters (glTexCoordPointer()). When I change those numbers, the streaks go in different directions, but I have yet to find any reason behind it, and I'm not sure if more fussing with that will solve my problem

EDIT: I'm pretty sure that I am establishing my uniforms wrongly. My problem is that I don't know what I should set them too. I was previously using immediate mode for lighting and materials. Also, possibly because my uniforms are wrong, I can't bind the shaders correctly (or what I think is correct) without the program crashing.

initVBO is called once, and drawCubeVBO is called every frame

```
public void loadTexture(GL2 gl) {
    // Load texture from image
    try {
        // Create a OpenGL Texture object from (URL, mipmap, file suffix)
        // Use URL so that can read from JAR and disk file.
        texture = TextureIO.newTexture(getClass().getClassLoader()
                .getResource(textureFileName), // relative to project root
                false, textureFileType);

        texture.setTexParameteri(gl, GL2.GL_TEXTURE_MIN_FILTER,
                GL2.GL_LINEAR);
        texture.setTexParameteri(gl, GL2.GL_TEXTURE_MAG_FILTER,
                GL2.GL_LINEAR);
        texture.setTexParameteri(gl, GL2.GL_TEXTURE_WRAP_S,
                GL2.GL_CLAMP_TO_EDGE);
        texture.setTexParameteri(gl, GL2.GL_TEXTURE_WRAP_T,
                GL2.GL_CLAMP_TO_EDGE);

        // Texture image flips vertically. Shall use TextureCoords class to
        // retrieve
        // the top, bottom, left and right coordinates, instead of using
        // 0.0f and 1.0f.
        TextureCoords textureCoords = texture.getImageTexCoords();

        textureTop = textureCoords.top();
        textureBottom = textureCoords.bottom();
        textureLeft = textureCoords.left();
        textureRight = textureCoords.right();

        } catch (GLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private FloatBuffer vertices;
    // private ShortBuffer indices;
    private int VBOVertices;
    // private int VBOIndices;
    float x = 1f; // the length/width/height of the cube

    public void initVBO(GL2 gl, String textureFileName, String textureFileType) {

        // cube
        // ///////////////////////////////////////////////////////////////////////
        // v6----- v5
        // / |      /|
        // v1------v0|
        // | |     | |
        // | |v7---|-|v4
        // |/      |/
        // v2------v3

        // vertex coords array for glDrawArrays()
        // =====================================
        // A cube has 6 sides and each side has 2 triangles, therefore, a cube
        // consists
        // of 36 vertices (6 sides * 2 tris * 3 vertices = 36 vertices). And,
        // each
        // vertex is 3 components (x,y,z) of floats, therefore, the size of
        // vertex
        // array is 108 floats (36 * 3 = 108).

        float[] vertexArray = {
                x, x, x, -x, x, x, -x, -x, x, // v0-v1-v2 (front)
                -x, -x, x, x, -x, x, x, x, x, // v2-v3-v0

                x, x, x, x, -x, x, x, -x, -x, // v0-v3-v4 (right)
                x, -x, -x, x, x, -x, x, x, x, // v4-v5-v0

                x, x, x, x, x, -x, -x, x, -x, // v0-v5-v6 (top)
                -x, x, -x, -x, x, x, x, x, x, // v6-v1-v0

                -x, x, x, -x, x, -x, -x, -x, -x, // v1-v6-v7 (left)
                -x, -x, -x, -x, -x, x, -x, x, x, // v7-v2-v1

                -x, -x, -x, x, -x, -x, x, -x, x, // v7-v4-v3 (bottom)
                x, -x, x, -x, -x, x, -x, -x, -x, // v3-v2-v7

                x, -x, -x, -x, -x, -x, -x, x, -x, // v4-v7-v6 (back)
                -x, x, -x, x, x, -x, x, -x, -x }; // v6-v5-v4

        vertices = Buffers.newDirectFloatBuffer(vertexArray.length);
        vertices.put(vertexArray);
        vertices.flip();

        this.textureFileName = textureFileName;
        this.textureFileType = textureFileType;
        loadTexture(gl);
        texture.enable(gl);
        gl.glEnable(GL2.GL_TEXTURE_2D);

        float[] textureArray = { 0, 0, 1, 0, 0, 1,

        1, 1, 1, 0, 0, 1 };

        FloatBuffer textureData = Buffers.newDirectFloatBuffer(12);
        // textureData.put(textureTop);
        // textureData.put(textureBottom);
        // textureData.put(textureRight);
        // textureData.put(textureLeft);
        textureData.put(textureArray);
        // textureData.order();
        textureData.flip();

        int[] temp = new int[4];
        gl.glGenBuffers(3, temp, 0);

        VBOVertices = temp[0];
        gl.glBindBuffer(GL.GL_ARRAY_BUFFER, VBOVertices);
        gl.glBufferData(GL.GL_ARRAY_BUFFER, vertices.capacity()
                * Buffers.SIZEOF_FLOAT, vertices, GL.GL_STATIC_DRAW);
        gl.glBindBuffer(GL.GL_ARRAY_BUFFER, 0);

        vboTextureCoordHandle = temp[2];
        gl.glBindBuffer(GL.GL_ARRAY_BUFFER, vboTextureCoordHandle);
        gl.glBufferData(GL.GL_ARRAY_BUFFER, 4, textureData, GL.GL_STATIC_DRAW);
        gl.glBindBuffer(GL.GL_ARRAY_BUFFER, 0);

        shader = new Shader(gl);
        shader.bind(gl);
        shader.attachVertexShader(gl);
        shader.attachFragmentShader(gl);
        shader.link(gl);
        // shader.unbind(gl);

        // setting the uniform
        shader.setUniform(gl, "texUnit", 0);
        shader.setUniform(gl, "Material", 1, 1, 1);
        shader.setUniform(gl, "Lights", 2);

        // activating textures
        gl.glActiveTexture(GL2.GL_TEXTURE0);
        texture.bind(gl);
        // gl.glBindTexture(GL.GL_TEXTURE_2D, GL.GL_TEXTURE0);

    }

    public void drawCubeVBO(GL2 gl, String textureFileName,
            String textureFileType) {

        // shader.bind(gl);

        // initializing textures

        // this.textureFileName = textureFileName;
        // this.textureFileType = textureFileType;
        // loadTexture(gl);
        // texture.enable(gl);
        // gl.glEnable(GL.GL_TEXTURE_2D);

        // drawing

        /* Setup Position Pointer */
        gl.glBindBuffer(GL.GL_ARRAY_BUFFER, VBOVertices);
        gl.glVertexPointer(3, GL.GL_FLOAT, 0, 0);

        /* Setup Texture Coordinate Pointer */
        gl.glBindBuffer(GL.GL_TEXTURE0, vboTextureCoordHandle);
        gl.glTexCoordPointer(3, GL.GL_FLOAT, 0, 0);

        // unbind the VBO
        gl.glBindBuffer(GL.GL_ARRAY_BUFFER, 0);

        // actual drawing
        // gl.glBindBuffer(GL.GL_ARRAY_BUFFER, VBOVertices);
        gl.glEnableClientState(GL2.GL_VERTEX_ARRAY);
        gl.glEnableClientState(GL2.GL_TEXTURE_COORD_ARRAY);

        gl.glDrawArrays(GL.GL_TRIANGLES, 0, vertices.capacity());

        gl.glDisableClientState(GL2.GL_TEXTURE_COORD_ARRAY);
        gl.glDisableClientState(GL2.GL_VERTEX_ARRAY);

        // shader.unbind(gl);

    }
}

```

And my shaders:

```
private String vertexShaderString =
        "#version 330\n"+

        "layout (std140) uniform Matrices {\n"+
            "mat4 m_pvm;\n"+
            "mat4 m_viewModel;\n"+
            "mat3 m_normal;\n"+
        "};\n"+

        "layout (std140) uniform Lights {\n"+
            "vec3 l_dir;    // camera space\n"+
        "};\n"+

        "in vec4 position;   // local space\n"+
        "in vec3 normal;     // local space\n"+
        "in vec2 texCoord;\n"+

        // the data to be sent to the fragment shader
        "out Data {\n"+
            "vec3 normal;\n"+
            "vec4 eye;\n"+
            "vec2 texCoord;\n"+
        "} DataOut;\n"+

        "void main () {\n"+

            "DataOut.normal = normalize(m_normal * normal);\n"+
            "DataOut.eye = -(m_viewModel * position);\n"+
            "DataOut.texCoord = texCoord;\n"+

            "gl_Position = m_pvm * position; \n"+
        "}";

private String fragmentShaderString =
        "#version 330\n"+

        "layout (std140) uniform Material {\n"+
            "vec4 diffuse;\n"+
            "vec4 ambient;\n"+
            "vec4 specular;\n"+
            "float shininess;\n"+
        "};\n"+

        "layout (std140) uniform Lights {\n"+
            "vec3 l_dir;    // camera space\n"+
        "};\n"+

        "in Data {\n"+
            "vec3 normal;\n"+
            "vec4 eye;\n"+
            "vec2 texCoord;\n"+
        "} DataIn;\n"+

        "uniform sampler2D texUnit;\n"+

        "out vec4 colorOut;\n"+

        "void main() {\n"+

            // set the specular term to black
            "vec4 spec = vec4(0.0);\n"+

            // normalize both input vectors
            "vec3 n = normalize(DataIn.normal);\n"+
            "vec3 e = normalize(vec3(DataIn.eye));\n"+

            "float intensity = max(dot(n,l_dir), 0.0);\n"+

            // if the vertex is lit compute the specular color
            "if (intensity > 0.0) {\n"+
                // compute the half vector
                "vec3 h = normalize(l_dir + e);\n"+
                // compute the specular term into spec
                "float intSpec = max(dot(h,n), 0.0);\n"+
                "spec = specular * pow(intSpec,shininess);\n"+
            "}\n"+
            "vec4 texColor = texture(texUnit, DataIn.texCoord);\n"+
            "vec4 diffColor = intensity *  diffuse * texColor;\n"+
            "vec4 ambColor = ambient * texColor;\n"+

            "colorOut = max(diffColor + spec, ambColor);\n"+
        "}";

// ProgramID
int programID;

// Vertex Shader ID
int vertexShaderID;

// Fragment Shader ID
int fragmentShaderID;

public Shader(GL2ES2 gl) {
    programID = gl.glCreateProgram();
}

public void attachVertexShader(GL2ES2 gl) {

    // Create GPU shader handles
    // OpenGL ES retuns a index id to be stored for future reference.
    vertexShaderID = gl.glCreateShader(GL2ES2.GL_VERTEX_SHADER);

    // Load and compile the source
    String[] vlines = new String[] { vertexShaderString };
    int[] vlengths = new int[] { vlines[0].length() };
    gl.glShaderSource(vertexShaderID, vlines.length, vlines, vlengths, 0);
    gl.glCompileShader(vertexShaderID);

    //Check compile status for errors
    int[] compiled = new int[1];
    gl.glGetShaderiv(vertexShaderID, GL2ES2.GL_COMPILE_STATUS, compiled,0);
    if(compiled[0]!=0){System.out.println("Horray! vertex shader compiled");}
    else {
        int[] logLength = new int[1];
        gl.glGetShaderiv(vertexShaderID, GL2ES2.GL_INFO_LOG_LENGTH, logLength, 0);

        byte[] log = new byte[logLength[0]];
        gl.glGetShaderInfoLog(vertexShaderID, logLength[0], (int[])null, 0, log, 0);

        System.err.println("Error compiling the vertex shader: " + new String(log));
        System.exit(1);
    }

    //Attach Shader
    gl.glAttachShader(programID, vertexShaderID);
}

public void attachFragmentShader(GL2ES2 gl) {

    // Create GPU shader handles
    // OpenGL ES retuns a index id to be stored for future reference.
    fragmentShaderID = gl.glCreateShader(GL2ES2.GL_FRAGMENT_SHADER);

    // Load and compile the source
    String[] vlines = new String[] { fragmentShaderString };
    int[] vlengths = new int[] { vlines[0].length() };
    gl.glShaderSource(fragmentShaderID, vlines.length, vlines, vlengths, 0);
    gl.glCompileShader(fragmentShaderID);

    //Check compile status for errors
    int[] compiled = new int[1];
    gl.glGetShaderiv(fragmentShaderID, GL2ES2.GL_COMPILE_STATUS, compiled,0);
    if(compiled[0]!=0){System.out.println("Horray! fragment shader compiled");}
    else {
        int[] logLength = new int[1];
        gl.glGetShaderiv(fragmentShaderID, GL2ES2.GL_INFO_LOG_LENGTH, logLength, 0);

        byte[] log = new byte[logLength[0]];
        gl.glGetShaderInfoLog(fragmentShaderID, logLength[0], (int[])null, 0, log, 0);

        System.err.println("Error compiling the fragment shader: " + new String(log));
        System.exit(1);
    }

    //Attach Shader
    gl.glAttachShader(programID, fragmentShaderID);

}

public void link(GL2ES2 gl) {

    //link
    gl.glLinkProgram(programID);

    //check for errors
    int[] compiled = new int[1];
    gl.glGetProgramiv(programID, GL2ES2.GL_LINK_STATUS, compiled,0);
    if(compiled[0]!=0){System.out.println("Horray! Shader program linked!");}
    else {
        int[] logLength = new int[1];
        gl.glGetProgramiv(programID, GL2ES2.GL_INFO_LOG_LENGTH, logLength, 0);

        byte[] log = new byte[logLength[0]];
        gl.glGetProgramInfoLog(programID, logLength[0], (int[])null, 0, log, 0);

        System.err.println("Error linking the program: " + new String(log));
        System.exit(1);
    }

}

public void bind(GL2ES2 gl) {
    //Associate attribute ids with the attribute names inside
    //the vertex shader.
    gl.glBindAttribLocation(programID, 0, "attribute_Position");
    gl.glBindAttribLocation(programID, 1, "attribute_Color");

    gl.glUseProgram(programID);
}

public void unbind(GL2ES2 gl) {
    gl.glUseProgram(0);
}

/**
 * Sets the uniforms in this shader
 *
 * @param name    The name of the uniform
 * @param values  The values of the uniforms (Max 4)
 */
public void setUniform(GL2ES2 gl, String name, float... values)
{
    if (values.length > 4)
    {
        System.err.println("Uniforms cannot have more than 4 values");
        System.exit(1);
    }

    // Get the location of the uniform
    int location = gl.glGetUniformLocation(programID, name);

    // Set the uniform values
    switch (values.length)
    {
        case 1:
            gl.glUniform1f(location, values[0]);
            break;
        case 2:
            gl.glUniform2f(location, values[0], values[1]);
            break;
        case 3:
            gl.glUniform3f(location, values[0], values[1], values[2]);
            break;
        case 4:
            gl.glUniform4f(location, values[0], values[1], values[2], values[3]);
            break;
    }
}

public void dispose(GL2ES2 gl) {
    gl.glUseProgram(0);

    gl.glDetachShader(programID, vertexShaderID);
    gl.glDeleteShader(vertexShaderID);
    gl.glDetachShader(programID, fragmentShaderID);
    gl.glDeleteShader(fragmentShaderID);
    gl.glDeleteProgram(programID);
}

public int getID() {
    return programID;
}

```

# Answer
I didn't check thoroughly, but one major problem I see here is that you aren't following the OpenGL manual: This line of code is never valid:

```
gl.glBindBuffer(GL.GL_TEXTURE0, vboTextureCoordHandle);

```

You must use a valid buffer bind target, in this case GL\_ARRAY\_BUFFER. As it stands now, you're using your model coordinates as the texture coordinates also, because they are still the active array buffer when you call glTexCoordPointer.
> 0 votes

---
Tags: textures, shaders, vbo, jogl
---


title: LibGDX Images not loading

text:
# Question
Title: LibGDX Images not loading
Now my Image isn't loading to the screen. I tried to be decorative with the code but since it isn't working I made it just like the video I'm whatching. I don't get any exceptions, but the image doesn't appear still.

My main desktop launcher class:

```
public class DesktopLauncher {
public static void main (String[] arg) {
    LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
    config.title = " Game Tests ";
    config.width = 500;
    config.height = 400;
    config.useGL30 = true;

    new LwjglApplication(new MyGdxGame(), config);
}
}

```

My Game class:

```
public class MyGdxGame extends Game {

@SuppressWarnings("unused")
private TestScreenA GameScreen;

@Override
public void create () {
    //loads image
    AssetLoaderTest.load();
    GameScreen = new TestScreenA(this);

}

@Override
public void render () {

}
}

```

My Screen class:

```
public class TestScreenA implements Screen{

@SuppressWarnings("unused")
private MyGdxGame game;

//Camera
private OrthographicCamera camera;

//images etc.
private SpriteBatch batch;

public TestScreenA(MyGdxGame game) {
    this.game = game;

    //Camera
    camera = new OrthographicCamera();
    camera.setToOrtho(false, 1920, 1080);

    batch = new SpriteBatch();

}

public void render(float delta) {
    //clears the screen with white
    Gdx.gl.glClearColor(1F, 1F, 1F, 1F);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    camera.update();

    //loads images scaled to camera
    batch.setProjectionMatrix(camera.combined);

    batch.begin();
        batch.draw(AssetLoaderTest.s, 0, 0);
    batch.end();

}

public void resize(int width, int height) {

}

public void show() {

}

public void hide() {

}

public void pause() {

}

public void resume() {

}

public void dispose() {

}

}

```

My AssetLoaderTest class:

```
public class AssetLoaderTest {

//Images etc.

public static Texture t;
public static Sprite s;

static void load() {

    t = new Texture(Gdx.files.internal("testImgs/badlogic.jpg"));
    //Automatically scales texture based off of window size
    t.setFilter(TextureFilter.Linear, TextureFilter.Linear);
    //a sprite is pretty much the body and the texture is the texture or image of it
    s = new Sprite(t);
    s.flip(false, true);

}

}

```

# Answer
> 1 votes
Your `MyGdxGame` class' `render` method doesn't do anything. It should call `GameScreen.render()` to render.

Some comments about style:

* Variable names should be lower-case on their first letter (`gameScreen` not `GameScreen`)
* Please fix your formatting next time
* Suppressing warnings should be done carefully; they're usually indicative of a problem that may bite you.

If you use version control, which you should even if working alone, you can always commit frequently and roll back your changes when you break something -- if you used the LibGDX app maker JAR to make your project, you should have a good, working starting point.

# Answer
> 0 votes
Not sure, but something really seems odd to me in your code.

In your launcher you have :

```
config.useGL30 = true;

```

And then you are doing :

```
Gdx.gl.glClearColor(1F, 1F, 1F, 1F);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

```

But since you want to use GL30, you should probably do :

```
Gdx.gl30.glClearColor(1F, 1F, 1F, 1F);
Gdx.gl30.glClear(GL30.GL_COLOR_BUFFER_BIT);

```

As Gdx.gl is a shortcut to GDX.gl20.

---
Tags: java, libgdx, rendering
---


# Question
Title: equivalent texture function to texture2D in OpenGL-ES?
I'm trying to figure it out how can implement the same result using **texture2D**. The result expected is a luminescence operation but I couldn't replicate the same functionality using texture2D for iOS. could you explain a little bit what the **texture** function does with the 20.0 value?

```
float logAvgLum = exp(texture(hdrSampler, texCoord ,20.0).a) ;

```

# Answer
The 20.0 is the bias used to manipulate the mipmap level to read. The same parameter exists in OpenGL ES (see a description in the specs here: http://www.khronos.org/registry/gles/specs/2.0/GLSL\_ES\_Specification\_1.0.17.pdf page 71). Note that it is only available in the fragment shader as the derivatives used to calculate the mipmap level are the differences to the neighbouring pixels (of one 2 by 2 quad in case you want to google more details) and this just doesn't exist during the vertex shading stage. So at least in the fragment shader the code should also run on ES (by replacing texture with texture2D), do you try to run it in the vertex shader?
> 1 votes

---
Tags: ios, opengl-es
---


# Question
Title: What's the difference between Box2D and tweening?
It seems like Box2D can be used to move sprites across the screen, so how does this differ from tweening? Is it that Box2D is for physical collision detections and tweening is just animations?

# Answer
> 0 votes
Box2D is a physics library for 2d environments. Tweening is the process of gradually interpolating values.

Tweening itself is not fundamentally for animation, though it is widely used in animation for smooth transitions.

---
Tags: animation, box2d, tweening
---


title: multiple textures into one texture

text:
# Question
Title: multiple textures into one texture
Can i fusion multiple .tga or .jpeg into only one, and texturise my model with it ?

Here is an example to explain my self better : I have Mr Bowser as 3d model and i want to integrate it in a game. The thing is that all the textures, from the color of his mouth to the cones on his shell are held by different tga files. For the mouth i have mouth.tga as texture, for the cones on the shell i have cone.tga and so on... . But what i want to achieve is to have cone.tga mouth.tga and so on, in the same and only file. Like all the textures to make Mr angry Bowser a colorfull character concentrated in one and only file. Can i achieve that, is there a way to do it ?

Any help will be much appreciated. Thank you.

# Answer
> 4 votes
You absolutely can combine them! Many 3D games contain an image for the characters body and one for the head, and some combine the two for a single texture for the entire a model. Here's an example of a whole head's texture:

Also check out this PDF if you'd like to learn more about texture mapping in general.

---
Tags: textures, maps
---


title: WDDM Managing Memory in D3DPOOL_DEFAULT

text:
# Question
Title: WDDM Managing Memory in D3DPOOL_DEFAULT
In this question I saw that I was running out of memory in `D3DPOOL_DEFAULT` in DX9EX. After changing my usage from `D3DUSAGE_DYNAMIC` to `0` (static usage), everything runs wonderfully with no DX9 error.

At the point in my load process where I would previously get DX9's out of memory error, I now see system memory start to grow. So I assume that the WDDM is managing my textures.

So my question is, am I really seeing memory management here? I read about the WDDM in Copying and Accessing Resource Data (Direct3D 10), but I'm not sure that pertains to DX9EX. Wikipedia says: WDDM drivers allow video memory to be virtuallized and video data to be paged out of video memory into system RAM.

# Answer
Direct3D9Ex exposes the WDDM virtualized memory behavior, whereas Direct3D 9 on WDDM emulates the XPDM behavior. With Direct3D9Ex, you never get "Lost Device", but you can get "Device Removed".

"DYNAMIC" is a specific behavior which requires memory that is accessible by both the CPU and GPU that is in limited supply depending on your system setup, so you should definitely prefer to use "static" data wherever possible.

A lot of detail on this is covered in the talk "Why Your Windows Game Won't Run In 2,147,352,576 Bytes"
> 1 votes

---
Tags: directx9, resource-management
---


title: Direct3d Techniques and Windows 8

text:
# Question
Title: Direct3d Techniques and Windows 8
Under Windows 8, what is the alternative to this code:

```
technique11 Light0Tex
{
    pass P0
    {
        ...

technique11 Light1Tex
{
    pass P0
    {
        ...

```

And:

```
Light1Tech    = mFX->GetTechniqueByName("Light1");

...

Light1Tech->GetPassByIndex(p)->Apply(0, md3dImmediateContext);

```

# Answer
Effects 11 is not supported by Windows Store apps for Windows 8.0 because it requires D3DCompile APIs at runtime. Hence, 'technique11' and it's kin are deprecated.

Effects 11 also has specific compiler support in the HLSL compiler, which in the latest (#47) is still there but emits a warning. Some newer DX 11.1 and DX 11.2 constructs are not supported with the legacy fx\_5\_0 profile.

All that said, you can technically use Effects 11 in a Windows Store app for Windows 8.1 because D3DCompiler #47 is present at runtime. You can also continue to use Effects 11 for Win32 desktop apps as long as you recognize a future HLSL compiler revision is likely to remove support for the required fx\_5\_0 profile.

See the Effects 11 CodePlex project.
> 1 votes

---
Tags: shaders, directx11, graphic-effects, windows-8
---


title: Laser Beam End Points Problems

text:
# Question
Title: Laser Beam End Points Problems
I am building a game in XNA that features colored laser beams in 3D space.

The beams are defined as:

1. Segment start position
2. Segment end position
3. Line width

For rendering, I am using 3 quads:

1. Start point billboard
2. End point billboard
3. Middle section quad whose forward vector is the slope of the line and whose normal points to the camera

The problem is that using additive blending, the end points and middle section overlap, which looks quite jarring. However, I need the endpoints in case the laser is pointing towards the camera!

See the blue laser in particular:

# Answer
> 1 votes
I'm afraid there is no "correct" solution to this problem without using multipass rendering, which would probably be awfully slow.

What you can do is draw an oriented hemicircle in both ends. See the picture below:

This should give pretty good results overall. Where this approach fails is when the laser is pointing towards the camera, especially if the projection of the line is smaller than the radius of the circle. See the picture below for what would happen:

Even with this issue, this should be a better solution than the one you are currently using. There is no overdraw, yet there is still some effort to draw the end points the way you want.

# Answer
> 0 votes
You could use normalized vectors to check to see if the laser is pointing at the camera, and then only draw the end points if it is. If the angle allows you could stop drawing the mid section the instant it starts pointing at the camera and drawing the end section.

---
Tags: xna, blending, special-effects, billboarding
---


# Question
Title: Phaser/HTML5 - Trying to add five instances to a group and display on the screen!
just started using Phaser today after seeing Thomas Palef's lessmilk series. I completed PhotonStorm's "Make your first Phaser game" tutorial, and grabbed the skeleton, some CSS, and started to throw together a game. It's pretty barebones right now, but this is what I have.

The issue is that the game doesn't display the additional "orc" units I've requested. I used a `for` loop to throw five orcs around the map within the specified borders (32 pixels from the outside boundary. I even wrote a check for the `x` and `y` of each in the `Update()` function, but they don't appear at all.

I don't know how to move on from where I am, and I'm not sure that any of what I've written has been written the right way, you know what I'm saying? Thanks.

http://pastebin.com/if2VTq7j

# Answer
The issue is this part:

`if (band.x > game.world.width - 64 || band.x < 64 || band.y > game.world.height - 64 || band.y < 64)
 {
 band.x = game.world.width / 2;
 band.y = game.world.height / 2;
 }`

band is a Group. Groups are display objects in their own right, and their children (your orcs) are positioned relative to the x/y coordinates of the *Group*. Because your group starts out at x: 0, y: 0 it will fall foul of this check `(band.x < 64)` and be re-positioned to the middle of the game world, so all your orcs are now shifted off down to the bottom right of the screen and are forced "out of world".

I'm not sure what this part of your code is trying to actually achieve, but comment it out and you should at least see your orcs appear.
> 2 votes

---
Tags: javascript, html5, phaser
---


title: AI / Pathfinding gets stuck

text:
# Question
Title: AI / Pathfinding gets stuck
In my tile-based game, I'm using a A-star algorithm, which I have not written myself but I believe should be correctly implemented.

The problem I have is that the enemy AI can get stuck so that the enemy never gets any closer to the player.

Here's an ascii example of what I mean (x = enemy, p = player, . = ground):

```
....
x..p
....
....

```

Now, if I move the player down and process turn (which moves the enemy), the pathfinder finds the the next tile to be at south... and if I move the player up again, the pathfinder finds the next tile to be at north... so the enemy never gets any closer to the player (unless there are some obstacles, or I am closer to the enemy).

I feel stupid not to be able to figure this out on my own (at least in a nice way), but here we are. Is this a common problem, or am I doing something stupid?

# Answer
> 4 votes
Well according to the rules of the game, the AI is doing the right thing - moving towards the player every time! It's only due to a quirky situation that the player can "trap" the AI in a loop:

```
               Start    Player   AI        Player   AI
                        moves    moves     moves    moves
               ....     ....     ....     ....     ....
               x..p     x...     ....     ...p     x..p
               ....     ...p     x..p     x...     ....
               ....     ....     ....     ....     ....
AI distance:     3        4        3        4        3

```

This is because the AI has two equally valid moves to take, one of which leads to loops. You can fix this by using a different **heuristic**. Euclidean distance is a good one - a.k.a. straight line distance, as the crow flies - in this case it will move horizontally:

```
               Start    Player   AI         AI
                        moves    moves  or  moves
               ....     ....     ....       ....
               x..p     x...     ....       .x..
               ....     ...p     x..p       ...p
               ....     ....     ....       ....
Euclidean  :     3       3.2       3         2.2

```

Note that even with this heuristic, you can get stuck in loops eventually. It is up to you to decide what to do in this situation:

```
               Start    Player   AI        Player   AI
                        moves    moves     moves    moves
               ....     ....     ....     ....     ....
               .xp.     .x..     ..x.     ..x.     ....    ...
               ....     ..p.     ..p.     .p..     .px.
               ....     ....     ....     ....     ....

```

---
Tags: java, path-finding
---


title: Array of map data

text:
# Question
Title: Array of map data
I'm looking for your thoughts on the best way to store map data.

I need to store data for territory ownership for each pixel on the map. The data for each pixel is as such:

```
Player 1 points: 24
Player 2 points: 118
Player 3 points: 78

```

Currently I'm testing by using an array `int[width][height][3]` to store the points.

I'm then looping through it every update and re-rendering depending on the points.

```
for (int i=0; i < screenWidth; i++) {
    for (int j=0; j < screenHeight; j++) {
        //Do stuff with array[i][j][0]
        //Do stuff with array[i][j][1]
        //Do stuff with array[i][j][2]
    }
}

```

Iterating through a `[800][600][3]` array each render is expensive.

What is a better way to go about this?

# Answer
> 1 votes
If changes happen in an area, then you only need to update that area (rather than updating the entire map.) You could divide the array into an 80x60 array (I'll call them 'chunks'), each with 10x10x3, sections. With some basic data on who owns each larger section. So if the raising/lowering only happens in adjacent fields, and you know that all chunks surrounding this one chunk are composed of only allies, then you can skip the one chunk entirely. Skipping a 10\*10\*3 array would be 300 lines of array-access code you could skip entirely.

Or, if you felt like getting fancy, you could try to divide the array into a quadtree, to help manage which sections are updated and which aren't. The above concept is basically a simplified version of a quad-tree (not dynamic, and not self-dividing.)

---
Tags: java, libgdx, maps, data-structure
---


title: match 3 Shuffling

text:
# Question
Title: match 3 Shuffling
I'm interested in hearing about to implement similar functionality to Candy Crush's shuffling. I have an algorithm to determine if there are any matches available and if there aren't, I want to shuffle the board ensuring there aren't any matches immediately after reshuffling but there is at least one potential match. I have some ideas in mind but I'm interested to see if there are any more efficient ways of doing it.

Thanks

# Answer
### Check:

1. Loop over all tiles and check for matches (first loop over all rows horizontally and check for 3 in a row then check vertically same way).
2. If no matches found - shuffle, else - exit.

### Shuffle:

1. Make a list of all available items.
2. Loop over all positions, for each position assign a random item from the list ensuring that no condition is violated (in this case no match is made).
3. If you can´t find a valid item restart the algorithm.
4. Run the check algorithm for finding potential matches if none found rerun shuffle.
5. *(Optional)* If more than a certain number of shuffles have occurred clear the field and restart with different items.
> 1 votes

# Answer
I'm currently experimenting with a similar game-concept and what I do is the following:

1. Iterate through columns (vertical) and check for 3 consecutive items of the same type. If that occurs, replace the last item of the match with a random, but different item. If one item has been changed, set a `changed` flag.
2. Do the same for rows (horizontal). Also set the changed flag if any item was changed.
3. Repeat the above two steps as log as the `changed` flag is set.

This could also potentially result in lots of iterations but is quite unlikely. Certainly it will be more efficient than re-shuffling your whole board every time.

*Addendum*: Please don't refer to these kinds of games as "Candy Crush". Match-3 would be the neutral wording.. or "Bejeweled" if you have to use brand-names ;)
> 1 votes

---
Tags: algorithm
---


# Question
Title: Drawing tile images with bigger height on floor tiles on 2.5D isometric map
Hello I am creating my first isometric game. I have floor tiles **which are 112\*56** in size.

This is a simple strategy game I am making, it's an existing game, I just copied the idea for practice since I don't have anything else to do.

Each game object should be located inside the floor tile, like floor tile is the base, it can't be outside of it. All entities will be inside one floor tile, or separated.

When I try to place a rock in `tiles[0][1]`, this happens:

(source: gyazo.com)

When I try to place it at tiles\[9\]\[9\] (corner) this happens (With red borders, so you can see offsets):

(source: gyazo.com)

I am not really sure what creates this big padding when the tiles go further. The further they are, the bigger padding they will have from the tile I think.

I use this formula to locate tiles:

```
    int x = (this.x * width / 2) - (this.y * width / 2);
    int y = (this.x * height / 2) + (this.y * height / 2);

x = i
y = j

```

I've tried making offY variable, where it does `imageHeight - floorTileHeight = 18`, and then do `int y = offY - (... formula for y ...)` but no luck, the position is always randomised. Works for one position, won't work for further position.

this is the water floor tile (112x56):

this is the rock tile (112x74):

I've added red borders so you can see how big it is.

What is causing this padding between tiles when I place them?

# EDIT

I am using Slick2D game library.

# EDIT 2

In my program, my graphics are separated into Layers. Each layer implements Layer.

I have the layer Board, which is responsible about everything that happens on the board, the floor, it's entities, and nature objects.

That layer Board, has 2 more sub-layers in it, Nature and Entity.

Currently I am having problems with the Nature layer, which is responsible for drawing nature objects like Rocks, flowers, and more.

```
public class Nature implements Layer {

    private Tile[][] tiles = new Tile[15][10];

    public Nature() {
        tiles[9][9] = new Tile(9, 9, 0, 0, Tiles.ROCK);
//      tiles[0][0] = new Tile(0, -22, Tiles.ROCK);
//      tiles[0][1] = new Tile(0, -22, Tiles.ROCK);
    }

    @Override
    public void render(Graphics g) {
        for (int i = 0; i < this.tiles[0].length; i++){
            for (int j = 0; j < this.tiles[1].length; j++){
                Tile tile = this.tiles[i][j];

                if (tile == null)
                    continue;

                tile.render(g);
            }
        }
    }

    @Override
    public void update() {
        // TODO Auto-generated method stub

    }

}

```

The actual tile class which does the drawing:

```
public class Tile {

    private int offX;
    private int offY;

    private int x;
    private int y;

    public TileSprite sprite;

    public Tile(int x, int y, Tiles tile) {
        this(x, y, 0, 0, tile);
    }

    public Tile(int x, int y, int offX, int offY, Tiles tile) {
        this.x = x;
        this.y = y;
        this.offX = offX;
        this.offY = offY;
        this.sprite = new TileSprite(tile);
    }

    public int getOffX() {
        return this.offX;
    }

    public int getOffY() {
        return this.offY;
    }

    public TileSprite getSprite() {
        return this.sprite;
    }

    public int getWidth() {
        return this.sprite.getSprite().getWidth();
    }

    public int getHeight() {
        return this.sprite.getSprite().getHeight();
    }

    public void render(Graphics g) {
        int width = this.getWidth();
        int height = this.getHeight();

        int x = (this.x * width / 2) - (this.y * width / 2);
        int y = (this.x * height / 2) + (this.y * height / 2);

        x -= width / 2;
        y -= height;

        g.drawImage(this.sprite.getImage(), x, y);
    }
}

```

# Answer
> 2 votes
in your `Tile.render` function you are multiplying the coordinates with the (half) width and height of the current image. But keep in mind that the grid-size of your world is fixed to the size of a normal tile. When you move an object 2 units to the left, its own size is irrelevant. Only the size of the unit matters.

Calculate the position based on the size of a **normal** tile, and then calculate the offset based on the actual size of the tile.

```
private static final int GRID_WIDTH = 112;
private static final int GRID_HEIGHT = 56;

public void render(Graphics g) {

    int x = (this.x * GRID_WIDTH / 2) - (this.y * GRID_WIDTH / 2) - this.getWidth() / 2;
    int y = (this.x * GRID_HEIGHT / 2) + (this.y * GRID_HEIGHT / 2) - this.getHeight();

```

---
Tags: java, graphics, tilemap, isometric
---


# Question
Title: Simulating 3D height in 2D scene (also shadows)
I recently stumbled across this http://vimeo.com/99118680 video and was stunned by the beautiful painted art and colors. But mostly I couldn't believe how everything appeared to have three dimensions despite all being 2D images and sprites. I've dug through the creator's blog and couldn't find any helpful ideas on how they managed this effect so I'm giving it a shot here.

My question is about the trees mostly: How could I go about making a tree out of 2D sprites that will orient correctly as if in 3D.

In addition if anyone has any ideas on how they did the shadows I would love to know that also (I feel like they are static but can't be sure).

# Answer
> 0 votes
If you watch the trees you can clearly see that a perspective camera is in use as it changes relative to the viewing angle.

The fact that some things are drawn over other implies that a depth value is also in use so we have a 3D data set.

Therefore, because there is a perspective camera being used to render a 3D data set it's likely that a standard 3D rendering pipeline is in use. So to render something like those trees you would make a 3D model of trees and render it.

Now, although you seem to be mistaken as to how this game's rendering system works I feel your question regarding drawing trees made of sprites is still valid, so I'll answer that.

**Drawing pseudo-3D trees using sprite tricks**

WARNING: This is a bit of a guess and I can't test out the code supplied right now, but it should provide the kind of illusion you are looking for.

So let's assume you have a set of sprites you will layer one on top of the other, each smaller than the last, to give the image of a tree such as a pine from above. We will also assume your rendering with an orthographic camera (nothing changes with respect to depth).

Essentially what we want to do is layout the sprites in the direction away from the centre of the camera but make sure that it's a stronger effect at the edge and a weaker one nearer the camera, with all sprites one on top of the other when it's in the very centre.

First work out the vector from the tree to the centre of the camera, take the distance and normalise this vector.

`Vector2 dir = treePos - cameraCenter;
 double dist = length(dir);
 dir = normalise(dir);`

where length() returns the vector magnitude and normalise() returns the unit vector.

Now this gives you a nice direction and a distance. Now we want to set the position of the individual sprites. We will draw the bottom one in the treePos and as we go up the tree we will draw each slightly further along a line, in the direction dir, proportional to the distance dist.

```
double heightBetweenSprites = 0.2; // experiment with this value.
for (int i = 0; i < nTreeSprites; ++i)
{
  // scaler = 0 when i = 0 so sprite i must be the bottom sprite.
  double scaler = distance * heightBetweenSprites * i;
  double x = treePos.x + scaler * dir.x;
  double y = treePos.y + scaler * dir.y;
  draw(treeSprite[i], x, y);
}

```

It should be noted that you might want to weight the scaler corresponding to the aspect ration as well. This should be done for each axis separately.

# Answer
> 1 votes
I suspect that there are several tricks in play.

It is entirely possible that the game camera or view is a 3D perspective camera and all the sprites are placed in a 3D environment just at different heights.

there could also be some clever parallax effects going on here.

I would most likely suspect that this is in fact either a 3D or "2.5D" game or it is a clever combination of all/some of the above including 3D.

I actually think that the shadows are dynamic and are based off of the models around them.

watch the subtle changes in the shadow when the player "equips/un-equips" the spear.

I can only guess but that is how I would achieve those things. With "Magics"

---
Tags: 2d, 3d, sprites, depth
---


title: Find point in 3D plane

text:
# Question
Title: Find point in 3D plane
I have four points in a 3D space, example:

(0,0,1)
(1,0,1)
(1,0,2)
(0,0,2)

Then I have a 2D position on that square plane:

x = 0.5
y = 0.5

I need to find out the 3D space point of that position in the plane. In this example it's easy: (0.5,0,1.5) Because Y is zero. But imagine that Y was not zero (and not all the same), that the plane is leaning in some direction. How would I calculate the point in that case?

I imagine this should be a pretty easy thing to solve, but I can't figure it out. Please answer in programming terms and not in straight math terms.

**Update with image:** The gray plane (made out of two triangles) are the real one actually existing. I create a non-existing plane on top of this, the ABCD corners are exactly the same, however it doesn't slope. What I need to do is project a pixel (blue one in example) from the non-existing plane to the existing plane. It will be in the exact same location, except that it has gained a Y value from the sloping plane.

What I've been able to work out so far on my own is which one of the two triangles to use in the gray plane and the normal of triangle. I basically just need to figure out how I can project the pixel.

# Answer
> 4 votes
I'll assume that the A, B, C, D points really do lie on the same plane, i.e. that the two triangles form a single flat surface.

The first step is to calculate the plane equation for the plane. If you don't know what that is, don't worry too much about it. It's a set of four numbers that specify the plane's location and orientation in space. It can be found using any three of the four points on the plane:

```
float4 planeEqn;
planeEqn.xyz = cross(point1 - point0, point2 - point1);
planeEqn.w = -dot(planeEqn.xyz, point0);

```

Here, `point0`, `point1`, and `point2` are any three of your original four points - it doesn't matter which ones, or in which order.

Now, you can solve the plane equation for y in terms of x and z. The plane equation in its native form looks like:

```
planeEqn.x * x + planeEqn.y * y + planeEqn.z * z + planeEqn.w = 0

```

where `(x, y, z)` is any point, and the equation is true (equals zero) only for points on the plane. With a bit of rearrangement you can solve for y:

```
y = (-planeEqn.x * x - planeEqn.z * z - planeEqn.w) / planeEqn.y;

```

That gives you the function for the y-value of any point on the plane, given its x- and z-values.

# Answer
> 0 votes
Figured it out mostly thanks to http://gamedeveloperjourney.blogspot.com/2009/04/point-plane-collision-detection.html

Made me realize I had to verify the normal a bit closer, turns out my plane's grid was being rendered a little different than the actual coordinates for the verticles. No wonder this was so hard to get right! The pixel was projected correctly but rendered incorrectly.

Thanks for all the help guys, that blogspot entry can't take all the credits. You helped me too.

---
Tags: 3d, mathematics
---


# Question
Title: How do C# and UnityScript differ in Unity development?
Other than the obvious language differences, how do UnityScript and C# differ when developing games in Unity3D?

* Is there a noticable performance difference?
* Is the UnityScript code packaged as-is? If yes, does this help the game's moddability?
* Is it possible to use libraries developed for one language while developing in the other one?
* Can the two languages be mixed in the same Unity project; coding some parts in C# and others in UnityScript?

# Answer
> 12 votes
**Is there a noticable performance difference?**

No. There technically is a very small performance difference, but it is not significant enough to base your choice of language on in most cases.

**Is it possible to use libraries developed for one language while developing in the other one?**

Yes. As long as you make sure to keep the folder structure recommended by the developer of the library, that library can be accessed from any language. This has to do with the Unity compilation order. Some features in IDEs, like autocomplete, may not work for the chosen library though. (EDIT: this can be fixed by using the free plugin UnityVS for Visual Studio.)

**Is it possible to mix the two languages in the same Unity project by coding some parts in C# and others in Javascript?**

Again, yes. It gets complicated quickly though, as you have to make sure everything is compiled in the right order. While it is technically possible, I'd recommend you pick one language and stick with it.

**Which language has better game dev specific resources available (books, websites, forums)?**

Hard to say. From browsing the forums, I'd say Javascript has slightly more tutorials and code examples. Code is generally pretty easy to port to the other language though, and since libraries are usable cross-language, this will most likely not be a major issue.

# Answer
> 8 votes
The very first question all beginning Unity developers have is C# or JS. Always go with C#.

Now, right now you may be thinking, *"But I don't want to learn C# and I already know a bit of JavaScript."*

But the misleading thing you need to consider is that **Unity JavaScript is not JavaScript.** It is a superficial veneer of ECMA syntax over .NET CLR. It does not do any of the cool things JavaScript does like anonymous enclosures and function references the way you would use them normally. It has it's own arrays that dont match up with normal .net arrays, and you'll encounter many pitfalls and limitations that you could've just avoided by using C#. Unity JavaScript is only a candy-coated layer of syntax designed to make .NET appear less intimidating, nothing more. It will do you more harm than good.

# Answer
> 7 votes
First off, I would recommend C# over JavaScript for programming in Unity for two main reasons. The first reason comes down to the strong/weak typing difference that you kind of dismissed. I do think strong typing works better than weak typing on a conceptual level, but frankly that's a whole big argument people have and so I'll focus more on a specific practical issue: Deploying to iOS (and possibly other platforms too, but that's the only one I know for sure) requires static typing. Unity actually even has a directive "#pragma strict" that can force static typing in JavaScript for this reason, but that just brings me to my second reason...

Secondly, the JavaScript in Unity is not entirely the same as JavaScript in a browser. This creates problems when you try to apply knowledge from outside Unity (ie. the majority of resources about JavaScript) to programming in Unity. This is why many Unity developers refer to the language as UnityScript.

---

Now to address your specific questions:

> Is there a noticable performance difference?

Not really, no (some details)

> Is the javascript code packaged as-is? And if yes, does this help the game's modability?

Depends on the platform, and no this doesn't really help modability

> Is it possible to use libraries developed for one language while developing in the other one?

I think so (although I've never needed to do this, because all the libraries I use were programmed in C#)

> Is it possible to mix the two languages in the same Unity project by coding some parts in C# and others in Javascript?

Yes (although I try to avoid it, for consistency reasons)

---
Tags: unity, c#, performance, unityscript
---


# Question
Title: SharpDX/D3D: How to implement and draw fonts/text
I am playing with SharpDX (Direct3D for .NET) without using "Toolkit", already finished with basic rendering 3D models. But now i am wondering how to program/create fonts for game (2D), or how to simple draw variable text to output with Direct3D? (it is not as SharpDX question as common Direct3D question, how to start with game GUIs? And what should i do to program simple GUI's like menu for a game (generally i understand that it's shaders).

# Answer
You could use a lookup texture for the alphabet. Then draw a quad for every letter and select the right letter by texture coordinates. You don't use transformation matrixes on this of course. This is a simple way to get started.

Advanced font rendering is a complex topic and you might want to use a library like FreeType for that. However, the basic principle stays the same. It just generates the lookup texture for you from font files.

The second part of your question about graphical user interfaces is another story, so I won't explain that in much detail here. Please open another question for this if you have further questions. But basically it is the same, you draw an unprojected quad and texture it with whatever you like your interface to look like. You can then draw text on top of that. Another interesting approach is to use web technology to define your interface, there is a webkit based library called Awesomium of this.
> 1 votes

# Answer
BMFont is widely used in games industry. It outputs an ASCII or binary file describing the characters' position that you can use to calculate texture coordinates when drawing your text quads.
> 0 votes

# Answer
If using DirectX11.1 is feasible for you (it would mean restricting support only to Windows 7 and 8) you can pretty much do everything you want with Direct2D. In D2D it all comes down to simple `DrawText("text", ...)` calls.
> 0 votes

---
Tags: 3d, gui, sharpdx, fonts
---


# Question
Title: Should I Open/Close SpriteBatch with different settings?
I'm still new in game developpement, and I'm trying to complete my 1st game. Its a simple 2d game, but i'm trying to add lots of differents techniques in it.

It's all good when you take a single tutorial (I followed some tutorials for the screen managers, for diffuse lightning, for camera, HUD, particles, spritesheet animations, etc. ) It's all quite simple to get it to works and run in a simple game.cs file.

the problem I have is when its time to all mix it toghether. I cant find any good pointers on how I should handle the spritebatch orderings. Should I use different spritebatch, or reuse the same over and over ? I was told I need to utilise as little spritebatch as possible ...

\** I KNOW i could test it and start to wonder about it only if I have a problem ... but instead I'd prefer to learn to do it right the 1st time I try it. If I get into a bigger project and this way of doing it only works on easy small 2d game ... its not much better than saying I've never done anything.

More specificly, I'm wondering if I keep my main Draw set up like this :

```
 graphicsDevice.Clear(Color.Black);

 spriteBat.Begin(paramteres set up for my camera);
   for each screen in screenmanager {
     screen.draw(spritebatch);
   }
 spriteBat.End();

  spriteBat.Begin(paramteres set up for my HUD);
     //draw hud stuff
  spriteBat.End();

```

....

and in my screens draw method ... i'll end up with :

```
void Draw(spritebat Spritebatch)
{
     //draw screen "normal" item affected by camera
  spriteBat.End();

  spriteBat.Begin(paramteres set up for particle);
    for each particlelist in particlemanager {
      for each particle in particleList
        particle.draw(spritebatch);
      }
    }
   spriteBat.End();

 spriteBat.Begin(paramteres set up for my light FX);
    //draw diffuse light and shadows stuff
 spriteBat.End();

 spriteBat.Begin(paramteres set up for my camera);
}

```

is this correct ?

# Answer
> 1 votes
Yeah, this is how spritebatch is meant to be used. It takes a view matrix in the begin parameter and uses that throughout the begin/end pair. You could argue that spritebatch would be more flexible with matrices if you could pass a view matrix in for each .draw call, but evidently the XNA team decided against this for one reason or another. To answer your question, having two seperate begin/ends won't make THAT much difference overall. Tutorials often make a note of using as little begin/end as possible to make the reader knows that it should not be called once for every draw call or nested somewhere in a class' .draw method.

The biggest problem I've found this leading to is when you have a .draw method in another class that relies on a spritebatch being begun. If that is the case, this method can only draw with one view matrix. This can be a bit of a problem, but shouldn't be too hard to get around.

Spritebatch .begin changes a lot of the state with the GPU. This is pretty expensive, but two calls per frame is very reasonable and shouldn't be a problem. If your 2D application is lagging on a decent modern computer, you should look for issues elsewhere.

---
Tags: xna-4.0
---


title: Load texture from different thread

text:
# Question
Title: Load texture from different thread
I am trying to load textures from a different thread but it fails everytime on this following method:

```
D3DX10CreateShaderResourceViewFromFile

```

Turning off my multithreaded routines make the textures load correctly.

How do I allow the device to load from a texture from a different thread?

# Answer
> 2 votes
By default, the Direct3D 10 device interface is 'thread-safe' if you don't use D3D10\_CREATE\_DEVICE\_SINGLETHREADED. This means it should work from multiple threads, but could well have lock contention.

Direct3D 11.x splits the device into two parts: a Direct3D 11 device interface which is always 'thread-safe' (again unless you use D3D11\_CREATE\_DEVICE\_SINGLETHREADED), and the Direct3D 11 device context interface which is explicitly not 'thread-safe'. This essentially lets you create resources on multiple threads, but you can't 'Map/Unmap' them from multiple threads.

Now all that said, D3DX itself may or may not be thread-safe. Are you using the 'thread-pump' mechanism?

Note that D3DX is deprecated. For Direct3D 11, you can use DDSTextureLoader or WICTextureLoader. They are 'thread-safe' unless you provide a device context for auto-gen mipmaps.

See this MSDN topic.

# Answer
> -1 votes
I can't tell you haw direct X does it. But in OpenGl you have the same problem. There the opengl context is bound to a specific thread and no other thread is allowed to call functions to opengl. But it is possible to explicitly share the context across threads, so that you can load textures in a different thread. Look for multi threaded direct x and you might find a solution.

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


# Question
Title: How do Action RPGs make different weapon types feel unique?
I'm getting feedback on my game which has Action RPG elements (think Diablo, Torchlight, etc.) but you control a team of heroes. When you kill enemies sometimes new weapons will drop. In my game the DPS of the weapon will be randomized but stronger the further you get. Each weapon type has a hard coded range and rate of attack, but it differs between types. As an example, every Pistol will attack once per second and every Machine Gun will attack 5 times per second.

A common complaint I'm getting is:

> The weapons needs more variety, there's not really many reasons to change weapons because they all have the same speed and small damage differences.

I'm struggling to achieve this. I can vary speed and range for each type, and this seems like an "ok" solution but it's not good enough. This just feels like a sliding scale that looks like this:

```
range <-----|-----------------> rate of attack
dps: 10

```

Here you can change the range and the rate of attack, but the DPS is still going to be based on the level of the enemies. In the end, it's *still* not going to matter which weapon you choose because they'll all have about the same DPS.

If I make it so they don't have the same DPS, then yeah, there will be reasons to change weapons, but it'll be because some weapons suck and some weapons are good. I don't think this puts me in a better place.

**I want the player to feel like weapon type X has pros and cons over weapon type Y. How can I achieve this?**

# Answer
By giving them *actual* pros and cons.

Damage and attack speed are one way to provide a pro/con relationship -- high damage/slow rate of fire versus low damage/high rate of fire -- for example. But that relationship can be a mathematical no-op if the resulting DPS is the same. If you put weapons out of alignment, such that the DPS is not always the same, then as you said you have an obviously better weapon.

So, consider adding further attributes or effects to weapon types, or to the combat system in general. For example, if your game supports the idea of "% chance to do X on hit" effects, that can allow you to drop the overall DPS of "fast" weapons, since "fast" weapons would make up for that by affording more opportunities for the "% chance" roll to trigger. Thus, the player has a choice between a weapon that offers a higher pure DPS or one that has a lower DPS but a higher overall chance of triggering on-hit effects.

You can also apply certain kinds of effects exclusively to certain kinds of attacks. For example, in Skyrim, each flavor of magic (fire, ice, lightning) has a unique side-effect. Fire magic causes additional damage over time via burning, whereas cold magic slows the target and lightning magic reduces the target's own mana pool. This provides a choice for players, even though the overall DPS (ignoring resistances) may be the same: they get to choose a style that complements how they want to play, either a brute force approach via fire damage or a more subtle one via cold spells.

Consider allowing certain kinds of skills only with certain kinds of weapons; relate those skills to the nature of the weapon in real-life. Daggers, for example, could feasibly be thrown and might have a few range-related skills (but you're not likely to be hurling your giant two-handed sword around; perhaps it would have instead skills for rendering foes immobile by damaging or destroying their limbs).

And then there's damage *type* you could model: piercing versus slashing versus bludgeoning damage. In D&D, certain creatures could only be hurt with certain kinds of damage. While that might be too draconian for modern games, you could incorporate some amount of that flavor.

What you really need to do is force players to *make an interesting choice*; games are all about interesting choices.
> 60 votes

# Answer
## A problem that all game designers face

Games need to engage their players.

In general, a game can be broken down into two dimensions. Depth, and required knowledge. There is generally a positive relationship between depth and engagement with the players, however depth is usually accompanied by additional required knowledge. There is a mostly negative relationship between burden of knowledge and player engagement and retention.

Requiring that the player learn some things in order to play your game is fine, however things can get out of hand quite fast. Just look at the genre of fighting games. One must learn a large number of button combos just to be considered competent at the game. It can get quite overwhelming for a new player.

Depth is often provided by adding things to the game. Adding mechanics, adding equipment, and adding hazards to the environment are all examples of methods for adding depth to a game. In any scenario where two options are not identical (such as a non-symmetrical battleground, or different weapons), a lot of care must be put into the balance of the game. More options means a more dire need for balance.

Not only is balance necessary to make PvP a fair and fun experience for all players involved, but it's also necessary to make a single player game a fun and engaging experience for the player. If you can progress in a game by simply mashing a single key, or if you can use any equipment without regard for its stats, then that aspect of the game is not engaging at all.

## How does this apply to your game?

Your players have submitted complaints about bland and unvaried weapons in your game, which is a symptom of the lack of depth. I gave the prior exposition so that you might have a better idea of how to fix this issue.

The best way to figure out why your game is lacking depth, and how to fix it, is to look at other games in the genre. See what that game has that engages their players as well as it does. Try to extract the essence of it so that when you apply the same concepts to your own game, it doesn't seem like a rip-off.

## Let's look at an example

I'm aware that your game uses guns as weapons, but let's take a look at From Soft's Dark Souls series as the concepts applied there are valid for almost any game to some extent. Each weapon falls into a general category that more or less dictates the style of weapon. There are swords, greatswords, katanas, clubs, giant clubs, bows, crossbows, and more. Each major category dictates how the user wields and uses the weapon by changing the animations for each weapon. This makes each weapon category feel significantly different.

However, it gets more deep than that. Individual weapons within the same category might use a varied version of the category's standard move set. In Dark Souls 1, the Uchigatana and Iaito have almost identical stats, but they have different movesets. Even though the Iaito has two or three less damage than the Uchigatana, some prefer the different moveset.

The other answers touched on this, but further distinction is made between weapons by factors beyond raw DPS and attack speed. In Dark Souls, weapons can apply status effects such as bleed or poison. While most katanas have very low DPS when compared to other weapons, the Uchigatana builds up your opponents bleed meter. When the meter fills (which happens in 4-6 hits), the opponent loses a large chunk of health. Bleed still builds up even if your opponent blocks the hit too. This makes the Uchigatana very useful against shield turtles. The main reason why I use this example is that you can make weapons that require specific counter-play. For example, you could make low damage bullets or projectiles that ignore or remove armor from their targets. Even though they have objectively low DPS, if your opponent builds armor then these penetrating bullets will have higher DPS than normal bullets. To make matters even more extreme, you could make bullets that not only ignore armor, but deal more damage based on how much armor your opponent has. Just food for thought.

Additionally, there are multiple methods of striking your opponent in Dark Souls. You can hit people with basic attacks like you would expect, however there are also things like backstabs and ripostes. These are considered to be "critical" attacks, in which the damage you deal is multiplied by your weapon's critical modifier. A dagger has very low base damage, but the critical multiplier is so high that you can oftentimes kill people in a single critical with a dagger.

Now obviously, your game employs the use of firearms. You can find very similar qualities in the weapons found in the Unreal Tournament series. Outside of the basic machine gun, all of the weapons are perfectly viable for use in a fight. Each weapon fills a specific niche, which may make you better off with a given weapon depending on the situation.

## What does this mean for your game?

There's a large number of dimensions that you can manipulate to change the feeling of different firearms. You can change the firing speed and mode of course, but you can also change things like how the weapon affects your player when fired, such as recoil and knock back. You can also modify the projectiles too. Not only can you change the damage they do, but you can also make the projectiles do special things. You can make slow projectiles, projectiles that are affected by the environment (wind, gravity), projectiles that you can charge (like the Unreal Tournament bio-rifle), projectiles that explode on contact (like a rocket launcher), or projectiles that erupt into many smaller projectiles upon landing (the Unreal Tournament flak cannon and bio-rifle again). There are plenty more that you can play with, but these are the first ones to come to mind.

## Watch out

A very difficult problem with building depth of choice into your gameplay is that you risk creating first order optimal strategies (FOOS). Put simply, a FOOS is an easy to execute, highly effective, and difficult to counter technique or style of play. Dark Souls is a prime example of what issues arise when severe imbalances in the equipment system lead to FOOSs. Since Dark Souls is predominantly single player, it's not a severe issue. However in a multiplayer setting, FOOSs can kill a game. The only real solution to the problem of FOOS in a deep gameplay architecture is extensive play testing. Simple number crunching can't match the ingenuity of players.

## Conclusion

The answer to the complaint of "these choices aren't unique enough" is usually to make the choices you offer more unique. Look at other games that are similar to the one you're working on and see how they provide depth to their gameplay. If your current toolset is insufficient, you might want to consider improving the capabilities of your toolset.

If you can balance your gameplay by merely running your different weapons through DPS calculators and making sure they are close to equal, then you are likely doing something wrong. You aren't providing room for more skilled players to flourish by providing more difficult or risky weapons that have higher damage potential.

Look at the channel Extra Credits on Youtube. They have a lot of useful information about this and many other topics relating to game design.
> 25 votes

# Answer
There are many factors that can differ between weapons. In your case, with guns and and sci-fi elements, here are a few possibilities:

* Area of effect. A grenade launcher, flamethrower, or machine gun can threaten multiple opponents. This isn't a good thing in enclosed spaces or where friendlies are crowded in with enemies, of course.
* Strength required. Heavy weapons may not be an option for your small spy character (though StarCraft Ghosts are genetically engineered and much stronger than they look).
* Accuracy. High precision is obviously critical at long range, while most games operate at spitting distance. Still, you might have super-tech aiming enhancement, like the smart guns in Aliens vs Predator, which is useful at medium range.
* Agility. One reason that SWAT teams and special forces use SMGs is because they're compact and can quickly swivel to face an attacker. A large heavy rifle takes a fraction of a second to shift, which may be too long.
* Concealability. When infiltrating an enemy compound, only very small weapons may be possible. Perhaps the players have to scavenge guns from their enemies, or fight to an armory or airdropped cache; forcing players to get by without their first choice of weapons for a while will make them appreciate them more!
* Electronic warfare. In a futuristic setting, maybe there's a gun which fires small rockets which track their targets, but it's ineffective against high-tech enemies with jammers. An ordinary slug-thrower won't be affected.
* Space tolerance. With small modifications, ordinary guns can operate in vacuum, but it's hard to use a gun with a trigger if your spacesuit has mittens or thick gloves. Low-recoil lasers or rocket pistols may be best in zero gravity, though a smart fighter will be behind cover and therefore probably braced. An armor-piercing gun might make holes in your space ship (or the cooling lines for colony LV-426's fusion reactor).
* Target interactions. Maybe electric weapons are most effective against robots, but microwave guns just scatter sparks; low-powered lasers can easily blind animals but most human soldiers have protective eye covering; plasma weapons are intimidating against rabble but too short-ranged to be effective against disciplined troops; only gauss rifles can pierce the heavy hide of a really big beast, but other weapons can still be useful if carefully aimed at the eyes.
* Repairability. Fancy guns need a machine shop, at least; a simple bow can be replaced anywhere there's springy wood. If your players operate in the field, far from home base, this may be important.
* Availability. If the players might lose their weapons, perhaps ditching them in space because they're about to be boarded by the police, the player who prefers hum-drum pistols which you can buy in any shady spaceport will be at an advantage over the player who really only mastered one obscure weapon.
* Style. Ideally, all of the above should mostly net out, in the end, such that I can choose to use a flashy machinegun, a stealthy pistol, or whatever, and be roughly equal to other characters. Let your players make a choice which expresses who they want to be, without it crippling them, and they'll "buy in" to your world more.

Others have already mentioned magazine capacity, reload speed, ease of acquiring ammo, shotgun spread, procs (DoT, stun), and armor-piercing.

The game Borderlands tried to stir up the usual level-based guns by having different brands with random modifications - Bob's guns tend to have high base damage, Shur-Fine guns have larger magazines, etc. - though IMHO the differences tended to be minimal such that one almost always traded up when a higher-level or higher-color weapon came along.

For an extreme example, games like Worms and Battle Block Theater have dozens of weapons which are each completely different. Exploding frogs, Ming vases, grenades, cluster bombs, and fireballs, why not? Obviously that works best with a comedic or over-the-top space fantasy setting. If your game is meant to be relatively realistic, this may not fly - but it's worth perusing for inspiration.
> 15 votes

# Answer
Beyond statistical differences, consider modifying the actual use of the different weapon types to better reflect some different playstyles. The "Feel" of a set of choices will frequently be completely tangential to the actual stats the weapons bring to the table, but can result in a much greater sense of variety.

Even within choices with the exact same DPS there's a big difference between something like an axe that sweeps in a wide arc and a spear with longer range but a narrow thrusting path. The former could be useful for dealing with fast enemies that may try to flank you while the later could allow you to carefully keep an enemy at bay (out of their own attack range). Similarly you could differentiate your pistol from your machine gun by things like weapon spread and whether you need to keep hitting the fire button for every shoot or can hold it down (not to mention the possibility of reload cycles, even if you have unlimited ammo available for simplicity)

Note that obviously these kinds of changes take far more coding work than tweaking the numbers, but if you can give a few points of variety here you can mix them with the numbers changes to make a multiplicative amount of available different weapons.
> 4 votes

# Answer
So first, I would say don't have all pistols have the same RoF etc, there probably isn't any need to keep that consistent. Have them vary slightly around an average for that weapon type.

But in terms of parameters you need to make a shotgun different from an uzi and from a pistol and a sniper rifle etc.

The main two parameters are obviously RoF and Damage, which give you theoretical dps.

But then you have the factors which limit your dps: Range, bullets/clip, time to insert new clip, accuracy. You could use some sort of critical hit system and give sniper rifles high crit chance.

Then you have the factors that don't directly affect damage - scarcity of ammo, weight, size, attachments (grenades? Light?).

Then you have factors based on specific enemies. Thick skin/armour? Reduce damage/shot by a constant amount, which will affect high RoF weapons low damage more than high damage low RoF weapons. A large number of weak enemies will be hard to kill with a sniper rifle simply due to the overkill damage the characters will deal - just make sure that your 'weak' enemies have less health than your high damage low RoF guns do per shot.

Then you also have some special factors; Shotgun damage should decrease with range, whereas other weapons should not. Some machine guns could get hot, so they have great RoF for a short time and then reduce.
> 4 votes

# Answer
Based on the initial complaints you mentioned, about a lack of variance and your subsequent assumption that a slider takes care of the variance you think would work, I've just got a few things to suggest that might help, without being able to draw on a thesis of game design which really wouldnt apply here and tbh sounds like a bunch of unnessesary chaff.

TL;DR; - Stop restricting your weapon design to just DPS and add enough diversity to make it more of what feels right to a player. Explosions, flashing lights, dancing monkey.

Basically, you have a slider moving from range to rate of fire. You're missing a modifying bend on that slider, where a high rate of fire doesnt necessarily have the accuracy desired, as others have suggested an area of effect could come into play. In most games of the genre I've played, I'll usually trade off rate of fire and damage to get a medium kill zone, so while I'm not threatended the weapon isnt useless when in close quarters. Usually means I'm a mage, but the occasional weaponsmith comes along sometimes (thanks torchlight) which makes guns a valid option. And shotguns are just pistols for those who suck at aiming.

So your slider secretly needs to invoke a usefulness rule. Long range slow firing weapons suck when ambushed, and high rate of fire weapons generally suck when taking out a sniper or grenadier.

People will always have their favourites, you arent going to change that. However, adding twists into the mix such as specific weapon classes/models required to access bonuses as has been mentioned previously, you can create the desire for your array. Like picking up a rifle extension that makes a shotgun long range capable.

Another thing to consider is having modifiers for weapons, strip out the concept of 70 different pre fab weapons giving nods to mp4's and ak's, and instead have like 5 or 6 weapons that they can mod the hell out of. Have ammo/battery pickups be more of a straight ammunition increment, and make the player do their own interesting things. have different mags that modify the ammunition properties, say using this green mag I add acid splash to my shots, or this red mag could have molten metal in it. Like, the guns could modify the vanilla ammo picked up to suit. you can still then restrict the pickups at that stage too, so shotgun/pistol/machinegun/sniper ammo, and then the players control what happens next.

Further, by using acid splash you might be adding aoe but its useless against say, energy shields or maybe when using molten metal ammo the capacity in a mag is reduced. A certain battery pack ( if it was an energy weapon ) could provide a stronger shot, but have a reduced capacity of energy before you need to pick up kmore of the vanilla input. You have so many avenues here I admit I dont envy the choices you have to make. When I sat down and started trying to make games the immediate flood of ideas about what I wanted to make was overwhelming, even trying to lock down a genre was hard let alone a subgenre.

To me, futuristic sci fi allows a range from a pistol which can have heavy slugs, dual weild ( basically double dps ) and energy based projectiles; shotties allow again the use of slugs but have a lot more fore to them. and reduced mag. Machine guns have increased mag sizes but are generally lower accuracy and of course firing rate can eat through ammunition which one might not be able to spare. And then rifles ( I still dont see the point in anything other than fps or the old "commandos"/"cannon fodder" games of old where you got a little reticle as a mouse cursor.

I think focussing on DPS alone is just going to be boring, yes players want to get the job done but if you can get an emotional aspect to come into the mix then its less of a calculated puzzle and more of a fun romp killing and looting.

So while your slider is now more of a graphic equaliser patch panel with logarythmic curves and assorted motorised dollies associated to it, I hope that some of my ramblings might have provided some ideas you could apply to your game to hush the moaners. Oh and there will ALWAYS be moaners.
> 4 votes

# Answer
As an example, one game I'm designing is a space game. In that game, players can choose to have their ship made of materials which are particularly reflective or absorbent of electromagnetic radiation. In a simple game, there would be a clear progression from better to worse. In my game though, I made one element in which you want as much radiation reflected as possible (enemy lasers are EM emissions) and I made another element where you want as much radiation absorbed as possible (radar relies on your ship reflecting enemy EM pulses). So now it's no longer clear what the "best" state is, but it is clear that any decision you make will have meaningful results. The choice the player makes here might not make them the strongest, but it will change the kind of play style that is optimal for them. In that way it changes the game itself. If a player has a super-reflective hull, they might get tired of being completely incapable of hiding so they might even get excited to find a "normal" one. It's less about finding "better" things and more about finding different things or finding things that enable a game mechanic to emerge.

You should incorporate that level of pros and cons to weapons in your games. Maybe a longbow has great range and power, but is ineffective inside a certain range or in windy areas (like open fields). So now a player has to think, "Am I going to be going in open fields? Are my enemies going to charge too close too fast?" Maybe a two-handed sword is very powerful but less effective in long fights due to the fatigue caused by its weight. So now the player thinks, "Will I be in short quick fights or long epic battles?" In this way choosing a weapon is less about getting stronger and more about gradually polarizing your optimal play style.
> 1 votes

# Answer
I just want to reinforce the idea of allowing certain skills to work just on an specific weapon type.

For instance take Vagrant Story and its Break Arts. Break Arts are skills which are tied to each specific weapon type (swords, daggers, axes, etc.), and are obtained as you use any weapon of that type. That way, Break Arts also play a role while deciding how to gear yourself.

Another idea that comes to mind is how weapons interact with other pieces of gear. Do you have the concept of one handed vs two handed weapons? Can characters dual wield one handers? Can certain types of weapon combine with specific pieces of gear? Most probably you already implemented such a system, but I mention it just in case.

Also, does your game include the concept of character class? If so, you can limit certain character classes to equip only certain type of weapons. That way, the overall diversity will feel higher, even tough players will have less alternatives for each character.
> 1 votes

# Answer
Not sure if this works in your game, but you could add accuracy/spread as an attribute to your guns: The farther you are removed from your target, the higher the penalty to accuracy becomes.
The spread of a gun modifies this penalty (i.e. low spread weapons like rifles work effectively on long distance, while high spread weapons like shotguns are almost useless at long distance.)
I would advice to calculate the hit-chance for each independent bullet, since that would allow you to occasionally hit an opponent from a distance with a high spread weapon, at the cost of lower damage. (A shotgun fires multiple pellets per round - say 7 pellets - and only X of those hit the opponent if you fire from a distance, X being lower the farther you are removed from your opponent.)
> 0 votes

# Answer
By adding or subtracting predefined attributes to individual items in the game that determine their usefulness. Most RPGs now let characters craft their own weapons and come up with personalized weaponry to a limited extent. The ability to craft ones own weapons can sometimes lead to hacks and unsupported actions by the players who find these "glitches" in the crafting process.
> 0 votes

---
Tags: game-design, balance
---


# Question
Title: What coordinates are we passing to pixel shader from vertex shader?
I have read articles about shader programing and understood the very basic knowledge of shader programing. One thing I always get confused is about the texture mapping. What I pass(output) from VS to PS is the vertex position and Texture Coordinates. I understood that in VS we can simply choose to pass the vertex position as it is or manipulate vertex position here (and may be something more). So what we ultimately pass is the position of the vetex. But... it is still not clear to me that we are passing which we are calling as texture coordinates or UV?

If I understood correctly, if my model is a simple triangle consist of 3 vertices, VS will be run three times for each of the vertix and I am passing the position of the vertex. Its straight forward. But what is with the texture? Say, I am using 50x50 jpg image as texture. How are the 3 vertices are mapped to this 50x50 pixel texture?

From the book I have started reading couple of days ago explained that the rasterizer is the one which groups the vertices to form triangle and calculates the number of pixel in the triangle. But again its not clear to me that what we are passing as texture coordinates to VS?

# Answer
Texture Coordinates are usually expressed in the range between `[0,1]`. Each (textured) vertex will have these coordinates. These coordinates are mapped to texels in the actual texture. `[0,0]` is the top left corner, `[1,1]` the bottom-right corner. When the coordinates are in a range that is multiple of 1, the texture will repeat itself.

For example, for a pixel halfway between `v0` having `t[0,0]` and v1 having `t[1,1]`, the rasterizer will interpolate the texture coordinates value, resulting in `t[0.5,0.5]`. The texture lookup would then sample the texel in middle of the texture.
> 2 votes

---
Tags: shaders, glsl, hlsl, rasterization
---


# Question
Title: Processing move between tiles with an animation in isometric map
In my isometric map, entities can only be in the center of the floor tile. So it's tile per position.

This is my map with an entity:

(source: gyazo.com)

Entity can either move forward, left, or right.

Where **forward** is `X + 1`, **left** is `X - 1, Y - 1`, **right** is `X + 1, Y + 1`.

I simply can move these entities by doing `tile.updateX(1)` for forward, etc.

But I want to make an animation for this move, so it can look like this:

(source: gyazo.com)

Can you see how that small shit moving smoothly through the tiles?

I've tried doing it like this:

```
public void updateShip() {
    this.move = true;
    this.moveX = 2;
    this.moveY = 1;
}

```

moveX and moveY are the offsets im going to add in the move.

and in the update method:

```
@Override
public void update() {
    if (move) {
        // Update animation every 17ms
        if (System.currentTimeMillis() - this.moveTime >= 17) {

            // adding relative offsets
            tiles[5][5].relativeX += moveX;
            tiles[5][5].relativeY += moveY;

            // adding moved token
            moved++;

            // timer to move Y coordinate
            if (System.currentTimeMillis() - turnY > 50){
                moveY++;
                turnY = System.currentTimeMillis();
            }

            // timer to move X coordinate
            if (System.currentTimeMillis() - turnX > 125){
                moveX++;
                turnX = System.currentTimeMillis();
            }

            // If moved more than 29 px, cancel animation and locate
            // to the right spot.
            if (moved >= 29) {

                // stops move
                move = false;

                // sets location
                tiles[5][5].updateX(1);
                tiles[5][5].updateY(1);

                // clears relatives offets
                tiles[5][5].relativeX = 0;
                tiles[5][5].relativeY = 0;
            }

            // upadates time
            this.moveTime = System.currentTimeMillis();
        }
    }

```

In the tile's grapics class, I draw the tiles like this:

```
public void render(Graphics g) {

    int width = this.getWidth() - offX;
    int height = this.getHeight() + offY;

    int x = (this.x * GRID_WIDTH / 2) - (this.y * GRID_WIDTH / 2) - width / 2;
    int y = (this.x * GRID_HEIGHT / 2) + (this.y * GRID_HEIGHT / 2) - height;

    x += relativeX;
    y += relativeY;

    g.drawImage(this.sprite.getImage(), x, y);
}

```

Ignore how messy my design is for now, I am just trying to figure out how moving to sides can be animated with a isometric grid.

however, with my method I could animate forward moving, I just keep the moveX to 2, and moveY to 1, and it will always move forward.

But with my code, this is what it does:

(source: gyazo.com)

What am I calculating wrong?

*Ignore that fact that I need the sprites of the ship's sides. First I need to test without.*

Update I think I did it:

```
private float moveX = 0.045f;
private float moveY = 0.000f;

@Override
public void update() {
    if (move) {
        Tile tile = tiles[5][5];

        if (moveX > 0.001)
            tile.updateX(moveX);

        if (moveY < 0.045)
        tile.updateY(moveY);

        moveX -= 0.001f;
        moveY += 0.001f;
    }
}

```

(source: gyazo.com)

# Answer
Use floating point variables for entities' velocity and position. Use integers only when translating from world position to screen position. This way, your ship will move smoothly thorugh tiles. Also, add a Camera object to convert your world coordinates to screen coordinates as soon as possible.
> 3 votes

---
Tags: java, graphics, animation, tiles
---


# Question
Title: D3D11 Can only Pixel Shader and Compute Shader stages write to buffers?
I am reading Practical Rendering and Computation with Direct3D 11.
In the book the D3D11 pipeline is often described with this image:

In the Chapter about resources, Paragraph about buffers, I understood that the only stages that can write to buffers are the Pixel Shader and the Compute Shader, using Unordered Access Views.
Is it correct? If so, why? Is it because of the inherent architecture of GPUs?

Then, what would be the typical method to output data from a different stage?
For example, how could one get the result of a computation done in the vertex shader, without needing to pass through the other stages?

# Answer
No, you can write to the stream output buffer from the vertex or geometry shader in D3D11. You must create your shader using ID3D11DeviceContext::CreateGeometryShaderWithStreamOutput call to enable this function. You can call it for a vertex shader or a geometry shader too. You also need to create a buffer which you write to and set it with ID3D11DeviceContext::SOSetTargets before the draw call.
It is all documented very well on MSDN.
> 3 votes

---
Tags: directx11, assets, pipeline
---


title: Avoid threads/multithreading

text:
# Question
Title: Avoid threads/multithreading
So here is the thing: I have made a thread for each generator an outpost has. We have a total of 6 outposts , 5 generators each. 3 teams, engineers can only repair generators and prevent their overload. In order to make the whole generator logic I use threads. If the thread gets interrupted it means that the generator got prevented from being destroyed , if the thread is finished normally , the generator got destroyed and if the generator is destroyed an engineer can repair them. Is there any way of avoiding threads because in spite of high cpu usage there are also other thread issues.

The same thing happens with the shield regeneration of each player. I'll just post the code for this one:

```
public static void startRegenerate(final Player p){

    if(already_regenerating_arraylist.contains(p.getId())){
        return;
    }

    final int previous_shield_lvl = p.getShieldLevel();
    final int previous_hp_lvl = (int) p.getHealth();

    Thread reg = new Thread(){

        @Override
        public void run(){

            already_regenerating_arraylist.add(p.getUniqueId());
            try {
                sleep(3000);
            } catch (InterruptedException e1) {
            }

            for(;;){

                if(p.getShieldLevel() >= 20){
                    p.setShieldLevel(20);
                    already_regenerating_arraylist.remove(p.getUniqueId());
                    break;
                }

                if(p.getHealth() < previous_hp_lvl || p.getShieldLevel() < previous_shield_lvl){
                    already_regenerating_arraylist.remove(p.getUniqueId());
                    break;
                }

                p.setFoodLevel(p.getFoodLevel() + 6);

                try {
                    sleep(1000);
                } catch (InterruptedException e) {
                }
            }

        }

    };

    reg.start();
}

```

After having more than 50 players stuff stop working (lag , etc...)

# Answer
> 4 votes
Rule number one of multithreading: avoid it. You might think: "Well, there are things in my game which are supposed to happen simultaneously. Wouldn't it be much more intuitive when each thing happens in its own thread?" No, it's not. Using multithreading makes your program magnitudes more complex. You have no control over how much CPU time the operating system gives to each of your threads and when exactly it switches between them, so they will become out of sync unless you manually synchronize them by making them wait for each other to finish. This introduces very hard to reproduce bugs due to race conditions and deadlocks. Sure, there are language features like `synchronized` to avoid some of them, but these have pitfalls on their own and are easy to forget.

The only argument ever for using more than one thread is performance.

Use threading when you have some calculation which is so CPU-intense that you need more than one core. But in that case don't use more threads than the machine has (currently idle) CPU cores and make sure each thread is able to do a lot of work before being forced to yield or wait for another thread, or you will gain nothing except burdening the OS with additional thread context switches. That's likely what slows down your application.

Another reason to use threading is when you have any network, database or file IO and don't want your application to become unresponsive in the meantime. However, in that case most environments should provide an asynchronous API which does the dirty multithreading stuff for you. In Java, thats Non-blocking IO.

OK, so how else could you structure your application?

You could have a standard game loop.

```
while game is running
     render a frame
     check time elapsed since last gamestate update
     update gamestate taking the elapsed time into account

```

give each object in your game an `update()` function and call that function of each object in a for-loop in your global update gamestate function.

There are two different approaches how to take the elapsed time into account. Either the delta-t model where you pass the difference between real-world time and processed time to the update-function and take it into account for all calculations, or the tick-model where you agree on the internal ticks-per-second rate with which your game logic works (usually 100), check how many ticks your simulation is behind real-time, and call the update-function that many times.

Which one is the better method depends on the game and your personal preference. I personally prefer the tick-method because it is a lot easier to write the update-functions when you don't have to take the delta-t factor into account for everything, but the delta-t method can sometimes (not always!) be a bit faster.

# Answer
> 1 votes
Don't use threads for this. Change "run" method to "update" and just loop through all generators in your mainloop and call "update" for those. I find your logic hard to understand and code hard to debug. This is just my opinion, but threads are not good for this kind of situations. You even have thread sleep in there, so it actually is not that time critical loop.

So, instead of creating thread for that, create update method that does what ever needs to be done and call it from mainloop.

---
Tags: java
---


title: Get 3D quad rotation matrix from points

text:
# Question
Title: Get 3D quad rotation matrix from points
I have 4 3D points which represent a even quad in space. (So 3 points are sufficient) I need to get all the individual transformations (translation, rotation, dimensions) so that I can build that quad in my CSS 3D engine. So the default normal vector for a quad is \[0, 0, 1\].

What I have so far:

```
// 4 points
p0, p1, p2, p3

// normal
normal = cross(p1 - p0, p2 - p0)

// axis and angle
axis = cross([0, 0, 1], normal)
angle = arccos(dot([0, 0, 1], normal))

// rotation matrix
rotationMatrix = matrix4.fromAxisAngle(axis, angle)

// width and height
width = sqrt((p2.x - p1.x)^2, (p2.y - p1.y)^2, (p2.z - p1.z)^2)
height = sqrt((p1.x - p0.x)^2, (p1.y - p0.y)^2, (p1.z - p0.z)^2)

// translation
x = (p0.x + p1.x + p2.x + p3.x) / 4
y = (p0.y + p1.y + p2.y + p3.y) / 4
z = (p0.z + p1.z + p2.z + p3.z) / 4

```

It almost works, but some rotations are wrong or more specifically one rotation axis is missing. This is logical because the rotation is only build from the normal. So how can I get the full rotation?

Here you see that the top and bottom quads are just rotated around the x axis but the y axis rotation is missing:

# Answer
Ok, think I got it. I now build the rotation matrix directly from the vectors:

```
xAxis = cross(normal, (p1 - p0))
yAxis = cross(normal, xAxis)
zAxis = normal

rotationMatrix = [
    xAxis.x, yAxis.x, zAxis.x,
    xAxis.y, yAxis.y, zAxis.y,
    xAxis.z, yAxis.z, zAxis.z
]

```
> 1 votes

---
Tags: rotation, matrix
---


title: Shadow Map field-of-view

text:
# Question
Title: Shadow Map field-of-view
I'm implementing a shadow map algorithm with a spotlight (a spotlight that always "looks" at a given object).

My issue is that for some configuration, part of the object the light is "looking at" is out of the light frustum. As a consequence everything that is not "seen" is shadowed.

To account for this I tried to increase the field of view of the "light camera", but as a result I get **very** blocky shadows.

Am I doing something wrong? Is there a more clever way to make sure the light can see the whole object? If not, how can I solve the above said artefact?

# Answer
> 1 votes
The field of view for the shadow map needs to be large enough to cover the whole cone of the spotlight. So if the cone is made wide enough to illuminate the whole object, the shadow map FoV will need to be wide enough to see all of it.

If the shadows are getting too blocky, you'll need to increase the shadow map texture resolution.

If the field of view gets very wide, approaching 180°, then a single shadow map won't work so well anymore—the texture will start to get stretched nonlinearly, putting more resolution around the edges and little at the center. For very wide spotlights or omnidirectional lights, one can use a cubemap (effectively 6 shadow maps pointing in different directions) instead of a single shadow map.

---
Tags: opengl, shadows, shadow-mapping, perspective
---


# Question
Title: How should I detect collisions with objects on a "timeline"?
I'd like to replicate this game's mechanic of the player smashing walls with a precise timing to a background rhythm.

How should I check when each wall should be broken? Does the player animation use a hitbox, or does it use timing to detect if the smashing animation should play?

# Answer
You need only simple collision detection for something like this: You could just compare the X-coordinate of the nearest wall with that of the player when the player throws a punch.

Something along the lines of

```
if (wall.x - player.x <= 50 && wall.x - player.x > 0) {
    // The wall is in a good position!
} else {
    // The wall is out of reach!
}

```

I used 50 as the maximum target distance here. Change it to fit the needs of your game.

If you would want this to be a part of an animation, just run this check in select frames of your animation, where the player's punch would be valid.
> 1 votes

---
Tags: c#, unity, collision-detection, timing
---