# Question
Title: Normal map applied as diffuse textures looks wrong
Diffuse textures works fine, but I am having problem with normal maps, so I thought I'd tried to apply the normal maps as the diffuse map in my fragment shader so I could see everything is OK.

I comment-out my normal map code and just set the diffuse map to the normal map and I get this:

http://postimg.org/image/j9gudjl7r/

Looks like a smurf!

This is the actual normal map of the main body:

http://postimg.org/image/sbkyr6fg9/

Here is my fragment shader, notice I commented out normal map code so I could debug the normal map as a diffuse texture

```
"#version 330                                                                                \n \
                                                                                \n \
layout(std140) uniform;                                                                                \n \
                                                                                \n \
const int MAX_LIGHTS = 8;                                                                                \n \
                                                                                \n \
struct Light                                                                                \n \
{                                                                                \n \
    vec4  mLightColor;                                                                                \n \
    vec4  mLightPosition;                                                                                \n \
    vec4  mLightDirection;                                                                                \n \
                                                                                \n \
    int   mLightType;                                                                                \n \
    float mLightIntensity;                                                                                \n \
    float mLightRadius;                                                                                \n \
    float mMaxDistance;                                                                                \n \
};                                                                                \n \
                                                                                \n \
uniform UnifLighting                                                                                \n \
{                                                                                \n \
    vec4  mGamma;                                                                                \n \
    vec3  mViewDirection;                                                                                \n \
    int   mNumLights;                                                                                \n \
                                                                                \n \
    Light mLights[MAX_LIGHTS];                                                                                \n \
} Lighting;                                                                                \n \
                                                                                \n \
uniform UnifMaterial                                                                                \n \
{                                                                                \n \
    vec4  mDiffuseColor;                                                                                \n \
    vec4  mAmbientColor;                                                                                \n \
    vec4  mSpecularColor;                                                                                \n \
    vec4  mEmissiveColor;                                                                                \n \
                                                                                \n \
    bool  mHasDiffuseTexture;                                                                                \n \
    bool  mHasNormalTexture;                                                                                \n \
    bool  mLightingEnabled;                                                                                \n \
    float mSpecularShininess;                                                                                \n \
} Material;                                                                                \n \
                                                                                \n \
uniform sampler2D unifDiffuseTexture;                                                                               \n \
uniform sampler2D unifNormalTexture;                                                                                \n \
                                                                                \n \
in vec3 frag_position;                                                                                \n \
in vec3 frag_normal;                                                                                \n \
in vec2 frag_texcoord;                                                                                \n \
in vec3 frag_tangent;                                                                                \n \
in vec3 frag_bitangent;                                                                                \n \
                                                                                \n \
out vec4 finalColor;                                                                                "
                                                                                "         \n \
                                                                                \n \
void CalcGaussianSpecular(in vec3 dirToLight, in vec3 normal, out float gaussianTerm)                                               \n \
{                                                                                \n \
    vec3 viewDirection = normalize(Lighting.mViewDirection);                                                        \n \
    vec3 halfAngle     = normalize(dirToLight + viewDirection);                                                     \n \
                                                                                \n \
    float angleNormalHalf = acos(dot(halfAngle, normalize(normal)));                                           \n \
    float exponent        = angleNormalHalf / Material.mSpecularShininess;                                          \n \
    exponent              = -(exponent * exponent);                                                                 \n \
                                                                                \n \
    gaussianTerm = exp(exponent);                                                                                \n \
}                                                                                \n \
                                                                                \n \
vec4 CalculateLighting(in Light light, in vec4 diffuseTexture, in vec3 normal)                                                      \n \
{                                                                                \n \
    if (light.mLightType == 1)          // point light                                                              \n \
    {                                                                                \n \
        vec3 positionDiff = light.mLightPosition.xyz - frag_position;                                                   \n \
        float dist        = max(length(positionDiff) - light.mLightRadius, 0);                                          \n \
                                                                                \n \
        float attenuation = 1 / ((dist/light.mLightRadius + 1) * (dist/light.mLightRadius + 1));                        \n \
        attenuation       = max((attenuation - light.mMaxDistance) / (1 - light.mMaxDistance), 0);                      \n \
                                                                                \n \
        vec3 dirToLight   = normalize(positionDiff);                                                                    \n \
        float angleNormal = clamp(dot(normalize(normal), dirToLight), 0, 1);                                       \n \
                                                                                \n \
        float gaussianTerm = 0.0;                                                                                \n \
        if (angleNormal > 0.0)                                                                                \n \
            CalcGaussianSpecular(dirToLight, normal, gaussianTerm);                                                                               \n \
                                                                                \n \
        return diffuseTexture * (attenuation * angleNormal  * Material.mDiffuseColor  * light.mLightIntensity * light.mLightColor) +      \n \
                                (attenuation * gaussianTerm * Material.mSpecularColor * light.mLightIntensity * light.mLightColor);       \n \
    }                                                                                \n \
    else if (light.mLightType == 2)     // directional light                                                                              \n \
    {                                                                                \n \
        vec3 dirToLight   = normalize(light.mLightDirection.xyz);                                                                         \n \
        float angleNormal = clamp(dot(normalize(normal), dirToLight), 0, 1);                                                         \n \
                                                                                \n \
        float gaussianTerm = 0.0;                                                                                \n \
        if (angleNormal > 0.0)                                                                                \n \
            CalcGaussianSpecular(dirToLight, normal, gaussianTerm);                                                             \n \
                                                                                \n \
        return diffuseTexture * (angleNormal  * Material.mDiffuseColor  * light.mLightIntensity * light.mLightColor) +  \n \
                                (gaussianTerm * Material.mSpecularColor * light.mLightIntensity * light.mLightColor);   \n \
    }                                                                                \n \
    else if (light.mLightType == 4)     // ambient light                                                            \n \
        return diffuseTexture * Material.mAmbientColor * light.mLightIntensity * light.mLightColor;                 \n \
    else                                                                                \n \
        return vec4(0.0);                                                                                \n \
}                                                                                \n \
                                                                                \n \
void main()                                                                                \n \
{                                                                                \n \
    vec4 diffuseTexture = vec4(1.0);                                                                                \n \
    if (Material.mHasDiffuseTexture)                                                                                \n \
        diffuseTexture = texture(unifDiffuseTexture, frag_texcoord);                                                \n \
                                                                                \n \
    vec3 normal = frag_normal;                                                                                \n \
    if (Material.mHasNormalTexture)                                                                                \n \
    {                                                                                \n \
        diffuseTexture = vec4(normalize(texture(unifNormalTexture, frag_texcoord).xyz * 2.0 - 1.0), 1.0);  \n \
       // vec3 normalTangentSpace  = normalize(texture(unifNormalTexture, frag_texcoord).xyz * 2.0 - 1.0);            \n \
        //mat3 tangentToWorldSpace = mat3(normalize(frag_tangent), normalize(frag_bitangent), normalize(frag_normal)); \n \
                                                                                \n \
       // normal = tangentToWorldSpace * normalTangentSpace;                                                              \n \
    }                                                                                \n \
                                                                                \n \
    if (Material.mLightingEnabled)                                                                                \n \
    {                                                                                \n \
        vec4 accumLighting = vec4(0.0);                                                                             \n \
                                                                                \n \
        for (int lightIndex = 0; lightIndex < Lighting.mNumLights; lightIndex++)                                    \n \
            accumLighting += Material.mEmissiveColor * diffuseTexture +                                             \n \
                                CalculateLighting(Lighting.mLights[lightIndex], diffuseTexture, normal);                       \n \
                                                                                \n \
        finalColor = pow(accumLighting, Lighting.mGamma);                                                           \n \
    }                                                                                \n \
    else {                                                                                \n \
        finalColor = pow(diffuseTexture, Lighting.mGamma);                                                          \n \
    }                                                                                \n \
}                                                                                \n";

```

Here is my wrapper around a texture

```
OpenGLTexture::OpenGLTexture(const std::vector<uint8_t>& textureData, uint32_t textureWidth, uint32_t textureHeight, TextureFormat textureFormat, TextureType textureType, Logger& logger) : mLogger(logger), mTextureID(gNextTextureID++), mTextureType(textureType)
{
    glGenTextures(1, &mTexture);
    CHECK_GL_ERROR(mLogger);

    glBindTexture(GL_TEXTURE_2D, mTexture);
    CHECK_GL_ERROR(mLogger);

    GLint glTextureFormat = (textureFormat == TextureFormat::TEXTURE_FORMAT_RGB ? GL_RGB : textureFormat == TextureFormat::TEXTURE_FORMAT_RGBA ? GL_RGBA : GL_RED);
    glTexImage2D(GL_TEXTURE_2D, 0, glTextureFormat, textureWidth, textureHeight, 0, glTextureFormat, GL_UNSIGNED_BYTE, &textureData[0]);
    CHECK_GL_ERROR(mLogger);

    glGenerateMipmap(GL_TEXTURE_2D);
    CHECK_GL_ERROR(mLogger);

    glBindTexture(GL_TEXTURE_2D, 0);
    CHECK_GL_ERROR(mLogger);
}

OpenGLTexture::~OpenGLTexture()
{
    glDeleteBuffers(1, &mTexture);
    CHECK_GL_ERROR(mLogger);
}

```

And here is the sampler I create which is shared between Diffuse and normal textures

```
    // texture sampler setup
    glGenSamplers(1, &mTextureSampler);
    CHECK_GL_ERROR(mLogger);
    glSamplerParameteri(mTextureSampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    CHECK_GL_ERROR(mLogger);
    glSamplerParameteri(mTextureSampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
    CHECK_GL_ERROR(mLogger);
    glSamplerParameteri(mTextureSampler, GL_TEXTURE_WRAP_S, GL_REPEAT);
    CHECK_GL_ERROR(mLogger);
    glSamplerParameteri(mTextureSampler, GL_TEXTURE_WRAP_T, GL_REPEAT);
    CHECK_GL_ERROR(mLogger);
    glSamplerParameterf(mTextureSampler, GL_TEXTURE_MAX_ANISOTROPY_EXT, mCurrentAnisotropy);
    CHECK_GL_ERROR(mLogger);

    glUniform1i(glGetUniformLocation(mDefaultProgram.GetHandle(), "unifDiffuseTexture"), OpenGLTexture::TEXTURE_UNIT_DIFFUSE);
    CHECK_GL_ERROR(mLogger);
    glUniform1i(glGetUniformLocation(mDefaultProgram.GetHandle(), "unifNormalTexture"), OpenGLTexture::TEXTURE_UNIT_NORMAL);
    CHECK_GL_ERROR(mLogger);
    glBindSampler(OpenGLTexture::TEXTURE_UNIT_DIFFUSE, mTextureSampler);
    CHECK_GL_ERROR(mLogger);
    glBindSampler(OpenGLTexture::TEXTURE_UNIT_NORMAL, mTextureSampler);
    CHECK_GL_ERROR(mLogger);

    SetAnisotropicFiltering(mCurrentAnisotropy);

```

The diffuse textures looks like they should, but the normal looks so wierd. Why is this?

# Answer
This line

```
diffuseTexture=vec4(normalize(texture(unifNormalTexture, frag_texcoord).xyz * 2.0-1.0), 1.0);

```

Should be

```
  diffuseTexture=vec4(normalize(texture(unifNormalTexture, frag_texcoord).xyz ), 1.0);

```

The reason is before normals are encoded into Normal maps their values could be in the range from -1.0 to 1.0, this doesn't really works with normal R8B8G8A8 images as they cannot store negative numbers. In order to make the image able to store normal numbers we do **Scale and Bias by multiplying by 0.5 and adding 1.0**. This will effectively map the normals' values:

* \[-1, 0\] =\> \[0.0, 0.5\] and
* \[0, 1\] =\> \[0.5, 1\]

Now inorder to get the original values you need to undo this Scale and Bias operation by multiplying by 2 and subtracting 1. Your problem is you don't need to do this when rendering a normal map as you don't really need the original (probably negative) values and render them on the screen.
> 3 votes

# Answer
You've left in the `* 2.0 - 1.0` when sampling the normal map. You probably want to comment that out as well if you're trying to visualize the normal maps for debugging purposes; that way they'll match up with what you see when looking at the normal map in an image viewer.
> 1 votes

---
Tags: c++, opengl, textures, normal-mapping
---


# Question
Title: Spherical harmonics lighting - what does it accomplish?
From my understanding, spherical harmonics are sometimes used to approximate certain aspects of lighting (depending on the application).

For example, it seems like you can approximate the diffuse lighting cause by a directional light source on a surface point, or parts of it, by calculating the SH coefficients for all bands you're using (for whatever accuracy you desire) in the direction of the surface normal and scaling it with whatever you need to scale it with (e.g. light colored intensity, dot(n,l),etc.).

What I don't understand yet is what this is supposed to accomplish. What are the actual advantages of doing it this way as opposed to evaluating the diffuse BRDF the normal way. Do you save calculations somewhere? Is there some additional information contained in the SH representation that you can't get out of the scalar results of the normal evaluation?

# Answer
The reason to use spherical harmonics is to approximate the incoming light distribution around a point—typically indirect light calculated by some global illumination algorithm. Then the BRDF is also approximated with spherical harmonics, to allow efficiently calculating the outgoing light seen by the viewer, by taking the dot product of the incoming light SH coefficients with the BRDF SH coefficients. This approximates the convolution of incoming light with the BRDF, as seen in the rendering equation.

If you only care to receive light from point-sources, you have no need for SH. Point lights are more accurately handled by just evaluating the BRDF directly. Also, if you have a fixed environment (sky etc.) that you want to receive light from, you can generate pre-convolved cubemaps offline (using CubeMapGen for instance) that do a pretty good job of approximating the convolution of the environment map with the BRDF. No need for SH here either.

Where SH really comes in handy is when you have a complex scene and you want indirect lighting, i.e. bounce lighting. In this case the light distribution varies from place to place. In principle, each individual point in the scene has a different lighting environment based on its surroundings. In practice we sample the lighting at discrete points using some global illumination algorithm. There are many ways to do it - you could sample lighting at each vertex of the surfaces, for instance, or at each texel of a lightmap. Or create a volumetric representation using a grid, or a tetrahedral mesh.

The point is, there are a large number of points where lighting is sampled, and so we need a flexible but very compact representation of the lighting around a point, to avoid consuming too much memory. SH fills this role nicely. It also has the handy property that it works well with interpolation, i.e. the SH coefficients can be interpolated from one sample point to another and the lighting in between will behave reasonably. And since it captures the overall angular distribution of incoming light, not just the light from one direction, you can use it with a normal-mapped surface and get pretty good results.

It should be noted, though, that SH is really only useful for diffuse lighting. Unless you use a truly insane number of SH coefficients, it will blur out the angular distribution of incoming light too much. For high-quality specular indirect lighting, something else is needed, such as parallax-corrected cubemaps and/or screen-space raytracing.
> 11 votes

# Answer
> What I don't understand yet is what this is supposed to accomplish ?

Short answer, more accurate physical light calculations. (with respect to some light surface interaction characteristics).

> Why not evaluate everything with the diffuse BRDF the normal way?

Unfortunately the problem lies within the definition of the **normal way**. The "normal" phong reflection model has been embraced long time ago by the real time rendering community from the beginning and has been the *de facto standard* because of it's simplicity that makes it appropriate for the use of real time rendering.

**The problem though**, real life light/material interaction is so complicated that it cannot be actually modeled by a single BRDF.

**BRDFs** are an abstraction of how the actual light interaction is supposed to happen. phong is just one many other, that has the advantage of simplicity.

> But what are the actual advantages ?

In computer graphics there are different BRDFs that fall into two main categories:

1. Based on physical theory.
2. Designed to fit specific a class of surface type and are usually used in real time rendering.

Talking about the second category each BRDF tries to accomplish certain characteristics with light surface interaction. The simplest possible BRDF is Lambertian which tries to model subsurface scattering and are often used in computer graphics, The constant reflectance value of a Lambertian BRDF is commonly refered to as the diffuse color.

In real time computer graphics usually BRDFs are manually selected and their parameters set to achieve a desired look (e.g. using Phong with certain values to model a plastic or a chrome surface).

On the other hand, sometimes BRDFs are measured directly from the desired surface (and are not represented by a math equation). This gives us much more physically accurate data about the surface that are otherwise hard to accomplish analytaclly.

One method to fit those captured data is to select an analytical BRDF and fit these data into it. **Spherical Harmonics** is just a technique used to represent those measured quantities, and fit them into an analytical BRDF model.

The best resource for BRDF theory can be found in real time rendering

* **7.5** BRDF Theory.
* On spherical harmonics revise **7.7.2** Representations for Measured BRDFs.
> 3 votes

---
Tags: rendering, lighting, spherical-harmonics
---


# Question
Title: In GLSL is it possible to offset vertices based on height map colour?
I am attempting to generate some terrain based upon a heightmap. I have generated a 32 x 32 grid and a corresponding height map -\>

In my vertex shader I am trying to offset the position of the Y axis based upon the colour of the heightmap, white vertices being higher than black ones.

```
//Vertex Shader Code
#version 330

uniform mat4 modelMatrix;
uniform mat4 viewMatrix;
uniform mat4 projectionMatrix;
uniform sampler2D heightmap;

layout (location=0) in vec4 vertexPos;
layout (location=1) in vec4 vertexColour;
layout (location=3) in vec2 vertexTextureCoord;
layout (location=4) in float offset;

out vec4 fragCol;
out vec4 fragPos;
out vec2 fragTex;

void main()
{
    // Retreive the current pixel's colour
    vec4 hmColour = texture(heightmap,vertexTextureCoord);

    // Offset the y position by the value of current texel's colour value ?
    vec4 offset = vec4(vertexPos.x , vertexPos.y + hmColour.r, vertexPos.z , 1.0);

    // Final Position
    gl_Position = projectionMatrix * viewMatrix * modelMatrix * offset;

    // Data sent to Fragment Shader.
    fragCol = vertexColour;
    fragPos = vertexPos;
    fragTex = vertexTextureCoord;
}

```

However the code I have produced only creates a grid with none of the y vertices higher than any others.

This is the C++ code that generates the grid and texture co-orientates which I believe to be correct as the texture is mapped to the grid, hence the white blob in the middle.

The grid-lines are generated in the fragment shader, sorry for any confusion.

I have tried multiplying the r value of hmColour by 1000 unfortunately that had no effect.

The only other problem it could be is that the texture coordinate data is incorrect ?

```
for (int z = 0; z < MAP_Z  ; z++)
   {
    for(int x = 0; x < MAP_X  ; x++)
    {
    //Generate Vertex Buffer

    vertexData[iVertex++] = float (x) * MAP_X;
    vertexData[iVertex++] = 0;
    vertexData[iVertex++] =  -(float) (z) * MAP_Z;

    //Colour Buffer  NOT NEEDED
    colourData[iColour++] = 255.0f; // R
    colourData[iColour++] = 1.0f; // G
    colourData[iColour++] = 0.0f; // B

    //Texture Buffer

    textureData[iTexture++] = (float ) x * (1.0f / MAP_X);
    textureData[iTexture++] = (float ) z * (1.0f / MAP_Z);

     }
    }

```

The heightmap texture I am trying to use appears like so (without grid-lines).

This is the corresponding fragment shader

```
// Fragment Shader Code
#version 330

uniform sampler2D hmTexture;

layout (location=0) out vec4 fragColour;

in vec2 fragTex;

in vec4 pos;

void main(void) {

    vec2 line = fragTex * 32;
    // Without Gridlines
    fragColour = texture(hmTexture,fragTex);

    // With grid lines
    // + mix(vec4(0.0, 0.0, 1.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0),
  //  smoothstep(0.05,fract(line.y), 0.99) * smoothstep(0.05,fract(line.x),0.99));

}

```

# Answer
> 3 votes
So, what you're doing looks generally ok. There are a few possible sources of error.

As Matthew said, you could be passing in uv coordinates wrong, and looking up the same thing everywhere.

My best guess however, is something related to the coordinate space.

```
vec4 offset = vec4(vertexPos.x , vertexPos.y + hmColour.r, vertexPos.z , 1.0);

```

So, for starters, this all happens in model space. Which seems appropriate to me but let's keep that in mind as we evaluate the following.

This implies that the grid varies in the `X` and `Z` axes, It is possible that the model is in the XY plane and one of the matrices puts it into the XZ plane. However, if everything else is working correctly, I'd expect this to be noticeable.

The other big possibility is that everything is in fact working... sort of except everything is very small. In all likely-hood, `hmColour` is in the range of 0.0 and 1.0 (unless you are using 32 bit per channel textures) And it's quite likely that vertexPos is in a much larger range than that. Considering that the terrain seems to poke through the grid in a few spots in the only image you posted I suspect this is the case. The easy test for this is to multiply hmColour.r by something large.

```
vec4 offset = vec4(vertexPos.x , vertexPos.y + hmColour.r * 1000.0, vertexPos.z , 1.0);

```

Or something similar.

# Answer
> 1 votes
It seems like you did not set the uv coordinates at each vertex, so it's most likely just sampling at the same point every time, resulting in a mesh with the same y offset. Try setting the UV coords at each vertex to the distance from the bottom left corner on each axis divided by the grid length.

You may also want to multiply the color value by some constant because in shader, the color value is always between 0 and 1.

---
Tags: opengl, glsl, graphics-programming, terrain
---


# Question
Title: How can I solve for the game's world coordinates?
I've used 3DReaperDX to get a obj file, the header information are shown as follows:

```
#AR=2.00606, FOV=45.09583(height), Xscale:0.83290, Yscale:0.41519, Zscale:1.0
#**************************************************
#ALPHABLENDENABLE: No
#ZENABLE: Yes
#ZWRITEENABLE: Yes
#TWOSIDED: No
#INVALID: No
#THIN: No
#RENDERTARGET_IS_BACKBUFFER: Yes
#WIDTH_DO_MATCH: Yes
#RGBWRITEDISABLED: No
# object DrawCall_0 to come ...
g
v 2143.35547 6654.99023 25835.37109
v 2243.17773 6296.61523 25957.53906
v 2343.00000 5856.84473 26093.97656

```

How can I get the game's world coordinates.

For example: I can map the scaleTransform to the VertexData

scaleTransform={X1scale,Y1scale,Z1scale} {0.8329,0.41519,1.}

Is the obj file enough to get the game's world coordinates? I want to put a object in this ground, and the coordinates is the same to that in the Game Engine,

And I can place something(with some fixed coordinates) in the Game and then to use 3DReaper to get the obj file. If the file is not enough itself to get the game world coordinates.

# Answer
You really should try to ask a better question.

Anyways, While there is some likelihood that your were returned coordinates in model space, or even view space. it looks very much that the coordinates are in post ModelWorld transform, and pre ViewProjection transform. That would then make the coordinates in "World space" But even if this is true, the game can do all sorts of weird things with their matrices. And even weirder things (Or the same things, yet more likely) if it's a more modern game using no fixed-function matrices.

So, given your question, I figure there are three possible things you could be wanting:

* The coordinates in model space. These are an points in local space, as they would be coming out of the editor, and entering the game engine.
* The coordinates in world space. This would be the points in the scene or world, placed relative to other objects in the scene, This generally varies as objects move in the world.
* The position of the object in world space. This is the position you use to get points in local space, into world space, and the point the game engine uses to represent the "position" of an object.

And in addition to those first two spaces, the points you have could also be in view space, which is everything in the world, brought into a space where vertices are relative to the camera location and rotation.

(Technically, you could be in projected view space also, but in that case you shouldn't be seeing numbers outside of say -1.0 to 1.0, depending on the API in use)

So, to convert from one space to another, we need to use the proper matrix:

* To go from model space to world space, you use the model transform matrix. Which is a matrix created from the models scale, rotation and translation.
* To go from world space to view space you use the camera transform matrix, which similarly is created from the camera's rotation and translation.
* And any of these matrices can be inverted to go in the reverse direction, so we'd talk about the inverse model transform matrix, or the inverse camera transform matrix in that case.

And if you didn't want vertex coordinates at all, and just want the objects position, that can be extracted from the 4th column of the Model transform matrix.

Adly any of that data is not contained in an obj file. and in all likelihood cannot be extracted in an easy and simple way from the game that's not very specific to the game. However you may not need it. Depending on your use case, you may just be able to get the geometric average of the points in question, and consider that the center of that coordinate space, and perhaps some other fix ups on orientation but it really comes down to what your use-case is.
> 2 votes

---
Tags: coordinates
---


title: Masking OpenGL texture by a pattern

text:
# Question
Title: Masking OpenGL texture by a pattern
Tiled terrain. User wants to build a structure. He presses build and for each tile there is an "allow" or "disallow" tile sprite added to the scene. FPS drops right away, since there are 600+ tiles added to the screen. Since map equals screen, there is no scrolling. I came to an idea to make an allow grid covering the whole map and mask the disallow fields.

Approach 1:

* Create allow and disallow grid textures.
* Draw a polygon on screen.
* Pass both textures to the fragment shader.
* Determine the position inside the polygon and use color from allowTexture if the fragment belongs to the allow field, disallow otherwise

Problem: How do I know if I'm on the field that isn't allowed if I cannot pass the matrix representing the map (enum FieldStatus\[\]\[\] (Allow / Disallow)) to the shader? Therefore, inside the shader I don't know which fragments should be masked.

Approach 2:

* Create allow texture.
* Create an empty texture buffer same size as the allow texture
* Memset the pixels of the empty texture to desired color for each pixel that doesn't allow building.
* Draw a polygon on screen.
* Pass both textures to the fragment shader.
* Use texture2 color if alpha \> 0, texture1 color otherwise.

Problem: I'm not sure what is the right way to manipulate pixels on a texture. Do I just make a buffer with width\*height\*4 size and memcpy the color\[\] to desired coordinates or is there anything else to it? Would I have to call glTexImage2D after every change to the texture?

Another problem with this approach is that it takes a lot more work to get a prettier effect since I'm manipulating the color pixels instead of just masking two textures.

```
varying vec2 TexCoordOut;

uniform sampler2D Texture1;
uniform sampler2D Texture2;

void main(void){
    vec4 allowColor = texture2D(Texture1, TexCoordOut);
    vec4 disallowColor = texture2D(Texture2, TexCoordOut);

if(disallowColor.a > 0){
    gl_FragColor= disallowColor;
}else{
    gl_FragColor= allowColor;
}}

```

I'm working with OpenGL on Windows. Any other suggestion is welcome.

# Answer
I believe both your approaches are pretty solid.
With your first approach :

* Create allow and disallow grid textures.
* Create the **array** representing the map
* Draw a polygon on screen.
* Pass both textures to the fragment shader.
* Determine the position inside the polygon and use color from allowTexture if the fragment belongs to the allow field, disallow otherwise

You create an array of your map with size = width * height of the matrix and pass it into the shader as an array of booleans using glUniform1iv ( or safer ints because the driver will first convert your boolean into int and then into boolean in the shader ). But with this approach you have to set the maximum size of the array inside the shader ( uniform int map\[320\*320\] ), because GLSL does not allow the creation of an array of unknown size, and pass the current size of the array as a uniform.

With your second approach :

* Create allow **and** disallow grid textures.
* Create an empty texture buffer same size as **the number of tiles**
* Memset the pixels of the empty texture to desired value for each tile that doesn't allow building.
* Draw a polygon on screen.
* Pass textures to the fragment shader.
* Use allowTexture color if maskTexture.r \> 0.0 or disallowTexture color otherwise.

You create the texture buffer with the size of width * height and set each pixel with the desired value. Then you create the texture with a format which has one channel ( GL\_R8 or GL\_R8I for example ) and every time you update it with glSubTexImage2D. Keep in mind that you should set the filtering to NEAREST or use textureFetch, otherwise the texture fetch will give you incorrect results.

An important thing to note, for both approached, is that you should update the buffers **only** when there is a change in the allow/Disallow map.
In my personal opinion, i will go with the second approach since it does not bound me to a maximum size of the map.
> 1 votes

---
Tags: opengl, textures, shaders, tilemap, masking
---


title: Unity3d High level literature

text:
# Question
Title: Unity3d High level literature
Is there any high level literature for mid professional programmers for Unity? There are a lot of tutorials for beginners, but I can't find anything about main API, pipeline or engine architecture. Recommend, please!

# Answer
> 2 votes
I've been collecting some resources and hope to one day write up something sensible on the architecture but for now I can dump some of my links:

Nurturing Large Projects http://www.youtube.com/watch?v=q9aeNtKKXeo

Pretty good introduction to creating and maintaining a larger project in Unity. They definitely take some shortcuts and overuse Singletons etc. but it's good for getting a base level of knowledge. They also provide the slides and a good list of further reading.

50 Tips for Working with Unity (Best Practices) http://devmag.org.za/2012/07/12/50-tips-for-working-with-unity-best-practices/

Continuing... When you're dealing with Unity, the underlying architecture for most of the things you're doing is component-based programming. You create GameObjects that have their behavior separated into discrete components like Collider, Rigidbody, Transform. There are some good books and blog posts about that. https://stackoverflow.com/questions/1901251/component-based-game-engine-design http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy

Pretty much all of these are great practices that will help you figure out how to work out some practical parts of the architecture by yourself.

---
Tags: unity
---


title: How to create a map system for my game?

text:
# Question
Title: How to create a map system for my game?
I wanted to make a small game about space. However, I had a couple of questions \[below\]

How will I draw a map for my game? I would like it to contain a solar system. How will I draw these planets?

Thanks in advance!

# Answer
> 1 votes
When it comes to generating content for a game, there are three approaches

1. **Create the content by hand.** Either hard-code it into the games sourcecode or write the files which store the content with a text editor. This is quite tedious and hard to maintain, but when you don't have a lot of content, it is a valid quick&dirty method.
2. **Create a map editor.** To make it more convenient to edit your game content, you create a GUI-based editor application for it. Depending on your requirements and how user-friendly you want it to be, this can be a quite large sub-project costing considerable development time, but it can pay off well in the long run. Especially because it allows you to delegate the content creation to other people who are less technically-inclined. When your game isn't that extraordinary, you could try using an existing map-editor and either adopt its format or write a converter. This can save you considerable amount of work. For tile-based 2d maps, there is Tiled, for example.
3. **Create your content procedurally.** Instead of creating the content by hand, you write a program to generate the content for you based on random numbers. Making the content look naturally and interesting to play (or even playable at all) like it was generated by humans can be quite hard (again - depending on your requirements), but when you can pull it off you can create as much content as you want with the click of a button. You can also integrate the generation algorithm into the game itself and let the player generate new game worlds at will, greatly improving replay value.

---
Tags: tilemap, maps
---


title: OpenGL ES - read content of VBO

text:
# Question
Title: OpenGL ES - read content of VBO
Is it possible to read back content of VBO in OpenGL ES 2.0 ? I have tried `glMapBufferOES`, but there is no READ flag.

I dont want any answers, like "you shouldnt do it" or "keep copy of geometry in ram".

# Answer
> 2 votes
I have used `glMapBufferRange` EXT (on iOS it should be supported on all types of devices), instead of `glMapBufferOES` / `glUnMapBufferOES` with READ flag, and its working correctly

```
glBindBuffer( GL_ARRAY_BUFFER, buffer );
void * data = glMapBufferRange(GL_ARRAY_BUFFER, 0, vboSize, GL_MAP_READ_BIT);

//do someething with data

glBindBuffer( GL_ARRAY_BUFFER, 0 );

```

# Answer
> 1 votes
Regarding OpenGL ES `glMapBufferOES` is not part of the standard OpenGL ES but is actually an extension, regardless, it seems you can't use GL\_READ\_ONLY\_OES the only defined tokens according to the extension registry are

```
/* GL_OES_mapbuffer */
#ifndef GL_OES_mapbuffer
#define GL_WRITE_ONLY_OES                                       0x88B9
#define GL_BUFFER_ACCESS_OES                                    0x88BB
#define GL_BUFFER_MAPPED_OES                                    0x88BC
#define GL_BUFFER_MAP_POINTER_OES                               0x88BD
#endif

```

It seems you can only use GL\_WRITE\_ONLY\_OES, I suspect that you can memcpy returned pointer (since naturally speaking writing on a memory location require reading it first from a computer architecture point of view). ***This is only a speculation I didn't test it nor I guarantee it to work***. for example in semi-pseudo code:

```
GLvoid*  vbo = glMapBufferOES(GL_ARRAY_BUFFER, GL_WRITE_ONLY_OES);
for (int i = 0; i < count; i++) {
    memcpy( yourBuffer, vbo, 4*sizeof(GLfloat));
}

```

# Answer
> 0 votes
> I dont want any answers, like "you shouldnt do it" or "keep copy of geometry in ram".

You're going to be disappointed then because the GL ES specification and documentation don't define any way of reading back: http://www.khronos.org/opengles/sdk/docs/man/

At this stage you need to consider *why* you want to do such a readback; reading back from GPU memory is a slow operation, and if you really must do it, you may be better off just not using buffer objects at all (which is allowed by ES2).

---
Tags: opengl-es
---


title: RPG Equipped Item System

text:
# Question
Title: RPG Equipped Item System
I'm making a 2d rpg with libgdx and java. I have an Inventory class with an Array of Items, and now I want to be able to equip items onto the player. Would it be more managable to do

1. have every item have an "equipped" boolean flag
2. have an "equipped" array in the player class
3. have individual equipped fields in player class, e.g.

> private Item equippedWeapon;
> private Item equippedArmor;
> public void equipWeapon(Item weapon){ equippedWeapon = weapon; }

Or just another way completely? Thanks.

# Answer
> 3 votes
There is no correct answer. However, I believe design wise there are *better* ways to do this. Personally, I would use the 3rd method you described. It would allow you to easily switch out each kind of item. And, whenever calculating damage or some similar action you could have code such as:

```
if(equippedWeapon != null)
    Damage = BaseDamage + equippedWeapon.DamageModifier
else
    Damage = BaseDamage

```

I'm assuming there is a better way to do what I just wrote but you understand what I mean. Just comment if you have any more questions or want some form of clarification.

# Answer
> 1 votes
The best solution will obviously be whatever works for your system, but this is how I've done it in the past:

```
public class Equipment
{
    WornItem[] wornEquipment = new WornItem[EquipmentSlot.values().length];
    public void equip(WornItem wornItem)
    {
        wornEquipment[wornItem.equipmentSlot.ordinal()] = wornItem;
    }

    public WornItem get(EquipmentSlot equipmentSlot)
    {
        return wornEquipment[equipmentSlot.ordinal()];
    }
}
public class WornItem extends Item
{
    EquipmentSlot equipmentSlot;
    //Item's properties here
    //id
    //name
    //etc.
}

public enum EquipmentSlot
{
    Weapon, Head, Torso, Legs
}

```

So if you want to get your weapon, you do:

```
Weapon weapon = (Weapon) equipment.get(EquipmentSlot.Weapon)

```

my inventory class is a list of Items

```
List<Item> items

```

and `Weapon extends WornItem which extends Item`

---
Tags: java, libgdx
---


# Question
Title: XNA ModelMesh.Draw vs GraphicsDevice.DrawIndexedPrimitives
I am using XNA 4.0 and I wonder if drawing models with multiple meshes is better by filling the vertex and index buffers first and calling GraphicsDevice.DrawIndexedPrimitives() or by simply using good ol' foreach(...) {ModelMesh.Draw()}.

Is it possible to add data to vertex/index buffers at all in order to pack all the models on the scene in them and then call Draw only once per frame?

I would appreciate a link to an in-depth explanation. Thanks.

# Answer
What I was looking for is called "instancing" or "batching". It is indeed faster to pile geometry before calling "Draw". An example with source code can be found here:

http://jcoluna.wordpress.com/2011/11/17/xna-light-pre-pass-instancing/
> 0 votes

---
Tags: xna, 3d, models
---


# Question
Title: A*, Tile costs and heuristic; How to approach
I'm doing exercises in tile games and AI to improve my programming. I've written a highly unoptimised pathfinder that does the trick and a simple tile class.

The first problem i ran into was that the heuristic was rounded to int's which resulted in very straight paths. Resorting to a Euclidian Heuristic seemed to fixed it as opposed to use the Manhattan approach.

The 2nd problem I ran into was when i tried added tile costs. I was hoping to use the value's of the flags that i set on the tiles but the value's were too small to make the pathfinder consider them a huge obstacle so i increased their value's but that breaks the flags a certain way and no paths were found anymore.

So my questions, before posting the code, are:

1. What am I doing wrong that the Manhatten heuristic isnt working?
2. What ways can I store the tile costs? I was hoping to (ab)use the enum flags for this
3. The path finder isnt considering the chance that no path is available, how do i check this?
4. Any code optimisations are welcome as I'd love to improve my coding.

```
public static List<Tile> FindPath( Tile startTile, Tile endTile, Tile[,] map )
{
    return FindPath( startTile, endTile, map, TileFlags.WALKABLE );
}

public static List<Tile> FindPath( Tile startTile, Tile endTile, Tile[,] map, TileFlags acceptedFlags )
{
    List<Tile> open = new List<Tile>();
    List<Tile> closed = new List<Tile>();

    open.Add( startTile );
    Tile tileToCheck;

    do
    {
        tileToCheck = open[0];

        closed.Add( tileToCheck );
        open.Remove( tileToCheck );

        for( int i = 0; i < tileToCheck.neighbors.Count; i++ )
        {
            Tile tile = tileToCheck.neighbors[ i ];

            //has the node been processed
            if( !closed.Contains( tile ) && ( tile.flags & acceptedFlags ) != 0 )
            {
                //Not in the open list?
                if( !open.Contains( tile ) )
                {
                    //Set G
                    int G = 10;
                    G += tileToCheck.G;

                    //Set Parent
                    tile.parentX = tileToCheck.x;
                    tile.parentY = tileToCheck.y;
                    tile.G = G;
                    //tile.H = Math.Abs(endTile.x - tile.x ) + Math.Abs( endTile.y - tile.y ) * 10;
                    //TODO omg wtf and other incredible stories
                    tile.H = Vector2.Distance( new Vector2( tile.x, tile.y ), new Vector2(endTile.x, endTile.y) );
                    tile.Cost =  tile.G + tile.H + (int)tile.flags; //Calculate H; Manhattan style

                    open.Add( tile );
                }
                //Update the cost if it is
                else
                {
                    int G = 10;//cost of going to non-diagonal tiles
                    G += map[ tile.parentX, tile.parentY ].G;

                    //If this path is shorter (G cost is lower) then change
                    //the parent cell, G cost and F cost.
                    if ( G < tile.G ) //if G cost is less,
                    {
                        tile.parentX = tileToCheck.x; //change the square's parent
                        tile.parentY = tileToCheck.y;
                        tile.G = G;//change the G cost
                        tile.Cost =  tile.G + tile.H + (int)tile.flags; // add terrain cost
                    }
                }
            }
        }

        //Sort costs
        open = open.OrderBy( o => o.Cost).ToList();
    }
    while( tileToCheck != endTile );

    closed.Reverse();

    List<Tile> validRoute = new List<Tile>();
    Tile currentTile = closed[ 0 ];
    validRoute.Add( currentTile );

    do
    {
        //Look up the parent of the current cell.
        currentTile = map[ currentTile.parentX, currentTile.parentY ];
        currentTile.renderer.material.color = Color.green;
        //Add tile to list
        validRoute.Add( currentTile );
    }
    while ( currentTile != startTile );

    validRoute.Reverse();

    return validRoute;
}

```

And my Tile class:

```
[Flags]
public enum TileFlags: int
{
    NONE = 0,
    DIRT = 1,
    STONE = 2,
    WATER = 4,
    BUILDING = 8,

    //handy
    WALKABLE = DIRT | STONE | NONE,
    endofenum
}

public class Tile : MonoBehaviour
{
    //Tile Properties
    public int x, y;
    public TileFlags flags = TileFlags.DIRT;
    public Transform cachedTransform;

    //A* properties
    public int parentX, parentY;
    public int G;
    public float Cost;
    public float H;
    public List<Tile> neighbors = new List<Tile>();

    void Awake()
    {
        cachedTransform = transform;
    }
}

```

# Answer
> 2 votes
## What am I doing wrong that the Manhattan Heuristic isn't working?

The Manhattan distance doesn't work as a heuristic for A\*, as the heuristic for A\* must never overestimate the distance. But, the Manhattan distance is always larger or equal to the real distance.

The Manhattan distance would work, if you only allow 90 degree movements (left, right, up, down on the map). If you restrict your movements to 45 degree movements (straight and diagonal moves) on a chess-board map you can use the maximum of the difference in x and y coordinates like this: `max((x2-x1),(y2-y1))`. If you use the Euclidean Distance to calculate costs as an integer, use floor() for rounding "down" the number to the next integer value (should be equivalent to converting the float to an int).

If your map size is limited and you have a lot of RAM you could also use a lookup-table for x/y-Distances to Euclidean Distance. Or just to lookup the square roots (uses much less memory usage, but you'll still need to the multiplications):

Explanation (why overestimation isn't working): The estimation is used to sort the path-finding approaches in a way so that the first solution found, is the "shortest" path (or path with the lowest costs). This works by summing up the costs for the reaching the current position (of each approach) and the minimum rest costs, which might in fact be estimated as zero (0) but must never exceed the actual costs needed. When estimated as zero, the search is equivalent to breadth-first search. But, if the estimation would exceed the actual costs, the optimal approach is most likely put in too "late" into the priority queue and a suboptimal solution is found before it.

Explanation (why max works): If there are no obstacles you can always walk diagonal until you reached the column or row of the target tile and then move straight the rest of the way. This way you reach the target with the distance that is equal to the maximum of the distances of the x and y coordinates (between current position and target position). Note that this is only validated for tiles arrange in a chess boards fashion. If working with arrangements like octagons, this might be different!

## What ways can I store the tile costs? I was hoping to (ab)use the enum flags for this

Use a function (or lookup-table) that returns the costs for each type of tile.

```
int tileCosts(TileFlags flags) {
   switch (flags) {
     case TileFlags.DIRT: return COSTS_DIRT;
     case TileFlags.STONE: return COSTS_STONE;
     case TileFlags.STONE|TileFlags.DIRT: return COSTS_DIRTY_STONES;
     default:
          // Handle undefined flags error...
   }
}

```

You can also use a lookup-table instead of the function. How ever, both methods allow you to set the costs for any tile type/combination independent of the flags value AND it helps to keep your code readable. If you use "flags" as costs, you'll most likely produce faulty code.

## The path finder isn't considering the chance that no path is available, how do i check this?

You can check this, by checking if your "open" list is empty. If it becomes empty, there are no more possible solutions left that are worth investigating (the shortest path to each reachable tile on the map has been calculated.

## Any code optimisations are welcome as I'd love to improve my coding.

Your performance problems are most likely not due to the Euclidean Distance calculations but because of inefficient sorting of the "open" list. The sort function needs a lot of computation time. You can heavily improve the speed if you do not use "open.Add( tile );" and "open.sort()". Because this sorts the whole list when inserting a single tile (causing N\*log2(N) comparisons, if N = number of elements in the list). Instead you should "insert" the tile into the right position. This only needs to scan the list at most once (N comparisons). Instead of programming this your own you can either use the "merge" method of your list. To do that, insert your new tile into a new list and merge the list into the new list. Or, you can use a the container type "priority\_queue" instead (see http://www.cplusplus.com/reference/queue/priority\_queue/), which is what you are actually simulating...

As mentioned above, you should use functions for special and complex operations (e.g. getting the costs for traversing a tile). Never do something tricky without putting a source code comment next to it.

For example, this should be done in a function (or better: a method of the Tile class):

```
tile.Cost =  tile.G + tile.H + (int)tile.flags; //Calculate H; Manhattan style

```

You should also use speaking names for the properties of the tiles (what do "G", "H" mean? I have to look it up elsewhere or even have to guess what it could mean, which makes the code unreadable).

Keep your functions short! When editing a function you should see the whole function on the screen, without scrolling. They should each implement only -one- algorithm. For example **A\*** and nothing else! Everything else, as Manhattan Distance calculations should be put into separate functions/methods.

---
Tags: c#, tiles, path-finding, tilemap, optimization
---


# Question
Title: How to make natural-looking paths with A* on a grid?
I've been reading this: http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html

But there are some things I don't understand, for example the article says to use something like this for pathfinding with diagonal movement:

```
function heuristic(node) =
    dx = abs(node.x - goal.x)
    dy = abs(node.y - goal.y)
    return D * max(dx, dy)

```

I don't know how do set D to get a natural looking path like in the article, I set D to the lowest cost between adjacent squares like it said, and I don't know what they meant by the stuff about the heuristic should be 4\*D, that does not seem to change any thing.

This is my heuristic function and move function:

```
def heuristic(self, node, goal):
    D = 5
    dx = abs(node.x - goal.x)
    dy = abs(node.y - goal.y)
    return D * max(dx, dy)

def move_cost(self, current, node):
   cross = abs(current.x - node.x) == 1 and abs(current.y - node.y) == 1
   return 7 if cross else 5

```

Result:

The smooth sailing path we want to happen:

The rest of my code: http://pastebin.com/TL2cEkeX

---

**Update**

This is the best solution I have found so far:

```
def heuristic(node, start, goal):
    dx1 = node.x - goal.x
    dy1 = node.y - goal.y
    dx2 = start.x - goal.x
    dy2 = start.y - goal.y
    cross = abs(dx1*dy2 - dx2*dy1)

    dx3 = abs(dx1)
    dy3 = abs(dy1)

    return 5 + (cross*0.01) * (dx3+dy3) + (sqrt(2)-2) * min(dx3, dy3)

def move_cost(current, node):
    cross = abs(current.x - node.x) == 1 and abs(current.y - node.y) == 1
    return 7 if cross else 5

```

It produces the desired path from the second pic, but does not handle obstacles very well (tends to crawl on walls) and fails to produce optimal paths sometimes on longer distances.

What are some tweaks and optimizations I can apply to improve it?

# Answer
A\* gives you the shortest path in the graph. When using a grid as your graph there are often *multiple* shortest paths. In your first diagram, that *is* one of the shortest paths. It puts all the axial movements first and all the diagonal movements afterwards. But that's the same length path as if you put all the diagonals first, or if you mixed axial and diagonal movements. These are all equivalently short, and which one A\* picks depends on how the code is written and how the graph is represented.

I think what you're wanting is either:

1. You need to move on the grid, but you want to mix the axial and diagonal steps so that it looks better. One approach is to choose one of the other equally short paths; keep reading that Heuristics page to find “tie breaking”. Another approach is when you're evaluating neighbors, choose randomly which one to evaluate first so that it doesn't always pick one before the other. I do *not* recommend using Euclidean/Cartesian distance if you want to move on the grid; it's a mismatch that makes A\* run slower.
2. You don't need to move on the grid, and want to move in a straight line. One approach is to straighten out the paths using “string pulling”. You're looking for places where the path turns, and drawing straight lines between those points. Another approach is to apply this to the underlying graph itself. Instead of pathfinding on the grid, pathfind on the key points on the map, and then move along straight lines between those key points. You can see an example here. Yet another approach is the Theta\* algorithm.
> 10 votes

# Answer
The A\* algorithm allows you to assign different costs to path edges. You can also assign costs depending on circumstances. This is your main tool to shape A\* paths into looking the way you want them to look.

When you want to discourage long diagonals, you can penalize them. Add a tiny bit of cost for each time the path goes into the same direction. When you do this, the algorithm will automatically try to distribute diagonal steps as evenly as possible over the whole path. Just make sure this additional cost is never more the the cost of taking an additional edge, or the algorithm will start to make completely unnecessary detours just to avoid straight lines.

A good formula could be:

`cost = normal_cost * (1.1 - 0.1 / num_of_steps_in_the_same_direction`)

Note that this requires that the path-cost is tracked as floating-point values, not as integers.
> 2 votes

# Answer
## Adapting A\*

As Philipp said, you should add costs when the direction doesn't change for long time. But, the function by Philipp may quickly lead to summing up additional costs, that are higher than the cost for traversing an additional tile. But his key idea is correct!

It seems easy to adapt A\* to calculate "all" optimal paths (with shortest length) and then selecting one of them by another heuristic. But there is a problem. If you have a long path, there might be a lot of solutions with optimal length. This causes the A\* algorithm to take much longer to compute all these other solutions, too. This is because the grid. You can not walk 80 degrees instead of 90 degrees, which leads to multiple suboptimal solutions instead of one optimal solution. For imagination, imagine a map without obstacles. The x-distance is 2 the y-distance is 3. This means, all shortest paths have 2 diagonal moves and 1 straight move. There are 3 valid combinations: S-D-D, D-S-D, D-D-S (where D=diagonal, S=straight) for this simple path. The real "fun" starts already when you have paths with e.g. 3 straight and 2 diagonal moves: S-S-S-D-D, S-S-D-S-D, S-S-D-D-S, S-D-S-S-D, S-D-S-D-S, S-D-D-S-S, D-S-S-S-D, D-S-S-D-S, D-S-D-S-S, D-D-S-S-S (10 variations of the shortest path, if I didn't miss any). I think you should have got the idea...

So we should fix this by adapting the cost function in a way that fewer solutions (or even only one solution) are "optimal".

## Adapting the Cost Function

Doing the adaptation as Philipp suggests in his example formula will give you much better results, but has still some problems. It will not evenly distribute the shorter/longer "parts" along the path, meaning: the direction changes will be more often at the beginning of the path or vice-versa.

Additionally, a path with endlessly having the actor to "turn" seems to be suboptimal when observed by a human. As it takes time (to show the turn animation) and therefore it must be slower.

How ever, instead of using floats for the costs you can implement a "secondary cost" or secondary sort criteria. If the primary costs are the same the secondary cost is used to estimate which solution is to be preferred. This will not accidentally cause the primary costs (route length in grid measure) to increase.
> 1 votes

---
Tags: path-finding, python
---


# Question
Title: Trying to create a sphere in UDK on which I can stand
Trying to build a globe in UDK, but when I do (create a sphere), my player falls straight through it. How do I make a sphere that I can walk on? Every other shape (cube, cone...etc) work just fine.

--

**Edit:** Specifically, I want to build a CSG/Brush sphere, not a mesh sphere. It appears to work just fine if I set the "sphere exptrapolation" to 1 or 2, but if I bump it up to 3 or higher, I fall right through. I literally created 2 spheres next to each other, one set at "2" and one at "3" - I can walk from the top of the "2" sphere and jump onto the "3" sphere, but I fall right through it.

# Answer
I have had the same problem, Dave. There are two options and they both involve creating a static mesh sphere. Either, you can create a sphere object with third-party software or you can create it with UDK. To create it with UDK:

1. Click BSP Sphere
2. Pick optimal sphere extrapolation
3. CSG Add
4. Right-click the BSP sphere and go down to Convert \> Convert to Static Mesh
5. Pick package to save to and click OK
6. Double-click the sphere static mesh in the content browser
7. Go to Collision \> Sphere Simplified Collision
8. Go to the right-side options on the Mesh Editor
9. * uncheck Simple Box Collision
    * uncheck Simple Line Collsion
    * uncheck Simple Rigid Body Collision

You can now walk on the sphere. BSP spheres, especially with high extrapolation, are hyper-slow.
> 4 votes

# Answer
This what I have found:

"If you double click on the mesh you are talking about int he Content Browser, a new window will pop up. This window is your Mesh Editor. On the mail Tool Menu Bar, you will see a *Collision drop down menu*. From there pick the collision you want to use, and then save you package the mesh is in. Now, that mesh, even in your scene should have collision, and you should not be able to pass through them.

Also, if you right click on your mesh in the view port, and choose properties. You will find a Check box in there named *Can Stand up on*. This will also help sometimes if your collision is built but you can still pass through the model."

http://forums.epicgames.com/threads/837455-Problem-Fall-Through-Object-s
> 3 votes

# Answer
Even without any experience on UDK, I can tell you that if you are walking over something, then gravity should not be calculated for your character: gravity should be applied ONLY to objects which are NOT standing over anything else...

Imagine a wall of bricks, where each brick is dynamic and then you calculate gravity for every brick in every frame... they won't look like a wall, but a lot of jumping bricks! Float precision makes it even worse and you'll never reach 0 vertical speed, so you have to clear the speed to 0 and remove any gravity calculations for objects standing on some kind of horizontal or not-so-steep surface (then you reactivate it when you JUMP, for example).

I've posted something in another question about something similar, maybe it also helps:: Handling collisions with ground

I don't know how UDK handles this kind of stuff, but if you can control gravity for a particular object and be told about collisions with the sphere to your character, you'll be able to prevent that behavior from happening.
> 0 votes

# Answer
Easy to do, just dont use the simple sphere collision, use the things with "Auto" and make yourself a collision box. Else you can also make your own collision box in blender or any 3D program by using an object with a name starting by "UCX\_". The simple sphere collision doesn't allow player to collide at all.
> 0 votes

---
Tags: collision-detection, udk
---


# Question
Title: Clientside anticheating in multiplayer game 1vs1
I'm developing a simple card game, where there will be a matchmaking system that will put you against another human player. This will be the only game mode available, a 1vs1 against another human, no AI.

I want to prevent cheating as much as possible. I have already read a lot of similar questions here and I already know that I cannot trust the client and I have to make all verifications server side. I intend to have a server (need one for the matchmaking anyway) and I intend to make some verifications server side but if I want to check everything server side this makes my server to be able to keep track of the state of all current games and check every action, and I don't have the money/infrastructure to support that server.

My idea is to make clients check and verify some of the actions made by their opponent\* and if they find some illegal action notify the possible cheating to the server and make the server verify it. This will still require my server to keep track of all current games, but it will save resources only checking some things that cannot be checked at client side(like card order in the deck) and only checking other things when they are actually wrong.

\*(only those they can check with out allowing themselves cheating! for example:they can't check if the played card was in hand cos that will need them to know all cards in hand)

**Summing up, my questions are**: is this a viable approach? will I actually save resources doing this or the extra complexity in the server and client for exchanging this messages is not worth it? do you know any game that has successfully or unsuccessfully tried a similar approach?

Thanks all for reading and answering

# Answer
Depending on the complexity of your game, verifying if an action is legal or not might require to backtrack large parts of the game. An example: *Player A says Player B can't play that card right now because he has no ResourceX. PlayerB says he has plenty ResourceX. Who is right?* To find out you would simulate the whole game again from start to finish to count the ResourceX the PlayerB has right now. So only verifying the players actions when one cries "foul" might not actually be that much of an optimization.

But is the effort really worth it?

I think you might have a case of premature optimization here. Although I don't know exactly what you are up to, a card game is usually not that computationally expensive on the server-side.

Card-games are usually designed to be played without computer support, so their game mechanics are usually computationally simple enough to be performed by humans\*. Also, human players usually take several seconds to make a move, which feels like eternity for the server. That means your server has only a light-weight task to perform every few seconds per game. I don't know how many simultaneous players you expect, but as long as you are still in the scale of a non-commercial hobby project, I doubt that even the cheapest server you can find won't be able to handle it. On the premise, of course, that you know how to program efficiently.

\*) as long as you exclude the players decision-making. Most games are build on the premise that the ideal winning strategy can theoretically be computed, but doing so is so complex that players and often even computers are unable to do so, so they need to use intuition. But you said you want no AI and only want player-vs.-player, so this is outside of the scope of this question. But it also makes one think about another cheating-aspect: Did you consider a player using a program to help them with decision-making? Like one which tells them the exact probability that the opponent has a certain card on hand?
> 8 votes

# Answer
"I want to prevent cheating as much as possible." - So say we all. :)

Perhaps a more sensible approach is to not waste time doing anything above and beyond the reasonable and generally effective anti-cheating measures.

Those are: double-testing for bugs that would allow players to perform any illegal actions, and sending only encrypted data (via https or custom encryption), and encrypting the app itself to make hacking more difficult. That's it.

**Players are most likely to cheat through bugs in the game than anything else.**

You might simply do better, development-wise, to wait whether your players actually care enough to cheat. If the app is not in a figurative "top 500 chart" and cheating isn't dead simple (ie bugs) players won't care enough to waste their time trying to cheat through other measures, such as modifying the IP stream or hacking the app.

Unless of course you're dealing real money and actual prizes here.

If your app is successful and cheating does become a problem, that's when you should tackle it. But at this point it's going to be a cat & mouse game, and the cheaters will always win.

Basically what I'm saying is that 100% of your players won't cheat if it isn't possible through a reproducible bug and/or your app is not very popular. If your app does become very popular, less than 1% of your players will cheat in ways you can't even begin to imagine.

So as far as cheating goes, you should protect yourself against the obvious cheats (bugs, encrypting both app and IP stream) and only react to actual cheats you learn of, and address those directly. What you really want is to log all player actions, have them verify on the server and if you find an illegal action that is occuring rather often, find out why. Could be a bug, could be an exploit, could be a technical hack.

The most important anti-cheating measure is learning that players actually DO cheat, and how.
> 4 votes

# Answer
I think you are running into some other problems here. What if the player is faking to be a normal client (by simulating your network traffic) and is using to corrupt your game by wrong validiation?

Instead of trying to build a bullet proof client system, which will lead you to continious bug / exploit fixing and banning, I would try to simplify the server system. I do not know enough about your game mechanic, but maybe you are able to boil the information on the server down to a minimum.

In general you should assume that the client you are talking to could deploy any code and game mechanic it feels like deploying. And this makes client side validiation nearly impossible
> 0 votes

# Answer
It depends a bit on what you consider as cheating. Is it using a tool to make/calculate the moves? Is it to change the deck of cards during the play? The first thing will be difficult to tackle. For the second one you can think about having each user insert it's cards and make a hash-code that is displayed on both sides. At the end the server can calculate the hash with the played cards and cards left. If a hash does not match then the user has cheated. If the rules were not followed then you can check this on your server too. You can do this on a user request to save resources. No information on the cards become available. To make the generation of the hash a bit more unique/complex you can include the username in the hash.
> 0 votes

---
Tags: multiplayer, card-game, anti-cheat
---


# Question
Title: LWJGL - Continuous key press event without delay
I am checking for key presses and then based on the keys pressed I am moving a square around the screen. I am setting booleans for the keys WASD. But , Whenever I try to keep the key down , it takes a while till it moves continuously (Just a half second stop after a single move.) Any way to get rid of that and make it be "smooth"? Code:

```
 up = false;
 down = false;
 left = false;
 right = false;
 reset = false;

 while(Keyboard.next()){
     if (Keyboard.getEventKeyState()) {
        if(Keyboard.isKeyDown(Keyboard.KEY_SPACE)){
             reset = false;
        }
         if(Keyboard.isKeyDown(Keyboard.KEY_W)){
            up = true;
        }
        if(Keyboard.isKeyDown(Keyboard.KEY_S)){
            down = true;
         }
         if(Keyboard.isKeyDown(Keyboard.KEY_A)){
            left = true;
        }
        if(Keyboard.isKeyDown(Keyboard.KEY_D)){
            right = true;
        }
     }
}

```

# Answer
> 1 votes
Since you're checking for events each update, you'll be relying on the key repeat events to start your continuous movement. That means that an event will be generated when the key is first pressed, then the repeat events will be created after a short delay.

So, try removing your check `if (Keyboard.getEventKeyState())` and the `while(Keyboard.next())` loop (that one is actually unnessary for how you're using the `Keyboard` class right now). That will allow the checks to operate without the event being triggered (thus bypassing the delay).

---
Tags: opengl, java, lwjgl, keyboard
---


# Question
Title: how to check if a gameserver can handle clients before game release?
we are developing an iOS-based game with multiplayer support. so far everything seems real good but now we want to make sure if server could handle 10000 clients or not. any idea how can I make sure server will survive that much traffic?

# Answer
For traffic load testing there are many tools, but you're going to need to test other things as well that will be specific to your game server because network traffic is only one part of the equation -- the processor utilization and constant database queries are two others that immediately come to mind as important factors that you'll want to measure (there will undoubtedly be other factors as well, which you'll have to determine based on your knowledge of how your game server works).

A really good way to do this might be to write a "**game player simulation**" client program and run multiple instances of it on multiple computers. The down side is that this could require the use of a lot of computers, but some local universities might have big computer labs that you could run these on (the professor might be interested in your test results since university professors tend to be genuinely curious about good research).

Your client may not need to be as sophisticated as a player, but you may want to make sure it does the following things (it doesn't have to be very intelligent as long as it can be slightly more functional than a drunk software developer who really shouldn't be driving herself home, so you might also want to flag the characters in a special way so that they can do silly things like walk through walls, have unlimited budgets to buy randomly selected goods from in-game merchants, have endless supplies of ammunition, and whatnot):

* Send random chat text on a randomly timed basis
* **Navigate in random directions** throughout the world (but tend to stay closer to major cities)
* Randomly choose to fire weapons in random directions when other players are nearby
* Buy/sell random goods from merchants, and occasionally **dump items** throughout the world
* Randomly **light things on fire** (or cause other forms of localized destruction)
* Get hordes of wild animals upset and run into a busy town with them chasing after, then randomly decide whether or not to logout (if chosen to logout, perhaps those wild animals will start attacking others in the town?)
* Heal injured players
* Set off randomly selected magic spells in crowded places
* Cook raw food, process raw lumber and other materials (such as from mining), etc.
* ...other simple tasks that your players are likely to do regularly

If you estimate that you'll have 9,000 players at one time, try to test this out with at least 3 times that number so that you'll know how your servers can handle a load of 27,000 simulated busy players (a lot of players tend to idle, especially the social types).

Also (**and this is very important**), if you do this, please, please, PLEASE, login with a regular character and record a video of all these computerized players doing stupid things and share that video with us here so we can have a good laugh (I'm thinking that "*drunken barn dance*" might be a good title for this movie if you can find just the right in-game scenario)! ;-D
> 17 votes

# Answer
This is an answer for an old question, hope it can be useful for those who get here by search engine. Netgend has a performance test platform can emulate 50,000 VUsers and can do all the flexible client emulations.

See the blogs, especially

* Networking made easy
* extracts fields from server responses
* Performance testing with binary data

Note that the message processing is not restricted to http messages, it applies to all messages.

Hope it's helpful.
> 0 votes

---
Tags: server, testing
---


# Question
Title: Why is my Tiled map distorted when rendered with LibGDX?
I have a Tiled map that looks like this in the editor:

But when I load it using an `AssetManager` (full static source available on GitHub) it appears completely askew.

I believe the relevant portion of the code is below. This is the entire method; the others are either empty or might as well be.

```
private OrthographicCamera camera;
private AssetManager assetManager;
private BitmapFont font;
private SpriteBatch batch;
private TiledMap map;
private TiledMapRenderer renderer;

@Override
public void create() {
    float w = Gdx.graphics.getWidth();
    float h = Gdx.graphics.getHeight();

    camera = new OrthographicCamera();
    assetManager = new AssetManager();
    batch = new SpriteBatch();
    font = new BitmapFont();

    camera.setToOrtho(false, (w / h) * 10, 10);
    camera.update();

    assetManager.setLoader(TiledMap.class,
            new TmxMapLoader(
                    new InternalFileHandleResolver()));
    assetManager.load(AssetInfo.ICE_CAVE.assetPath, TiledMap.class);
    assetManager.finishLoading();

    map = assetManager.get(AssetInfo.ICE_CAVE.assetPath);

    renderer = new IsometricTiledMapRenderer(map, 1f/64f);
}

```

# Answer
Is your tiled map isometric or it is orthographic ?

if it is orthographic use orthographic tiledmap renderer .

---

More specifically, change

```
renderer = new IsometricTiledMapRenderer(map, 1f/50f);

```

to

```
renderer = new OrthogonalTiledMapRenderer(map, 1f/50f);

```
> 7 votes

---
Tags: rendering, libgdx, tilemap
---


# Question
Title: How should I manage persistent score in Game Center leaderboards?
Let's say that I'm developing an iOS RPG where the player gains 1 point per monster kill.

The amount of monsters killed is persistent data: it is an endless adventure, and the score keeps on growing. It isn't a "session score" like Fruit Ninja, but rather a "reputation score".

There are Game Center leaderboards for that score. Keep killing monsters, your score goes up, and the leaderboards are updated.

My problem is that, technically, you can log out and log in using a different Game Center account, kill one monster, and the leaderboards will be updated **for the new GC account**.

Supposing that this score is a big deal, this could be considered as cheating, because if you have a score of 2000, any of your friends who have never played the game can simply log into your iPhone, play the game, and the system will update the score for their accounts, essentially giving them 2000 points in the leaderboards for doing nothing.

I have considered linking one GC account to a specific save game. It won't update your score unless you're using the linked GC account. But what if the player actually needs to change their GC account? Technically they would be forced to start a new game and link their account to that profile.

How should I prevent this kind of cheat? Essentially, I don't want someone to distribute a high schore to multiple GC accounts, given the fact that the game updates the score constantly since it isn't a "session score".

I do realize that it isn't quite a big deal. But I'm curious about how to avoid this.

# Answer
> 1 votes
Well, any time you need persistent data that usually means you need to write it to a file.

What I would do, is make a dictionary of dictionaries and write that to a file. The main dictionary will hold the keys of each username, and the value fields will hold the high scores in a dictionary. That is, assuming you have more than one high score per user, maybe a top ten high scores. You might also be able to get away with a dictionary of lists.

If you only have one high score per username, you can just use a regular dictionary with the username as the key and the high score as the value.

Since you are developing iOS, you *should* write to a plist since they are pretty easy to read and write from, but it's ultimately up to you.

Hope this gives a nudge in the right direction.

---
Tags: ios, leaderboards, game-center
---


# Question
Title: Limiting the speed of a dragged sprite in Cocos2dx
I am trying to drag a row of sprites using ccTouchesMoved. By that I mean that there is a row of sprites (they are colored squares) lined up next to each other and if I grab one with a touch the rest follow it. If a sprite moves off screen I want to append it to the rest of the sprites in formation. However, if the sprite formation moves too fast it creates a slight gap between it and the appended sprites. How do I go about limiting the speed that I can drag the sprite with ccTouchesMoved? This is the only solution I could think of to my problem. If anyone has another suggestion to prevent this sprite gap from happening I would appreciate it.

In ccTouchesBegan I loop through the sprites, mark the one that is touched(used for another part of game), and save the distance between the touch point and every other sprite.

```
touch = (CCTouch*)(touches->anyObject());
location = touch->getLocation();
for (int i = 0; i < grid->getGridSizeY(); i++) {
    for (int j = 0; j < grid->getGridSizeX(); j++) {
        button = grid->button(i, j);
        button->setDistanceX(location.x-button->getPositionX());
        button->setDistanceY(location.y-button->getPositionY());
        if (button->boundingBox().containsPoint(location)) {
            button->setTouched(true);
        }
    }
}

```

Then in ccTouchesMoved I loop through all the sprites again and set them to always be the same saved distance from the touch point.

```
touch = (CCTouch*)(touches->anyObject());
location = touch->getLocation();
for (int i = 0; i < grid->getGridSizeY(); i++) {
    for (int j = 0; j < grid->getGridSizeX(); j++) {
        button = grid->button(i, j);
        button->setPositionX(touchLocation.x - button->getDistanceX());
        button->setPositionY(touchLocation.y - button->getDistanceY());
        }
    }
}

```

This is the update method code only for a sprite moving off the left side of the screen. No point in writing all the sides until I get one side to work:

```
for (int i = 0; i < grid->getGridSizeY(); i++) {
    for (int j = 0; j < grid->getGridSizeX(); j++) {
        button = grid->button(i, j);
        //Replaces button if it goes off left side of grid
        if (button->getPositionX() < grid->button(0, 0)->getPositionX() - button->boundingBox().size.height / 2) {
            button->setPositionX(grid->button(grid->getGridSizeY() - 1, 0)->getCoord().x + button->boundingBox().size.height / 2);
            button->setDistanceX(location.x-button->getPositionX());
        }
    }
}

```

# Answer
It turns out the issue was being caused by

```
button->setDistanceX(location.x-button->getPositionX());

```

Since the distance was set regarding the touch location instead of the position of the sprite itself, if the touchlocation moved too fast it caused a gap depending on how fast it was moving, since the touchlocation updates before the sprite position. All I had to do was change the distance to be set relative to the sprite position instead of the touch position and it works flawlessly now.
> 1 votes

---
Tags: sprites, movement, cocos2d-x
---


# Question
Title: Black or White Border/Shadow around PNGs in SDL/OPENGL
having the same issue as this: Why do my sprites have a dark shadow/line/frame surrounding the texture? however, when I do the fix suggested there (changing GL\_SRC\_ALPHA to GL\_ONE) it just replaces the black border with a white border on the images. was able to find a lot of results on google from people finding black borders and fixing it with the GL\_ONE change, but no results for white borders. any ideas?

heres some of my relevant code.

init:

```
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glEnable(GL_DEPTH_TEST);
glEnable(GL_MULTISAMPLE);
glEnable(GL_TEXTURE_2D);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glAlphaFunc(GL_GREATER, 0.01);
glEnable(GL_ALPHA_TEST);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);

```

when each texture is loaded:

```
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_2D, textureID);
gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, surface->w, surface->h, GL_BGRA, GL_UNSIGNED_BYTE, surface->pixels);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

```

thanks!

# Answer
It seems you are using non-power of 2 texture dimensions and mipmapping which calls for trouble because the minifying interpolation has incomplete information along the edges. Prefer to manually expand all textures to power of 2 before loading. Use the desired color for those padding pixels.

If you have many small textures of arbitrary dimension it might also be a good idea to create a single power of 2 texture atlas.
> 3 votes

---
Tags: opengl, sdl, png
---


# Question
Title: What Type of Options should be on the Game Settings Menu?
I have seen a post about the main menu options here: UI: Main Menu options for mobile games. What options should be listed? What do users want to see?

But I want to know what kind of options should/need to be available on the settings screen.

I am making a rather simple 2D game for Android, but really I haven't found many aspects that warrant an options button or a check box besides turning the sound and music on/off. I was thinking graphics settings but then again, how many apps really need graphics settings besides immersive 3D ones?

# Answer
Keep your options/config as simple as possible and include only what all players would likely use, such as volume.

That said, it may be a good idea to add an **Advanced** or **Extra** button that takes the user to an extra config screen where you could add many different things that the average user may never want/need (such as resetting progress, tweaks for different device sizes, etc). Because mobile devices (and their users) are so varied it may benefit you to have options that allow them to customize their experience.

In the end, it will largely depend on your game and it's intended audience. If it is a really simple game, and volume is your only option, it might be best to just include it on the main screen and skip the options screen - or even better, just have a mute button available at all times (main menu, pause menu, etc) since most mobile devices can handle volume manually.
> 3 votes

---
Tags: android, game-design, menu
---


# Question
Title: a flexible data structure for geometries
What data structure would you use to represent meshes that are to be altered (e.g. adding or removing new faces, vertices and edges), and that have to be "studied" in different ways (e.g. finding all the triangles intersecting a certain ray, or finding all the triangles "visible" from a given point in the space)? I need to consider multiple aspects of the mesh: their geometry, their topology and spatial information.

The meshes are rather big, say 500k triangles, so I am going to use the GPU when computations are heavy.

I tried using arrays with vertices and arrays with indices, but I do not love adding and removing vertices from them. Also, using arrays totally ignore spatial and topological information, which I may need studying the mesh. So, I thought about using custom double-linked list data structures, but I believe doing so will require me to copy the data to array buffers before going on the GPU. I also thought about using BST, but not sure it fits.

Any help is appreciated. If I have been too fuzzy and you require other information feel free to ask.

# Answer
Depending on your needs there are different data structure that you can use for geometry representation, before I answer your question I need to point out that geometric representation are usually chosen based on two basic factors,

1. **Topological Requirements**: this includes the types of meshes you are going to store, triangles only? n-polys ? regular, irregular or semi regular?
2. **Algorithmic Requirements**: Some algorithms work better on some data structure than other. This strictly depends on the type of the algorithm and you may want to use different data structures for different algorithms. For example you need to ask yourself if the structure/algorithm needs a pre-processing step? the time needed to answer specific query such as the adjacent edges of a vertex, edge ?

I will try to concisely list the most important mesh representations, while pointing out their pros and cons:

* **Face Based**: The simplest form stores a set of faces, it can store faces(indices) and separate vertices or you can simply construct faces using vertex positions, this structure is more suitable to store one type of face/polys (e.g. tri) otherwise the implementation becomes complex with little benefit.

**Pros**: Cache friendly(usually). Efficient to store in memory, used in many file formats (e.g. Obj, VRML). Maps nicely to GPU rendering, usually used in games.

**Cons**: Edges and connectivity info are implicit and not explicitly defined making some geometric queries expensive to compute, Cannot store irregular meshes.
* **Edge Based**: This defines a face in terms of the edges making a face, each edge stores a reference for it two end point vertices. It's also common for a vertex to have a reference for it's owner edge this is great for efficiently traversing the data structure. An example implementation is the winged-edge data structure. Edges can also store reference to the next and previous edges, which makes good candidate for traversing the structure.

**Pros**: Can represent arbitrary polygon, good for traversing adjacent edges.

**Cons**: Not so great for memory consumption, traversing a ring still needs distinctive cases. Requires extra processing for GPU rendering.
* **Half-Edge Based**: Similar to Edge-Based with the very important distinction that it defines each edge as a two distinct directed Half-Edges instead of a bidirectional single Edge.

The importance boils down to that Half-edges are oriented consistently in counter-clock wise around each face modelling a ring-loop explicitly, and hence making traversal easier by avoiding some extra cases like asking at which vertex in the face are we standing. Getting a good implementation for this structure is hard so I recommend using OpenMesh which is a great implementation of the structure and many other algorithms.

**Pros**: Great flexibility with traversal that other structures lack, can model arbitrary polygons, can explicitly model empty faces. Some implementations (AFAIK) can model irregular meshes. Great for geometric algorithms, and makes it easy to mix faces of different vertex count in one mesh.

**Cons**: Harder to implement, not so memory friendly, and usually requires a lot of Heap allocations. Requires extra processing for GPU rendering.

A sample implementation for the half-edge data structure would look like this:

```
    struct Vertex
    {
       Vector3      Position;
       HalfEdge*    halfedge; // outgoing halfedge
    };

    struct HalfEdge
    {
      Vertex*   vertex;
      Face*     face;
      HalfEdge*   next;
      HalfEdge*   prev;
    };

    struct Face
    {
      HalfEdge*   halfEdge; // any halfedge
    };

```
* There is also **Directed Edge Data Structure**, which is a memory efficient implementation of the half edge that is designed for triangle meshes.

As a final note, **I recommend Half-Edge or Directed Edge (if triangles only) for geometric processing**, but depending on your application you may need multiple representations, since for example Half-edge are not particularly great for GPU rendering/streaming and may require extra processing for rendering.
> 7 votes

# Answer
Half-edges are usually used for many serious geometrical analysis and modification algorithms.

You may find it more convenient to add a higher-level abstraction layer on top of this if you don't want to work with half-edges directly.
> 5 votes

---
Tags: geometry, data-structure, computational-geometry, c++, gpgpu
---


title: Improving Click and Drag with C++

text:
# Question
Title: Improving Click and Drag with C++
I'm currently using SFML 2.0 to develop a game in C++. I have a game sprite class that has a click and drag method. The method works, but there is a slight problem. If the mouse moves too fast, the object the user selected can't keep up and is left behind in the spot where the mouse left its bounds. I will share the class definition and the given function implementation.

Definition:

```
class codePeg
{
protected:
    FloatRect bounds;
    CircleShape circle;
    int xPos, yPos, xDiff, yDiff, once;
    int xBase, yBase;
    Vector2i mousePos;
    Vector2f circlePos;
public:
    void init(RenderWindow& Window);
    void draw(RenderWindow& Window);
    void drag(RenderWindow& Window);
    void setPegPosition(int x, int y);
    void setPegColor(Color pegColor);
    void mouseOver(RenderWindow& Window);
    friend int isPegSelected(void);
};

```

Implementation of the "drag" function:

```
void codePeg::drag(RenderWindow& Window)
{
mousePos = Mouse::getPosition(Window);
circlePos = circle.getPosition();

if(Mouse::isButtonPressed(Mouse::Left))
{
    if(mousePos.x > xPos && mousePos.y > yPos
        && mousePos.x - bounds.width < xPos && mousePos.y - bounds.height < yPos)
    {
        if(once)
        {
            xDiff = mousePos.x - circlePos.x;
            yDiff = mousePos.y - circlePos.y;
            once = 0;
        }
        xPos = mousePos.x - xDiff;
        yPos = mousePos.y - yDiff;
        circle.setPosition(xPos, yPos);
    }
}
else
{
    once = 1;
    xPos = xBase;
    yPos = yBase;
    xDiff = 0;
    yDiff = 0;
    circle.setPosition(xBase, yBase);
}
Window.draw(circle);
}

```

Like I said, the function works, but to me, the code is very ugly and I think it could be improved and could be more efficient. The only thing I can think of as to why the object cannot keep up with the mouse is that there are too many function calls and/or checks. The user does not really have to move the mouse "fast" for it to happen, I would say at an average pace the object is left behind. How can I improve the code so that the object remains with the mouse when it is selected?

Any help improving this code or giving advice is greatly appreciated.

# Answer
> 6 votes
You have to implement behavior for when it was pressed last frame, pretty much.

something like

```
void codePeg::drag(RenderWindow& Window)
{
mousePos = Mouse::getPosition(Window);
circlePos = circle.getPosition();

if(Mouse::isButtonPressed(Mouse::Left))
{

    if(***pressedLastFrame ||***
        mousePos.x > xPos && mousePos.y > yPos
        && mousePos.x - bounds.width < xPos && mousePos.y - bounds.height < yPos)
    {
        if(once)
        {
            xDiff = mousePos.x - circlePos.x;
            yDiff = mousePos.y - circlePos.y;
            once = 0;
        }
        xPos = mousePos.x - xDiff;
        yPos = mousePos.y - yDiff;
        circle.setPosition(xPos, yPos);
    }
    ***pressedLastFrame = true;***
}
else
{
    once = 1;
    xPos = xBase;
    yPos = yBase;
    xDiff = 0;
    yDiff = 0;
    circle.setPosition(xBase, yBase);
    ***pressedLastFrame = false;***
}
Window.draw(circle);
}

```

That way, when it's been pressed already and you go out of bounds, it won't lose the connection with the drag.

---
Tags: c++, game-design, sfml
---


title: Unity 2D sprite support?

text:
# Question
Title: Unity 2D sprite support?
Does Unity 3D support 2D sprites yet? I know that they have mentioned it in a blog post but I don't know if that feature has gone live yet

# Answer
> 4 votes
2D sprites, or point sprites in 3D?

3D: Unity supports point sprites as billboards, by rotating the necessary geometry to face the camera; presumably point sprites could also be implemented more efficiently via a fragment shader.

2D: Unity 2D Toolkit OR Sprite Manager are the basic go-to points for anyone wanting to write 2D games under Unity.

P.S. The feature you mention is expected to be in the 4.3 release, which isn't out just yet.

---
Tags: unity
---