title: why is glVertexAttribDivisor crashing?

text:
# Question
Title: why is glVertexAttribDivisor crashing?
I am trying to render some trees with instancing. This is rather weird, but before sleeping yesterday night, I checked the code, and it was in a running state, when I got up this morning, it is crashing when I am calling `glVertexAttribDivisor` I haven't changed any code since yesterday.

Here is how I am sending data to GPU for instancing.

```
    glGenBuffers(1, &iVBO);
    glBindBuffer(GL_ARRAY_BUFFER, iVBO);
    glBufferData(GL_ARRAY_BUFFER, (ml_instance->i_positions.size()*sizeof(glm::vec4)) , NULL, GL_STATIC_DRAW);
    glBufferSubData(GL_ARRAY_BUFFER, 0, (ml_instance->i_positions.size()*sizeof(glm::vec4)), &ml_instance->i_positions[0]);

```

And then in vertex specification--

```
    glBindBuffer(GL_ARRAY_BUFFER, iVBO);
    glVertexAttribPointer(i_positions, 4, GL_FLOAT, GL_FALSE, 0, 0);
    glEnableVertexAttribArray(i_positions);
    glVertexAttribDivisor(i_positions,1); // **THIS IS WHERE THE PROGRAM CRASHES**

    glDrawElementsInstanced(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0,TREES_INSTANCE_COUNT);

```

I have checked `ml_instance->i_positions`, it has all the data that needs to render.

I have checked the value of `i_positions` in vertex shader, it is the same as whatever I have defined there.

I am little out of ideas here, everything looks pretty much fine. What am I missing?

# Answer
I ran the program in debug mode, and found out that `glVertexAttribPointer` was NULL. After restarting my windows the program started running like it was before.

I am using glew along with win32 in VS2008, but one thing i do not understand is, why glVertexAttirbPOinter was NULL? I was initializing glew properly. and it was getting initialized everytime i started the program. Why i wasn't gettinga valid address for that method?
> 0 votes

---
Tags: opengl, c++, glsl, vertex, instancing
---


# Question
Title: How can I make a snake's tail follow the head?
Following an assignment and just getting started with libGDX by building a small Snake clone I've run into an issue that I'll probably be ashamed for in a little while.

I currently have a snake's head (a simple rectangle at this stage) moving around the game's canvas. The most straight-forward way of building the rest of the snake was to have the head own a Java Collections LinkedList of SnakeElements which would in-/decrease in size according to what the player does.

Having this list of SnakeElements follow the head however has proven to not be trivial.

The current function doing this is as follows and is called every time the head updates its position:

```
private void moveTail (float x, float y, int direction) {
    float tmpx, tmpy;
    int tmpdirection;
    int offset_x, offset_y;

    for (SnakeSegment snse : tail) {
        offset_x = 0;
        offset_y = 0;

        tmpx = snse.getX();
        tmpy = snse.getY();
        tmpdirection = snse.getDirection();

        switch(direction) {
            case 0:
                offset_x = 0;
                offset_y = -(2 + snse.width);
                break;
            case 1:
                offset_x = -(2 + snse.width);
                offset_y = 0;
                break;
            case 2:
                offset_x = 0;
                offset_y = (2 + snse.width);
                break;
            case 3:
                offset_x = (2 + snse.width);
                offset_y = 0;
                break;
            default:
                System.out.println("wrong direction");
        }

        snse.setX(x + offset_x);
        snse.setY(y + offset_y);
        snse.setDirection(direction);

        x = tmpx;
        y = tmpy;
        direction = tmpdirection;
    }
}

```

which unfortunately results in this behavior:

Any tips on how to make a correctly working snake tail would be much appreciated :)

# Answer
> 19 votes
Think of the problem like this:
How does a snake move in the original game?
The snake moves towards its current direction. The behavior looks like the head appears out of nothing, and the last tail part disappears.

You can have a list of snakeparts. What you want to do is remove the last item in the list which represents the last tail part.
Then you want to create a new headpart where it should be positioned and put it in the first position of the list.
This means the remainder of the snake is not moved since you only alter first and last position.
This creates a snakelike behavior.

# Answer
> 1 votes
The way I see it is as a "Caterpillar" like system, where each part of the snake follow the part ahead of it.
In another words, each part of the snake would be an Object with *Position (x, y)*, a *reference* to the part ahead of it that it would use to move around and a function to process the position of the part ahead of it and move accordingly. The main snake (the Head) should have references for every part of the snake, and would call the function responsible to make the part follow its predecessor, being the Head the predecessor of the first part.
Hope it helps!

---
Tags: java, libgdx
---


# Question
Title: How can I generate random maps that feel like Age of Empires II random maps?
I like the way Age of Empires II generate random maps turned out (good variety, decent biome transitions, maps felt random without feeling chaotic), but am struggling to replicate the style. I've attempted using e.g., Perlin noise, but everything comes out either too homogeneous, or if not, the Perlin value -\> terrain heuristics are too sensitive and fragile to make a variety of world types.

I remember the AoE2 map type "The Unknown" advertised "100,000 possible maps", suggesting some use of seed numbers, but I'm not sure how to use seed numbers to produce the variety I saw.

What algorithms and heuristics could I use to produce random maps that feel like AoE2 random maps?

**Edit to be more specific:**

Thinking further about my problem, and studying what I like about AoE2's random map engine, I believe **my biggest problem is managing the distribution of water and plant life on the map**. I now see I've also tied that up in my mind with "biome transitions that make sense", but that's a different problem (though I expect my continued use of Perlin noise will make it tricky to solve).

I've added several AoE2 random maps that highlight what I like about their mapping engine, which my own efforts are failing to reproduce. All screenshots are taken from random map type, "Custom" -\> "The Unknown". I did not instruct the game to use specific geographies like archipelagos.

Further below are images from my own map engine. Each pixel corresponds to one AoE2 map tile.

One complication for my project is I want maps to be many, many times larger than AoE2 maps. Thus, whatever engine I use must be able to create the full range of biomes in each map, and not one narrow set of biomes per map, like AoE2 uses.

# Age of Empires II maps

Here's an example that features inland lakes and some sort of river-looking things. I like how the map includes a large amount of water scattered about, but that water is still somewhat concentrated - there are large swaths of land that are available for building your empire. You don't have to spend the entire game planning your city around the water.

Here's similar example where the game was smart enough to connect islands with traversable marshes. I can't imagine how a noise-based algorithm would create the marsh there, and only those places. Also, notice how the game created the land such that each player has their own private, large swath of land all to start out with. It didn't create random patches of land, then take a best-guess as to which one would be the least terrible for each player to start on.

I like that this map also makes heavy use of water, but *doesn't* include many inland lakes. Contrast it with the first image. I like the way AoE2 creates entirely different geographies using the same building blocks. My attempt at using Perlin noise failed here - I either get enormous sprawling oceans that dwarf the land mass, or the Land of 10,000 Lakes. I also found it hard to get both islands *and* connected continents (think North/South America).

Contrast this image with the one above it. They show that the aridity of a map doesn't depend on the water level. The first image features a map that's nearly devoid of water, yet contains forests and grass. The second image has a moderate amount of water, yet is a desert. I like that that's possible (think having both New Mexico or the Sahara and Costa Rica in your world).

# My own maps

I've read in a bunch of places that a good way to build maps is to layer multiple levels of Perlin noise, each representing a different dimension of data. Following popular recommendations, I went with elevation and moisture, selecting terrain types from the Whittaker table here.

I took two perlin maps, quantized the values from each into integers via a simple `if perlin_val < x { i=some_int } else if perlin_val < y...`, then mapped the (elevation, moisture) integer pairs to a table of terrain types (e.g., \[1,0\]-\> tropical desert, \[1,1\] -\> grassland). Oceans were included in this system - elevation=0 defined ocean.

There's good variation, and in many ways it feels like a real world, but there are a few problems:

* First, there's no pattern to the ocean depths. You'd expect shallow waters near shore and deep waters further out, there's no rhyme or reason as to which is where
* Second, all of the water is concentrated in the oceans; there are no lakes or rivers, because Perlin noise doesn't suddenly dip to a lower value in the middle of a continent.
* Creating a balance between quantities of each biome is very, very difficult. I attribute this to:

+ Perlin noise follows a normal distribution, so estimating how to adjust the probability of each dimension mapping is difficult
    + Trying to balance multiple dimensions is hard - maybe I want more (2,3) so I up the odds of getting (n,3). Well, now I have too much (3,3) and everything looks wrong.
    + When I zoomed the noise in closely enough to have smooth data, I wasn't getting a very complete sample of Perlin values. So I'd tweak my distributions for the map in front of me, reload a new random map, and get very different results.

I tried to fix the rivers/lakes issue by making water from a third set of Perlin values. A binary water/land decision, then apply all of the above stuff to the land. This makes it drastically easier to control water distribution (still not perfect, but better), but introduces the problem that there are a lot of biome transitions that don't make sense. E.g., inexplicable patches of desert in the midst of lush grassland, snow on the beach, etc. It's also still hard to control proportions of land biomes, for the reasons mentioned above.

Looking at that the above problems, I tried a simpler algorithm that only mapped the Perlin noise to one dimension. I now have an array of terrain types escalating from 0=deep ocean -\> 1=shallow ocean -\> 2=beach ... -\> N=snow. While this yields islands and continents, and makes it far easier to balance the proportion of each terrain, the terrain types are far too clustered. Every land mass looks like an elevation map, generally without terrain types scattered across its surface. Every land mass has approximately the same features, always in the same order, and always in the same ring-like shape.

# Answer
Check out Amit Patel's excellent article that I feel is kind of a quintessential resource for procedural generation of terrain...

http://www-cs-students.stanford.edu/~amitp/game-programming/polygon-map-generation/

The key thing he does is use graph structure to model his terrain, not straight up noise maps (Perlin et al). I won't embed his illustrations, but read the article, and I think you'll find it helpful to get you thinking about a different approach.

If you are making a CIV/AOE type game, placement of resources will be important. You can't have key resources be too rare, or high value ones be too common. If you presume each polygon to be a zone with a given characteristic (see article's illustrations, it will make more sense), I could see assigning resources to each polygon based on some algorithm of your choosing. You can get pretty clever by making the resources in a polygon be statistically biased by the neighbors so that a forest next to a desert might be rare, but forest next to grassland more common for example.
> 9 votes

# Answer
I create random map scripts for *Age of Empires 2*. My most recent one is for the HD version.

If you're looking to understand how to create maps for Age of Empires 2, there is this excellent guide to RMS (Random Map Scripting).

Age of Empires uses an expert system, allowing scripts to write routines for the generation rules, which you can learn a lot from. As for regions, I imagine that would simply be a case of masking off areas and applying different scripts/routines to the masked areas accordingly. You can easily see the generation rules of existing map scripts by opening them in a text editor. I write mine in Notepad
> 4 votes

---
Tags: procedural-generation, maps, terrain
---


# Question
Title: How to tell right from left: Finding the vector pointing towards the right side of a character?
We have two vectors:

1. Pointing from the floor to a 3d character's head.
2. Pointing from the character towards where it's facing.

How do I find the vector point from the character towards the right?

The vector has to be orthogonal with the other two but also face in right direction and not to the left.

This is very similar to the question: Determining if something is on the right or left side of an object? But I just want the math to computer the third vector from the first two.

# Answer
According to the link kindly provided by @Patrick Hughes the answer is this:

```
cx = ay * bz - az * by
cy = az * bx - ax * bz
cz = ax * by - ay * bx

```

If the two other vectors are normalized, the resulting vector is also normalized.

Watch out! If you pick the wrong order you may get the wrong direction.

In my case:

```
UP = A; FRONT = B;

```
> 2 votes

---
Tags: mathematics, vector
---


title: Per-pixel displacement mapping GLSL

text:
# Question
Title: Per-pixel displacement mapping GLSL
Im trying to implement a per-pixel displacement shader in GLSL. I read through several papers and "tutorials" I found and ended up with trying to implement the approach NVIDIA used in their Cascade Demo (http://www.slideshare.net/icastano/cascades-demo-secrets) starting at Slide 82.

At the moment I am completly stuck with following problem: When I am far away the displacement seems to work. But as more I move closer to my surface, the texture gets bent in x-axis and somehow it looks like there is a little bent in general in one direction.

**EDIT**: I added a video: click

I added some screen to illustrate the problem:

Well I tried lots of things already and I am starting to get a bit frustrated as my ideas run out.

I added my full VS and FS code:

VS:

```
#version 400

layout(location = 0) in vec3 IN_VS_Position;
layout(location = 1) in vec3 IN_VS_Normal;
layout(location = 2) in vec2 IN_VS_Texcoord;
layout(location = 3) in vec3 IN_VS_Tangent;
layout(location = 4) in vec3 IN_VS_BiTangent;

uniform vec3 uLightPos;
uniform vec3 uCameraDirection;
uniform mat4 uViewProjection;
uniform mat4 uModel;
uniform mat4 uView;
uniform mat3 uNormalMatrix;

out vec2 IN_FS_Texcoord;
out vec3 IN_FS_CameraDir_Tangent;
out vec3 IN_FS_LightDir_Tangent;

void main( void )
{

   IN_FS_Texcoord = IN_VS_Texcoord;

   vec4 posObject = uModel * vec4(IN_VS_Position, 1.0);
   vec3 normalObject         = (uModel *  vec4(IN_VS_Normal, 0.0)).xyz;
   vec3 tangentObject        = (uModel *  vec4(IN_VS_Tangent, 0.0)).xyz;
   //vec3 binormalObject       = (uModel * vec4(IN_VS_BiTangent, 0.0)).xyz;
   vec3 binormalObject =  normalize(cross(tangentObject, normalObject));

   // uCameraDirection is the camera position, just bad named
   vec3 fvViewDirection  = normalize( uCameraDirection - posObject.xyz);
   vec3 fvLightDirection = normalize( uLightPos.xyz - posObject.xyz );

   IN_FS_CameraDir_Tangent.x  = dot( tangentObject, fvViewDirection );
   IN_FS_CameraDir_Tangent.y  = dot( binormalObject, fvViewDirection );
   IN_FS_CameraDir_Tangent.z  = dot( normalObject, fvViewDirection );

   IN_FS_LightDir_Tangent.x  = dot( tangentObject, fvLightDirection );
   IN_FS_LightDir_Tangent.y  = dot( binormalObject, fvLightDirection );
   IN_FS_LightDir_Tangent.z  = dot( normalObject, fvLightDirection );

   gl_Position = (uViewProjection*uModel) * vec4(IN_VS_Position, 1.0);
}

```

The VS just builds the TBN matrix, from incoming normal, tangent and binormal in world space. Calculates the light and eye direction in worldspace. And finally transforms the light and eye direction into tangent space.

FS:

```
#version 400

// uniforms
uniform Light
{
    vec4 fvDiffuse;
    vec4 fvAmbient;
    vec4 fvSpecular;
};

uniform Material {
    vec4 diffuse;
    vec4 ambient;
    vec4 specular;
    vec4 emissive;
    float fSpecularPower;
    float shininessStrength;
};

uniform sampler2D colorSampler;
uniform sampler2D normalMapSampler;
uniform sampler2D heightMapSampler;

in vec2 IN_FS_Texcoord;
in vec3 IN_FS_CameraDir_Tangent;
in vec3 IN_FS_LightDir_Tangent;

out vec4 color;

vec2 TraceRay(in float height, in vec2 coords, in vec3 dir, in float mipmap){

    vec2 NewCoords = coords;
    vec2 dUV = - dir.xy * height * 0.08;
    float SearchHeight = 1.0;
    float prev_hits = 0.0;
    float hit_h = 0.0;

    for(int i=0;i<10;i++){
        SearchHeight -= 0.1;
        NewCoords += dUV;
        float CurrentHeight = textureLod(heightMapSampler,NewCoords.xy, mipmap).r;
        float first_hit = clamp((CurrentHeight - SearchHeight - prev_hits) * 499999.0,0.0,1.0);
        hit_h += first_hit * SearchHeight;
        prev_hits += first_hit;
    }
    NewCoords = coords + dUV * (1.0-hit_h) * 10.0f - dUV;

    vec2 Temp = NewCoords;
    SearchHeight = hit_h+0.1;
    float Start = SearchHeight;
    dUV *= 0.2;
    prev_hits = 0.0;
    hit_h = 0.0;
    for(int i=0;i<5;i++){
        SearchHeight -= 0.02;
        NewCoords += dUV;
        float CurrentHeight = textureLod(heightMapSampler,NewCoords.xy, mipmap).r;
        float first_hit = clamp((CurrentHeight - SearchHeight - prev_hits) * 499999.0,0.0,1.0);
        hit_h += first_hit * SearchHeight;
        prev_hits += first_hit;
    }
    NewCoords = Temp + dUV * (Start - hit_h) * 50.0f;

    return NewCoords;
}

void main( void )
{
   vec3  fvLightDirection = normalize( IN_FS_LightDir_Tangent );
   vec3  fvViewDirection  = normalize( IN_FS_CameraDir_Tangent );

   float mipmap = 0;

   vec2 NewCoord = TraceRay(0.1,IN_FS_Texcoord,fvViewDirection,mipmap);

   //vec2 ddx = dFdx(NewCoord);
   //vec2 ddy = dFdy(NewCoord);

   vec3 BumpMapNormal = textureLod(normalMapSampler, NewCoord.xy, mipmap).xyz;
   BumpMapNormal = normalize(2.0 * BumpMapNormal - vec3(1.0, 1.0, 1.0));

   vec3  fvNormal         = BumpMapNormal;
   float fNDotL           = dot( fvNormal, fvLightDirection );

   vec3  fvReflection     = normalize( ( ( 2.0 * fvNormal ) * fNDotL ) - fvLightDirection );
   float fRDotV           = max( 0.0, dot( fvReflection, fvViewDirection ) );

   vec4  fvBaseColor      = textureLod( colorSampler, NewCoord.xy,mipmap);

   vec4  fvTotalAmbient   = fvAmbient * fvBaseColor;
   vec4  fvTotalDiffuse   = fvDiffuse * fNDotL * fvBaseColor;
   vec4  fvTotalSpecular  = fvSpecular * ( pow( fRDotV, fSpecularPower ) );

   color = ( fvTotalAmbient + (fvTotalDiffuse + fvTotalSpecular) );

}

```

The FS implements the displacement technique in TraceRay method, while always using mipmap level 0. Most of the code is from NVIDIA sample and another paper I found on the web, so I guess there cannot be much wrong in here. At the end it uses the modified UV coords for getting the displaced normal from the normal map and the color from the color map.

I looking forward for some ideas. Thanks in advance!

Edit: Here is the code loading the heightmap:

```
glTexImage2D(GL_TEXTURE_2D,
                     0,
                     GL_RGBA,
                     mWidth,
                     mHeight,
                     0,
                     GL_RGBA,
                     GL_UNSIGNED_BYTE,
                     mImageData);

        glGenerateMipmap(GL_TEXTURE_2D);

        //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR);
        //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);

        //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
        //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

```

Maybe something wrong in here?

# Answer
I dont know why to be honest. But it finally works now, when I am NOT normalizing the viewdirection in the VS before transforming it into the tangent space.

Here is a final video: http://www.paxi.at/random/final.avi
> 1 votes

# Answer
Perhaps your heightmap texture is not sufficiently large when you are close to the object since the texels \> pixel by a large factor? Also do you have any filters enabled on the heightmap texture?
> 0 votes

---
Tags: glsl, displacement-mapping, per-pixel
---


# Question
Title: Cascaded shadowmapping problem with split distances
I'm doing cascaded shadow mapping and I have problem. From the cameras position, the splits are \[camPos, 6\], \[camPos+6, 12\], \[camPos+12, 18\] and \[camPos+18, 100\]. The "mSplitDistance" variable is the camera position + splitFarDistance (in camera space) for each split. So, standing at world pos 0.0f and looking down -Z, the values would be \[-6, -12, -18, -100\], and turn around and look down +Z means \[6, 12, 18, 100\]

The shadow mapping is only accurate in the last split, from 18 to 100; there the shadows behave as intended. In the first three splits, it is sometimes accurate and sometimes completely wrong.

I am using deferred renderering, so I am just drawing a quad and then go fragment per fragment and extract the world position / normals / etc from there.

I suspect there is somethign wrong in the lighting fragment shader. Here it is:

```
#version 430

 layout(std140) uniform;

 const float DEPTH_BIAS = 0.00005;

 uniform UnifDirLight
{
     mat4 mVPMatrix[4];     // the bias * crop * projection* view matrices for the directional light
     float mSplitDistance[4];
     vec4 mLightColor;
     vec4 mLightDir;
     vec4 mGamma;
     vec2 mScreenSize;
 } UnifDirLightPass;

 layout (binding = 2) uniform sampler2D unifPositionTexture;
 layout (binding = 3) uniform sampler2D unifNormalTexture;
 layout (binding = 4) uniform sampler2D unifDiffuseTexture;
 layout (binding = 6) uniform sampler2DArrayShadow unifShadowTexture;

 out vec4 fragColor;

 void main()
{
     vec2 texcoord = gl_FragCoord.xy / UnifDirLightPass.mScreenSize;

     vec3 worldPos = texture(unifPositionTexture, texcoord).xyz;  // world position; in world space
     vec3 normal   = normalize(texture(unifNormalTexture, texcoord).xyz);
     vec3 diffuse  = texture(unifDiffuseTexture, texcoord).xyz;

     int index = 3;
     if (worldPos.z > UnifDirLightPass.mSplitDistance[0])
         index = 0;
     else if (worldPos.z > UnifDirLightPass.mSplitDistance[1])
         index = 1;
     else if (worldPos.z > UnifDirLightPass.mSplitDistance[2])
         index = 2;

     vec4 projCoords = UnifDirLightPass.mVPMatrix[index] * vec4(worldPos, 1.0);
     projCoords.w    = projCoords.z - DEPTH_BIAS;
     projCoords.z    = float(index);
     float visibilty = texture(unifShadowTexture, projCoords);

     float angleNormal = clamp(dot(normal, UnifDirLightPass.mLightDir.xyz), 0, 1);

     fragColor = vec4(diffuse, 1.0) * visibilty * angleNormal * UnifDirLightPass.mLightColor;
}

```

Any ideas on what could be wrong? I suspect the might be some issue with the way I select the index, but I havn't figured it out yet.

EDIT: Screenshots to show the problem. The first three show that the shadow mapping works on and off at various distances, and the fourth shows the last split where it works as intended

http://s23.postimg.org/ngwk5gnff/image.png

http://s11.postimg.org/b9cqu45sz/image.png

http://s16.postimg.org/4daom7ded/image.png

http://s27.postimg.org/y7gs1kbmb/image.png

EDIT2: added more screenshots with debug

The colors show the farDistance (red, green, blue, white) http://s13.postimg.org/asvxzfe3b/image.png http://s23.postimg.org/gew8jmfnv/1\_color.png¨

The splits looks okay in the above, but notice how the shadows cut out still... and no shadows on the cube?

http://s21.postimg.org/gc0tn3obr/image.png http://s28.postimg.org/xlmnxe3al/2\_color.png

EDIT3:

Heres how I create the lights VP matrix used for generating shadowmap (which is then multiplied by a bias matrix before passed on to shader)

```
Mat4 CreateDirLightVPMatrix(const CameraFrustrum& cameraFrustrum, const Vec3& lightDir)
    {
        const Vec3 lightDirx = glm::normalize(lightDir);
        const Vec3 perpVec1  = glm::normalize(glm::cross(lightDirx, Vec3(0.0f, 0.0f, 1.0f)));
        const Vec3 perpVec2  = glm::normalize(glm::cross(lightDirx, perpVec1));
        Mat4 lightViewMatrix(Vec4(perpVec1, 0.0f), Vec4(perpVec2, 0.0f), Vec4(lightDirx, 0.0f), Vec4(0.0f, 0.0f, 0.0f, 1.0f));

        Vec4 transf = lightViewMatrix * cameraFrustrum[0]; // cameraFrustrum is a std::array<Vec4, 8> and 0-3 is near-points and 4-7 are far points of the frustrum
        float maxZ = cameraFrustrum[0].z, minZ = cameraFrustrum[0].z;
        for (uint32_t i = 1; i < 8; i++)
        {
            transf = lightViewMatrix * cameraFrustrum[i];
            if (cameraFrustrum[i].z > maxZ)
                maxZ = cameraFrustrum[i].z;
            if (cameraFrustrum[i].z < minZ)
                minZ = cameraFrustrum[i].z;
        }

        const Mat4 mvp = glm::ortho(-1.0f, 1.0f, -1.0f, 1.0f, maxZ, minZ) * lightViewMatrix;

        float maxX = -1000.0f, minX = 1000.0f;
        float maxY = -1000.0f, minY = 1000.0f;
        for (uint32_t i = 0; i < 8; i++)
        {
            transf = mvp * cameraFrustrum[i];

            if (cameraFrustrum[i].x > maxX)
                maxX = cameraFrustrum[i].x;
            if (cameraFrustrum[i].x < minX)
                minX = cameraFrustrum[i].x;
            if (cameraFrustrum[i].y > maxY)
                maxY = cameraFrustrum[i].y;
            if (cameraFrustrum[i].y < minY)
                minY = cameraFrustrum[i].y;
        }

        float scaleX = 2.0f / (maxX - minX);
        float scaleY = 2.0f / (maxY - minY);
        float offsetX = -0.5f * (maxX + minX) * scaleX;
        float offsetY = -0.5f * (maxY + minY) * scaleY;

        Mat4 cropMatrix(1.0f);
        cropMatrix[0][0] = scaleX;
        cropMatrix[1][1] = scaleY;
        cropMatrix[3][0] = offsetX;
        cropMatrix[3][1] = offsetY;

        return cropMatrix * glm::ortho(-1.0f, 1.0f, -1.0f, 1.0f, maxZ, minZ) * lightViewMatrix;
    }

```

Any hints are much appreciated

# Answer
I had similar problem to yours. And I think that you can have something wrong in two places:

1. Bad light view projection matrix. You should make some preview of each cascade and check if shadow map looks ok. In my case after transform bounding box of frustum split by light view matrix, transformed box position in z axis was wrong and in far distances shadow map was blank. To solve that I substract near plane of main camera (from which you look at) value from min.z (min.z-=camera.near()) and far plane from max.z (max.z-=camera.far()). This gave me proper range for each cascade.
2. Bad split distance. Even if it looks ok it could be wrong. In your screenshots you can see only scene with bad shadows or scene with colored splits. To get more conclusions it is better to multiply (or add) final fragment by color of split. It can show you more what is a real problem. I'm not sure if your solution is good but I used method presented here. So I multiply each frustum split far plane by main camera projection matrix and compare it with depth buffer content.

Hope it is clear (it is hard to me to explain that, not good in theory) and will help :)
> 2 votes

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


# Question
Title: Why am I not getting an sRGB default framebuffer?
I'm trying to make my OpenGL Haskell program gamma correct by making appropriate use of sRGB framebuffers and textures, but I'm running into issues making the default framebuffer sRGB.

Consider the following Haskell program, compiled for 32-bit Windows using GHC and linked against 32-bit freeglut:

```
import Foreign.Marshal.Alloc(alloca)
import Foreign.Ptr(Ptr)
import Foreign.Storable(Storable, peek)
import Graphics.Rendering.OpenGL.Raw
import qualified Graphics.UI.GLUT as GLUT
import Graphics.UI.GLUT(($=))

main :: IO ()
main = do
    (_progName, _args) <- GLUT.getArgsAndInitialize
    GLUT.initialDisplayMode $= [GLUT.SRGBMode]
    _window <- GLUT.createWindow "sRGB Test"

    -- To prove that I actually have freeglut working correctly.
    -- This will fail at runtime under classic GLUT.
    GLUT.closeCallback $= Just (return ())

    glEnable gl_FRAMEBUFFER_SRGB
    colorEncoding <- allocaOut $ glGetFramebufferAttachmentParameteriv
        gl_FRAMEBUFFER gl_FRONT_LEFT gl_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING
    print colorEncoding

allocaOut :: Storable a => (Ptr a -> IO b) -> IO a
allocaOut f = alloca $ \ptr -> do
    f ptr
    peek ptr

```

On my desktop (Windows 8 64-bit with a GeForce GTX 760 graphics card) this program outputs `9729`, a.k.a. `gl_LINEAR`, indicating that the default framebuffer is using linear color space, even though I explicitly requested an sRGB window. This is reflected in the rendering results of the actual program I'm trying to write - everything looks washed out because my linear color values aren't being converted to sRGB before being written to the framebuffer.

On the other hand, on my laptop (Windows 7 64-bit with an Intel graphics chip), the program prints `0` (huh?) and I get an sRGB default framebuffer *by default whether I request one or not!* And on both machines, if I manually create a non-default framebuffer bound to an sRGB texture, the program correctly prints `35904`, a.k.a. `gl_SRGB`.

Why am I getting different results on different hardware? Am I doing something wrong? How can I get an sRGB framebuffer consistently on all hardware and target OSes?

# Answer
> 2 votes
OK, I've figured out enough details on this issue that I can "answer" it, although I'm not entirely happy with the results...

* The actual issue was inverted from what I thought was the case: my Nvidia-powered desktop was doing the sRGB conversions correctly, while my Intel-powered laptop was incorrectly outputting the linear color space values without converting them. I don't know why the default framebuffer on my desktop reports a `gl_LINEAR` color space even when an sRGB framebuffer is requested, but as long as I have `gl_FRAMEBUFFER_SRGB` turned on everything seems to display correctly.
* I ended up switching to GLFW for windowing, and it couldn't give me a working sRGB framebuffer on my laptop either. I think the issue may be related to this question, for which the answer was essentially "Intel drivers suck, don't trust anything they do".

---
Tags: opengl, color, glut, nvidia, srgb
---


# Question
Title: XNA 4.0 - Strange Behavior when using RenderTarget2D
My Problem is similar to XNA 4.0 - Why does using a RenderTarget2d cause transparency on models?.

I want to render my scene to a Texture2D and then draw the texture. If I set no RenderTarget at all (render directly to the back buffer), everything looks fine.

I draw my models/textures with:

```
graphics.GraphicsDevice.Clear(Color.Black);
spriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.Opaque, SamplerState.AnisotropicClamp, DepthStencilState.Default, RasterizerState.CullCounterClockwise);

[...Drawing methods for models etc. are called here...]

spriteBatch.End();

```

If I change that code to:

```
RenderTarget2D target = new RenderTarget2D(this.GraphicsDevice,this.GraphicsDevice.PresentationParameters.BackBufferWidth,this.GraphicsDevice.PresentationParameters.BackBufferHeight);
this.GraphicsDevice.SetRenderTarget(target);

graphics.GraphicsDevice.Clear(Color.Black);

spriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.Opaque, SamplerState.AnisotropicClamp, DepthStencilState.Default, RasterizerState.CullCounterClockwise);

[...Drawing methods for models etc. are called here...]

spriteBatch.End();
this.GraphicsDevice.SetRenderTarget(null);

```

And render the texture / save it as an image-file, some objects get transparent and the drawing order changes sort of randomly.

# Answer
> 1 votes
The docs do not state what kind of depth buffer and color buffer will be used using that overload. I suspect not explicitly specifiying a depth buffer is the issue here.

Try the most complete constructor overload like this, and probably your problems will disappear:

```
new RenderTarget2D (
         this.GraphicsDevice graphicsDevice,
         this.GraphicsDevice.PresentationParameters.BackBufferWidth,
         this.GraphicsDevice.PresentationParameters.BackBufferHeight,
         true,
         SurfaceFormat.Color,
         DepthFormat.Depth16,
         4,
         RenderTargetUsage.DiscardContents
);

```

---
Tags: xna-4.0, rendering, spritebatch, rendertargets
---


# Question
Title: Revert to closest non intersecting position
First, let me start by saying:

> *Please forgive me if this question have already been asked. I've tried to search but didn't find any solution. (It might be due to my lack of terms).*

I have two circles with `r` radius, `p(x,y)` position and `v(x,y)` velocity. I need a formula for calculating position **p3** if the first circle (blue) intersects with the second circle (red), thus placing it as close as possible next to the red circle without intersecting.

Any ideas?

```
Vector2 c1 = new Vector2((p1.X + r1), (p1.Y + r1));
Vector2 c2 = new Vector2((p2.X + r2), (p2.Y + r2));
bool intersects = ((Vector2.Distance(c1, c2)) < (r1 + r2));

```

# Answer
The math is a bit easier if we center our coordinate system on the final position of the red circle, which I'll call p2 here. We can treat the red circle as stationary, given OP's comment above.

So we're looking for a time t when the blue circle's position is exactly r1 + r2 away from the red circle at p2. We can find the position once we know this time.

Let's define:

```
p = p1 - p2
v = v1
r = r1 + r2

```

So we're trying to solve:

```
||p + t*v|| = ||r||

```

Or equivalently:

```
(p + t*v)^2 = r^2
p^2 + 2(t)(p · v) + (t^2)(v^2) = r^2
t^2(v^2) + t(2p · v) + p^2 - r^2 = 0

```

Now we can write some code to solve this using the quadratic formula.

```
float t = deltaTime;

float a = Vector2.dot(v, v);
float b = 2f * Vector2.dot(p, v);
float c = Vector2.dot(p, p) - r*r;

float discriminant = b*b - 4f*a*c;

if(discriminant >= 0f) // Otherwise there is no solution: the circles never touch.
{
   float denominator = 1f/(2f * a);
   float center = -b * denominator;
   float offset = Sqrt(discriminant) * denominator;

   // In general there are two solutions, so here I'll arbitrarily select the point closest to the blue circle's start position
   // even if that means it's pushed backward, or pushed beyond where its velocity could take it this frame.
   if(center >= 0)
   {
       t = Min(t, center - offset);
   }
   else
   {
       t = Max(t, center + offset);
   }
}

p3 = p1 + t * v1;

```

The discriminant check, mins & maxes above should give the correct behaviour even if you use this code for circles that never intersect. But if you're pre-filtering for intersecting pairs, you can simplify them a little.

Note that this will not work if p1's velocity is zero. In that case, you may want to set:

```
p3 = p2 + Vector2.normalize(p1 - p2) * (r1 + r2);

```

...which can also fail if p1=p2, so you'll want some default separation vector if this kind of pathological case can happen.
> 3 votes

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


title: Level progression grid/chart

text:
# Question
Title: Level progression grid/chart
What I'd like to do is create a sheet where I can track character XP/level progression.

I created this by hand:

It's sloppy, but in the realm of what I'd like to generate on a computer. Each bar represents XP needed to level up, with each square on the grid representing a set number of XP.

Any ideas how I could go about doing this in a more standardized/repeatable/printable?

# Answer
Looking at what you wrote, it seems the progression of each number of squares in a block is `(2k - 1) where k > 0` You can extend this to include the amount of XP per block as: `(2k - 1) * c where k > 0, c > 0` The constant value can be tweaked as needed for gameplay purposes.

If you are talking about trying to represent the drawn bars *graphically* then it is simply: `((2k - 1) * c) % PIXEL_WIDTH where k is the level number, c is the number of pixels per square, PIXEL_WIDTH is the max pixels per horizontal bar.`
> 1 votes

---
Tags: mathematics, gui, character, progression
---


# Question
Title: How can I read the color of a specific pixel in XNA?
I want a way to find out if, for example, the pixel at `Vector2(2, 5)` on the game window is color `Color.Red`, or some other color or set of coordinates. How can I do this?

# Answer
Render your scene to a texture render target (`RenderTarget2D`) by creating one, setting it active via `SetRenderTarget` and then drawing your scene. Since a `RenderTarget2D` is also a `Texture2D`, you can use the `GetData` method to copy the texture data to an array of the appropriate type, which you can index to acquire the appropriate color data using linearized 2D indexing (that is, compute the index as `index = (y * width) + x`, where `width` is the width of the texture).

Note that the "appropriate type" of the array will depend on the format of the render target you have created.

Generally, this is an inefficient collection of operations relative to other possible ways to achieve the overall end-result you are looking to achieve. However, since your question doesn't provide further details about *why* you want to read the color data at a specific pixel, it's difficult to provide further guidance. Consider asking another question with more details about your end goal.
> 1 votes

# Answer
I would imagine render all your going to draw to a texture, and then ask the texture for it's color data. I've never tried it myself, but that's where I'd start. I would rather have left this as a comment.
> 2 votes

---
Tags: xna, c#, coordinates, color
---


title: DirectX particle system. ConstantBuffer

text:
# Question
Title: DirectX particle system. ConstantBuffer
I'm new in DirectX and I'm making a 2D game. I want to use a particle system to simulate a 3D starfield, so each star has to set its own constant buffer for the vertexshader es. to set it's world matrix. So if i have 500 stars (that move every frame) i need to call 500 times VSsetconstantbuffer, and map/unmap each buffer. with 500 stars i have an average of 220 fps and that's quite good. My bottelneck is Vs/PsSetconstantbuffer. If i dont call this function i have 400 fps(obliviously nothing is display, since i dont set the position of the stars). So is there a method to speed up the render of the particle system??

Ps. I'm using intel integrate graphic (hd 2000-3000). with a nvidia (or amd) gpu will i have the same bottleneck?? If, for example, i dont call setshaderresource i have 10-20 fps more (for 500 objcets), that is not 180.Why does SetConstantBuffer take so long??

```
LPVOID VSdataPtr = VSmappedResource.pData;
memcpy(VSdataPtr, VSdata, CszVSdata);
context->Unmap(VertexBuffer, 0);

result = context->Map(PixelBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &PSmappedResource);
if (FAILED(result))
{
    outputResult.OutputErrorMessage(TITLE, L"Cannot map the PixelBuffer", &result, OUTPUT_ERROR_FILE);
    return;
}
LPVOID PSdataPtr = PSmappedResource.pData;
memcpy(PSdataPtr, PSdata, CszPSdata);
context->Unmap(PixelBuffer, 0);

context->VSSetConstantBuffers(0, 1, &VertexBuffer);
context->PSSetConstantBuffers(0, 1, &PixelBuffer);

```

this update and set the buffer. It's part of the render method of a sprite class that contains a the vertex buffer and the texture to apply to the quads(it's a 2d game) too. I have an array of 500 stars (sprite setup with a star texture). Every frame: clear back buffer; draw the array of stars; present the backbuffer;

draw also call the function update( which calculate the position of the sprite on screen based on a "camera class")

Ok, create a vertex buffer with the vertices of each quads(stars) seems to be good, since the stars don't change their "virtual" position; so.... In a particle system (where particles move) it's better to have all the object in only one vertices array, rather then an array of different sprite/object in order to update all the vertices' position with a single setbuffer call. In this case i have to use a dynamic vertex buffer with the vertices positions like this:

```
verticesForQuad={{ XMFLOAT3((float)halfDImensions.x-1+pos.x, (float)halfDImensions.y-1+pos.y, 1.0f), XMFLOAT2(1.0f, 0.0f) },
    { XMFLOAT3((float)halfDImensions.x-1+pos.x, -(float)halfDImensions.y-1+pos.y, 1.0f), XMFLOAT2(1.0f, 1.0f) },
    { XMFLOAT3(-(float)halfDImensions.x-1+pos.x, (float)halfDImensions.y-1.pos.y, 1.0f), XMFLOAT2(0.0f, 0.0f) },
    { XMFLOAT3(-(float)halfDImensions.x-1.pos.x, -(float)halfDImensions.y-1+pos.y, 1.0f), XMFLOAT2(0.0f, 1.0f) },

```

....other quads}

where halfDimensions is the halfsize in pixel of a texture and pos the virtual position of a star. than create an array of verticesForQuad and create the vertex buffer

```
ZeroMemory(&vertexDesc, sizeof(vertexDesc));
vertexDesc.Usage =      D3D11_USAGE_DEFAULT;
vertexDesc.BindFlags =  D3D11_BIND_VERTEX_BUFFER;
vertexDesc.ByteWidth =  sizeof(VertexType)* 4*numStars;

ZeroMemory(&resourceData, sizeof(resourceData));
resourceData.pSysMem =  verticesForQuad;

result = device->CreateBuffer(&vertexDesc, &resourceData, &CvertexBuffer);

```

and call each frame `Context->IASetVertexBuffers(0, 1, &CvertexBuffer, &stride, &offset);`

But if i want to add and remove obj i have to recreate the buffer each time, havent i?? There is a faster way? I think i can create a vertex buffer with a max size (es. 10000 objs) and when i update it set only the 250 position (for 250 onjs for example) and pass this number as the vertexCount to the draw function (numObjs\*4), or i'm worng

# Answer
This is a question of how the performance goes on different cards. I would assume that setting and remapping the constant buffer is a big performance hit for you since it usually always is. But you can never be 100% sure with out proper profiling.

Why It takes so long is because it´s sending data from the cpu to the gpu. this generally takes a few cycles to do. To optimize this is to create a smart way of using your constant buffers. Usually sort your drawcalls so that you have to do as little update between the calls as possible. that is, for every particle that will have the same color, sort then and only update that value when you can.

unfortunately with out more information about how your renderer works it´s super hard to say how to either organize or structure your shader programs. If you would supply more code it would be much easier.
> 1 votes

---
Tags: c++, directx, particles
---


title: XNA: Non-overlapping shadows

text:
# Question
Title: XNA: Non-overlapping shadows
I want to create an effect similar to the following in XNA / MonoGame:

There's a background and a semi-transparent shadow consisting of several objects (two circles in this example). However, the shadows merge **without darkening their overlapping region**!

My current approach was the following:

* Render all required shadow objects using a `DepthStencilState` and a `AlphaTestEffect`.
* Then, render a single-pixel semitransparent black texture over the entire screen using another `DepthStencilState` to display shadows.

However, it didn't work as expected: the shadow objects get rendered to the target, and the stencil buffer seems unaffected.

Here's what I want:

* A way to render a sprite to Stencil Buffer **only**, with absolutely no visible modifications to the target.
* A way to render a **semitransparent** texture using the stencil buffer.

Stencil states and effects are initialized as follows:

```
StencilCreator = new DepthStencilState
{
    StencilEnable = true,
    StencilFunction = CompareFunction.Always,
    StencilPass = StencilOperation.Replace,
    ReferenceStencil = 1
};

StencilRenderer = new DepthStencilState
{
    StencilEnable = true,
    StencilFunction = CompareFunction.Equal,
    ReferenceStencil = 1,
    StencilPass = StencilOperation.Keep
};

var projection = Matrix.CreateOrthographicOffCenter(0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, 0, 0, 1);
var halfPixel = Matrix.CreateTranslation(-0.5f, -0.5f, 0);

AlphaEffect = new AlphaTestEffect(GraphicsDevice)
{
    DiffuseColor = Color.White.ToVector3(),
    AlphaFunction = CompareFunction.Greater,
    ReferenceAlpha = 0,
    World = Matrix.Identity,
    View = Matrix.Identity,
    Projection = halfPixel * projection
};

MaskingTexture = new Texture2D(GameEngine.GraphicsDevice, 1, 1);
MaskingTexture.SetData(new[] { new Color(0f, 0f, 0f, 0.3f) });

```

What am I doing wrong?

# Answer
I actually found a much easier easier way that does not require any shaders. The trick is simple:

1. Create a `RenderTarget2D` and clear it with `Colors.Transparent`.
2. Render all the shadows into the render target using solid black color. This way shadows will not darken each other, as each of them is pitch black already.
3. Draw the render target into the main scene using `BlendingMode.AlphaBlend`.

The transparency of draw color will determine the overall shadow darkness.
> 0 votes

# Answer
I think this could be solved using render targets. I propose the following technique

Create two render targets, one for the colors in the scene and one for the lighting in your scene

```
colorMap = new RenderTarget2D(GraphicsDevice, windowWidth, windowHeight, false, SurfaceFormat.Color, DepthFormat.Depth16, 16, RenderTargetUsage.DiscardContents);
lightMap = new RenderTarget2D(GraphicsDevice, windowWidth, windowHeight, false, SurfaceFormat.Color, DepthFormat.None, 16, RenderTargetUsage.DiscardContents);

```

Set your colorMap and draw your game, without lighting

```
GraphicsDevice.SetRenderTarget(colorMap);
GraphicsDevice.Clear(Color.CornflowerBlue);
DrawMyAwesomeGame();

```

Set your lightMap and draw your lighting (or inversely your shadows)
Note that you have to clear your lightmap to white if you want to paint the shadows or to black if you want to paint he lit place

```
GraphicsDevice.SetRenderTarget(lightMap);
GraphicsDevice.Clear(Color.White);
DrawShadows();

```

Now let's return rendering to the screen

```
GraphicsDevice.SetRenderTarget(null);

```

Now we're going to need a shader to combine these two. Let assume we already have one (we'll see the source later)

```
combineEffect.Parameters["colorMap"].SetValue(colorMap);
combineEffect.Parameters["lightMap"].SetValue(lightMap);

combineEffect.Techniques[0].Passes[0].Apply();

```

Of course the shader needs something to work with, so lets draw a full screen quad (code at the end of this post)

```
quad.Render(GraphicsDevice, Vector2.One * -1.0f, Vector2.One);

```

Ok so let's get back to the shader, how does it combine the two

```
float3 diffuseColor = tex2D(colorSampler, input.TexCoord).rgb;
float4 light = tex2D(lightSampler, input.TexCoord);
float ambient = 0.1f; // ambient lighting, everything is atleast lit so much

diffuseLight.r = max(diffuseLight.r, ambient);
diffuseLight.g = max(diffuseLight.g, ambient);
diffuseLight.b = max(diffuseLight.b, ambient);

return float4((diffuseColor * diffuseLight), 1);

```

This should do the trick!

**Other code used in this post**

The full shader:

```
texture colorMap;
texture lightMap;

sampler colorSampler = sampler_state
{
  Texture = (colorMap);
  AddressU = CLAMP;
  AddressV = CLAMP;
  MagFilter = LINEAR;
  MinFilter = LINEAR;
  Mipfilter = LINEAR;
};
sampler lightSampler = sampler_state
{
  Texture = (lightMap);
  AddressU = CLAMP;
  AddressV = CLAMP;
  MagFilter = LINEAR;
  MinFilter = LINEAR;
  Mipfilter = LINEAR;
};

struct VertexShaderInput
{
  float3 Position : POSITION0;
  float2 TexCoord : TEXCOORD0;
};

struct VertexShaderOutput
{
  float4 Position : POSITION0;
  float2 TexCoord : TEXCOORD0;
};

VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
    VertexShaderOutput output;
    output.Position = float4(input.Position, 1);
    output.TexCoord = input.TexCoord;
    return output;
}

float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
    float3 diffuseColor = tex2D(colorSampler, input.TexCoord).rgb;
    float4 light = tex2D(lightSampler, input.TexCoord);
    float ambient = 0.1f; // ambient lighting, everything is atleast lit so much

    diffuseLight.r = max(diffuseLight.r, ambient);
    diffuseLight.g = max(diffuseLight.g, ambient);
    diffuseLight.b = max(diffuseLight.b, ambient);

    return float4((diffuseColor * diffuseLight), 1);
}

technique Technique1
{
  pass Pass1
  {
    VertexShader = compile vs_2_0 VertexShaderFunction();
    PixelShader = compile ps_2_0 PixelShaderFunction();
  }
}

```

The quad primitive:

```
internal class Quad
{
    private VertexPositionTexture[] vertices;
    private short[] indexBuffer;

    internal Quad()
    {
        vertices = new VertexPositionTexture[]
                    {
                        new VertexPositionTexture(
                            new Vector3(0, 0, 0),
                            new Vector2(1, 1)),
                        new VertexPositionTexture(
                            new Vector3(0, 0, 0),
                            new Vector2(0, 1)),
                        new VertexPositionTexture(
                            new Vector3(0, 0, 0),
                            new Vector2(0, 0)),
                        new VertexPositionTexture(
                            new Vector3(0, 0, 0),
                            new Vector2(1, 0))
                    };

        indexBuffer = new short[] { 0, 1, 2, 2, 3, 0 };
    }

    /// <summary>
    /// Renders the four vertices for a quad directly without touching render states,
    /// setting shaders, etc...
    /// </summary>
    internal void Render(GraphicsDevice device, Vector2 bottomLeft, Vector2 topRight)
    {
        vertices[0].Position.X = topRight.X;
        vertices[0].Position.Y = bottomLeft.Y;

        vertices[1].Position.X = bottomLeft.X;
        vertices[1].Position.Y = bottomLeft.Y;

        vertices[2].Position.X = bottomLeft.X;
        vertices[2].Position.Y = topRight.Y;

        vertices[3].Position.X = topRight.X;
        vertices[3].Position.Y = topRight.Y;

        device.DrawUserIndexedPrimitives<VertexPositionTexture>
        (
            PrimitiveType.TriangleList,
            vertices,
            0,
            4,
            indexBuffer,
            0,
            2
        );
    }

```
> 2 votes

---
Tags: xna, c#, 2d, xna-4.0, monogame
---


# Question
Title: What are the advantages of having component logic in a "system" versus the component itself?
For the past few days I've been trying to make my first game. I did some research on usual development practices and patterns and I settled on a composition system where the different components communicate using messages that the container-GameObject distributes.

For instance say that I press the attack key. The playerInput component sends an AttackMessage to all the other components using the notify function of the GameObject. The Weapon component picks the message, sets some local variables and sends a RigidBodyStateMessage to the RigidBody component which in turn sends another message containing the rotation and position of the GameObject. The Weapon component catches the message and instantiates a bullet using the information passed in the message.

Communication between different objects is achieved using messages sent in message buses on which the GameObjects have registered. For example, the PhysicsComponent continuously sends messages to the collisionBus which are then delivered to the registered GameObjects.

This approach allows for complete decoupling between the components but I am not sure if it may create any long-term problems. Some people also told me that components shouldn't have any logic in them and that they should only keep data which will be processed in systems. I was wondering what advantages the latter method would bring compared to the one that I am currently using. Sorry for the wall of text, I am writing from my phone.

Any help is much appreciated!

# Answer
First, it is perfectly acceptable for a component-based system to support components with logic, or to support components without logic. There is no codified standard for component-based implementations used in game development.

There are advantages and disadvantages to either approach, but in the end none of the advantages really outweigh the others. The right choice for your game will be to choose the pattern that best expresses how *you* want to, or need to, reason about your components and their place in your larger architectural space.

Components as "pure data" allow you to make certain assumptions about them: for example, you know there is no execution state (such as "where they are in their update method") that you would need to persist if you wanted to serialize the component out to persistent storage. This can result in a simpler, cleaner system of serialization for components (both for save data and for sending across a network). If you really implement them as pure, plain-old-data objects they can be faster to copy around in bulk (depending on your language and its idioms regarding "objects" versus plain data).

However, components as "pure data" also mean you need a third-party (a "system" in your parlance) interface to drive any behavior or processing you want associated with the components. This can be disadvantageous if the overhead of creating a new "system" in your API is large. If the overhead is small, then this problem is essentially reduced to the issue of syntactic sugar for OO operations (`this->Method()` as a member function is not much different then `Method(object)`; both can be used to implement OO design).

Now, there are fairly compelling advantages to processing components *in* external "systems" objects versus within the entity itself ("foreach entity, foreach component in entity, update the component"). Externalizing the processing provides for potentially better cache locality, makes concurrent processing easier, and other sorts of things. That is orthogonal to the concept of requiring that components only be data though; you can have components with behavior that are also bulk-processed by a "system" interface.
> 6 votes

# Answer
Generally I think it boils down to code maintainability. In your current design, would adding a new component require you to update all the others respectively? Or would it suffice you add some code in one specific spot. If it's the former than you *may* be doing something wrong.

The reason I often use systems is that I don't wish to expose all the data (instances) to all the components. I also don't want to "spread my code to thin". If there is code that is strongly related I'd rather have it in one place where I can update all of it in one full swing. Using a system (at least) appears simpler because all the interaction between objects is handled by a specific external unified body of code. This way I don't need to expose aggregations of instances to every specific component. On the other hand it is important to avoid the "God Object" Anti-Pattern. Each aspect of interaction should be dealt by a unique system relevant to that specifically.

This (I think) helps me when I find data has been corrupted. I know more specifically where to look and how to track the fault's source.

There is nothing wrong with combining this approach with the alternative one when this becomes relevant because a certain behavior / interaction is perhaps unique to a specific component. It can be avoided though by having the components interact with the system.
> 0 votes

---
Tags: entity-system, component-based, messaging, software-engineering
---


title: Explanation of matrix transformations

text:
# Question
Title: Explanation of matrix transformations
I've been looking for something that can help me understand matrix transformations. I've been to multiple different sites, including Wikipedia and quite a lot of related questions on SE and other forums. I also posted a similar question in another forum and was unable to get results. Oh, and I visited a number of learning sites like Khan Academy to no avail.

The linked websites all provide methods to calculate transformed pixel-perfect collisions, but they require matrices for input. Some of the sites tell you to ignore how matrices work and focus on the collision methods, but how can you do that if you need to use matrices for input?

In trying to figure out how to convert my data into matrices and use XNA's mysterious matrix transformation tools, I ran into one of math's famous jargon-barriers with such head-scratchers as *vector space* and *linearity*, among plenty others.

So the question is, **can you explain how to create position, rotation, and scaling matrices, as well as how to combine them and *why* they work?**

As I've explained, I wouldn't be asking this question if I hadn't exhausted all of my searching queries. I am no more advanced in my mathematical understanding than Pre-Calculus.

# Answer
> 1 votes
I also struggled a bit on matrices. As I can remember, the videos from BSVino helped me a lot. https://www.youtube.com/user/BSVino/videos This guy provides several videos about maths for game developers and there are a few on matrices as well (rotation, scale, perspective transform etc..)

---
Tags: c#, xna-4.0
---


title: Are display lists faster than VBOs?

text:
# Question
Title: Are display lists faster than VBOs?
I'm making a voxel rendering engine. My "chunks" are 32 * 32 * 256 blocks and I can render a 16 * 16 square of them (which corresponds to Minecraft's maximal render distance). I'm using VBOs holding XYZ `float` positions and UV float coordinates. I use one VBO per chunk.

VBOs are alloacted with:

```
GL44.glBufferStorage(GL15.GL_ARRAY_BUFFER,
            BufferUtils.createFloatBuffer(32 * 32 * 256 * 6 * 6 * 5),
            GL30.GL_MAP_WRITE_BIT | GL44.GL_MAP_PERSISTENT_BIT);

```

I map them once at creation:

```
GL30.glMapBufferRange(GL15.GL_ARRAY_BUFFER,
            0,
            32 * 32 * 256 * 6 * 6 * 5 * 4,
            GL30.GL_MAP_WRITE_BIT | GL30.GL_MAP_UNSYNCHRONIZED_BIT | GL44.GL_MAP_PERSISTENT_BIT, null);

```

Then I can write directly into the buffer and make changes visible to the GPU with:

```
GL42.glMemoryBarrier(GL44.GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT);

```

This works, except I get about 20 FPS, while Minecraft gets 300 without frustum culling. The CPU is clearly not the bottleneck, as I have 1M FPS when the window is minimized.

Am I doing something wrong or are VBOs slower than Minecraft's Display Lists? How can I speed this up?

System specs: i7 4770 & GTX 770 OC

# Answer
I finally implemented a display list version and now I get nearly 3000 constant FPS, which is excellent I think. I didn't change the number of vertices nor the number of chunks (I already did a face selection when tesselating the chunks).

Like @bcrist said, the persistant mapping may have killed the performance.

Display lists are also far more easier to use than VBO's, as I don't even need to manually allocate memory, and they don't require the latest unsupported OpenGL versions.
> 0 votes

# Answer
If you don't do any optimization you are rendering up to ~half a billion vertices, you can:

Remove faces/vertices where blocks touch, and don't issue draw calls for chunks that lay outside of the FOV.

Beyond that you can do more advanced vismap approaches, and merge faces when possible.

If you still think there is something wrong, i suggest you edit your post with some more code, rather then just the buffer initializations.
> 4 votes

---
Tags: opengl, java, lwjgl, vbo
---


# Question
Title: GPU skinning algorithm incorrectly distorts mesh
I've been trying to implement a GPU-based matrix palette skinning algorithm with WebGL, but the rendering appears incorrect even though I can't find evident conceptual problems in the underlying algorithm. Left image is the rigged model in Blender, right image is the same mesh rendered with my algorithm.

I wrote a custom JSON exporter which exports the exact same data as the THREE.js exporter - position and rotation quaternions for bindposes and keyframes, weights and indices (checked manually). With THREE.js the animation renders correctly, so the issue must lie somewhere in my matrix manipulation process.

My process is the following:

1. Calculate the world matrices for each bone in the bindpose. This is obtained by first calculating `localMatrix` with `mat4.fromRotationTranslation(localMatrix, bone.rot, bone.pos)`, then by copying `localMatrix` in the `worldMatrix` if the current bone is the root, or by multiplying `localMatrix` with the parent's `worldMatrix` if it is not; finally, the inverse bindpose matrix is stored. (\* note that, per exporter invariant, each parent precedes all of its children in the array, so each parent's worldMatrix will have been calculated by the time it is requested; see this article).

```
  for(var i = 0; i < this.geometry.bones.length; i++) {
    var bone = this.geometry.bones[i], localMatrix = mat4.create();

    mat4.fromRotationTranslation(localMatrix, bone.rot, bone.pos);

    bone.worldMatrix = mat4.create();
    bone.inverseBindpose = mat4.create();

    if(bone.parent == -1) {
      mat4.copy(bone.worldMatrix, localMatrix);
    } else {
      // *
      mat4.multiply(bone.worldMatrix, this.geometry.bones[bone.parent].worldMatrix, localMatrix);
    }
    mat4.invert(bone.inverseBindpose, bone.worldMatrix);
  }

```
2. For each keyframe, recalculate the bone hierarchy with the same algorithm but with the degrees of freedom specified by the keyframe, then for each keyframe-bone calculate a matrix offsetting from the bindpose by multiplying its world matrix with the `inverseBindpose` calculated in the first step.

```
  var kf = this.geometry.keyframes;
  for(var i = 0; i < kf.length; i++) {

    var flat = [];

    for(var j = 0; j < kf[i].length; j++) {
      var bone = kf[i][j],
          parent = this.geometry.bones[j].parent,
          localMatrix = mat4.create();

      mat4.fromRotationTranslation(localMatrix, bone.rot, bone.pos);

      bone.worldMatrix = mat4.create();

      if(parent == -1) {
        mat4.copy(bone.worldMatrix, localMatrix);
      } else {
        mat4.multiply(bone.worldMatrix, kf[i][parent].worldMatrix, localMatrix);
      }

      var offsetMatrix = mat4.create();
      mat4.multiply(offsetMatrix, bone.worldMatrix, this.geometry.bones[j].inverseBindpose);
      bone.offsetMatrix = offsetMatrix;

      flat.push.apply(flat, offsetMatrix);
    }
    this.keyframes[i] = new Float32Array(flat);

  }

```
3. Plug everything in the buffers and invoke the vertex shader. I tried deforming a mesh in the same way on the CPU and the results are exactly the same, so I think this rules it out and the problem lies in the matrices, but here's the shader for the sake of completeness.

```
  uniform mat4 uP, uV, uM;
  uniform mat4 uBonesFrame[8];
  uniform mat3 uN;
  uniform bool uSkin;

  attribute vec3 aVertex, aNormal;
  attribute vec2 aTexCoord;

  attribute highp vec2 aSWeights;
  attribute highp vec2 aSIndices;

  varying vec3 vVertex, vNormal;

  mat4 boneTransform() {

    mat4 ret;
    float normfac = 1.0 / (aSWeights.x + aSWeights.y);

    ret = normfac * aSWeights.y * uBonesFrame[int(aSIndices.y)] +
          normfac * aSWeights.x * uBonesFrame[int(aSIndices.x)];

    return ret;
  }

  void main() {

    mat4 bt = uSkin ?
      boneTransform()
      :
      mat4(
          1., 0., 0., 0.,
          0., 1., 0., 0.,
          0., 0., 1., 0.,
          0., 0., 0., 1.
      );

    gl_Position = uP * uV * uM * bt * vec4(aVertex, 1.0);
    vVertex = (bt * vec4(aVertex, 1.0)).xyz;
    vNormal = (bt * vec4(aNormal, 0.0)).xyz;
  }

```

In pseudo code, it goes like this:

```
For each bone
  Calculate localMatrix from quaternion and translation
  If (is root bone) worldMatrix = localMatrix
  Else worldMatrix = parent's worldMatrix * localMatrix
  inverseBindpose = invert(worldMatrix)

For each keyframe
  For each bone
    Calculate localMatrixKF from quaternion and translation
    If (is root bone) worldMatrixKF = localMatrixKF
    Else worldMatrixKF = parent's worldMatrixKF * localMatrixKF
    offsetMatrixKF = worldMatrixKF * inverseBindpose
    Use offsetMatrixKF to deform the vertex

```

I've also tried deforming `(0.0, 0.0, 0.0)` with the bones' matrices to obtain the joint positions and I found `(0.0, 0.0, 0.0)`, `(-.87, .50, 0.00)`, `(-.87, 2.50, 0.0)` and `(1.73, 4.00, 0.00)` with the offset matrices and `(0.0, 0.0, 0.0)`, `(-.87, 1.00, 0.00)`, `(-.87, 1.50, 0.0)` and `(1.73, 1.00, 0.00)` with the world matrices at keyframe 2, where it bends past the XZ plane. The world coordinates look ok to me, I'm not really sure about the offset matrices, the 2.50 and 4.00 values look a little large to me.

Am I doing something incredibly wrong?

If necessary, I'll upload the full code somewhere.

Thank you in advance for your patience, I'm losing my mind over this.

---

# Answer
I solved my own problem. I drew the wireframe of the bones and then I understood. I didn't apply the transformations in Blender so I was deforming a mesh bigger twice than it should have been. See the picture:

The armature is clearly smaller than the mesh, this is the reason why the deformation came out incorrect. By applying rotation, location and scale in Blender (Ctrl+A on the 3D view) the problem went away. The algorithm as I described in the question turns out to be fundamentally correct. I hope that it might be of use to someone at least! :)
> 1 votes

---
Tags: glsl, webgl, skinning
---


title: Platformer Collision Detection Order

text:
# Question
Title: Platformer Collision Detection Order
I'm attempting to create a 2D Platformer Game and I'm having difficulty with the physics I have implemented. Each loop my code does the following:

1. Apply the physics to a temporary X and Y Co-ordinates to find the new position of the Player
2. Generate points around the sprite to check for collisions and assign them directions (Which allows for collision correction based on the direction of the collision)
3. Loop through each of the points, find the Tile each point is on and check whether it is solid. If it is, mark that direction (The direction linked to the point, that I created earlier) as solid.
4. After checking all of the points, only apply the physics to X and/or Y if no collision is detected for that direction.

My code, simplified, is below:

```
var tileWidth = 8, // Tile Width/Height
    gravity = 0.3, // Map Gravity
    friction = 0.8, // Map Friction
    speed = 10, // Get the Users Speed
    xVelocity = 0, // Get the Players X Velocity
    yVelocity = 0, // Get the Players Y Velocity
    x = this.x, // Players X Value
    y = this.y, // Players Y Value
    origX = x, origY = y, // Store the original X & Y Values for later use
    jumping = this.jumping, // Get whether the Player is currently jumping
    grounded = this.grounded, // Get whether the Player is currently grounded
    scale = 4, // Store the Global Graphics scale for rendering
    spritesheet = this.spritesheet; // Fetch the Players Sprite

if(isPressed(UP_ARROW)) { // If the Up Arrow Key is pressed
    if(!jumping && grounded) { // If the Player is grounded and NOT already Jumping
        jumping = true; // They're now Jumping...
        grounded = false; // And no longer grounded
        yVelocity = -(speed / 2) * 2;
    }
}
if(isPressed(RIGHT_ARROW)) { // If the Right Arrow Key is pressed
    if(xVelocity < speed) {
        xVelocity++;
    }
}
if(isPressed(LEFT_ARROW)) { // If the Left Arrow Key is pressed
    if(xVelocity > -speed) {
        xVelocity--;
    }
}

// Apply Gravity and Friction to the X & Y Velocities
xVelocity *= friction;
yVelocity += gravity;

grounded = false; // Reset the grounded value to allow jumping

var points = [],
    newX = (x + xVelocity),
    newY = (y + yVelocity),
    tile = null,
    dir = null,
    checkedDown = false,
    tilesWidth = Math.ceil(spritesheet.getWidth() / (tileWidth / 2)),
    tilesHeight = Math.ceil(spritesheet.getHeight() / (tileWidth / 2));

for(var h = 0; h <= tilesHeight; h++) {
    points.push([ newX, newY + (h * ((tileWidth / 2) * scale)) + ((h == 0) ? 1 : ((h >= tilesHeight) ? -1 : 0)), 0 ]);
    points.push([ newX + (tilesWidth * ((tileWidth / 2) * scale)), newY + (h * ((tileWidth / 2) * scale)) + ((h == 0) ? 1 : ((h >= tilesHeight) ? -1 : 0)), 1 ]);
}
for(var w = 0; w <= tilesWidth; w++) {
    points.push([ newX + (w * ((tileWidth / 2) * scale)) + ((w == 0) ? 1 : ((w >= tilesWidth) ? -1 : 0)), newY, 2 ]);
    points.push([ newX + (w * ((tileWidth / 2) * scale)) + ((w == 0) ? 1 : ((w >= tilesWidth) ? -1 : 0)), newY + (tilesHeight * ((tileWidth / 2) * scale)), 3 ]);
}

var moveLeft = true,
    moveRight = true,
    moveUp = true,
    moveDown = true,
    solid = false;

for(var p = 0; p < points.length; p++) { // For all the generated checking points...
    dir = points[p][2];
    tile = Engine.manager('map').getActive().findTile(points[p][0], points[p][1]);
    solid = tile.isSolid();

    if(solid) { // If this Tile is Solid...
        switch(dir) { // Switch based on the Tile's direction

            case 0: // Left
                moveLeft = false;
            break;

            case 1: // Right
                moveRight = false;
            break;

            case 2: // Up
                moveUp = false;
            break;

            case 3: // Down
                moveDown = false;
            break;

        }
    }
}

if(!moveDown) {
    yVelocity = 0;
    jumping = false;
    grounded = true;
}
if(!moveLeft || !moveRight) {
    xVelocity = 0;
    jumping = false;
}

if(grounded) yVelocity = 0;

// Add the X & Y Velocity to the X & Y values
x += xVelocity;
y += yVelocity;

// Round off our X & Y Value to stop Graphical glitches
x = Math.ceil(x);
y = Math.ceil(y);

```

(Copied from the Entity Update Loop, the `scale` value is for scaling up graphics)

The Collision points generation would generate points like this:

The issue I'm having is that when a player falls and hits the floor, the collision detection for Left and Right is triggered. This is because it checks for collision on Left, Right, Up and Down with the new co-ordinates, and even if they collide with the ground it triggers the Left/Right because they were also in a solid tile at the time. What I want to know is; how should I go about this? I've been trying to think of a different way to approach this but I've had no luck, I'm not great when it comes to physics (Hence the super-simple Friction and Gravity)

# Answer
Once you know that your rectangles collided, you can use the square of the distance between them to know from which side, the collision took place.

```
var pRect; // Player rectangle
var oRect; // Other rectangle

if (intersects(pRect, oRect))
{
    // Calculate the vertical and horizontal
    // length between the centres of rectangles

    var hd = abs((pRect.centerX * pRect.centerX) + (oRect.centerX * oRect.centerX));
    var vd = abs((pRect.centerY * pRect.centerY) + (oRect.centerY * oRect.centerY));

    // Now compare them to know the side of collision

    if (hd < vd)
    {
        if (pRect.centerX < oRect.centerX)
            // Collision on right side of player
        else
            // Collision on left side of player
    }
    else if (vd < hd)
    {
        if (pRect.centerY < oRect.centerY)
            // Collision on bottom side of player
        else
            // Collision on top side of player
    }
}

```

Hope this helps.
> 4 votes

# Answer
The "left" and "right" collision points should start "below" the top collision point and "above" the low collision point so they won't be triggered when standing on the floor or hitting your head against a ceiling.

Also, it might make it easier to do collision checking *before* moving your player, rather than moving, and then collision checking.

An easy way to achieve this, is to remove the topmost and lowermost "side" collision checking points.
> 0 votes

---
Tags: physics, platformer
---


# Question
Title: Quad Texture to Pixel Screen Space (DirectX 11)
I think I must be using the wrong wording for what I want, because I seached and just kept finding pixel shader questions. But this seems like something that anyone making a 2D game would want.

Basically I have my quad, my loaded texture in a ID3D11ShaderResourceView and I can draw it to the screen using coordinates of -1.0 to 1.0.

But what I want to accomplish is drawing based on pixels.

i.e.

I would want to draw a 20x20 pixel image to coordinates 100,100 on a 800x600 screen. But, I want to do this by manipulating the quad to the correct size and position to mimic this (which is, I assume, a common way to do 2D in DirectX11).

As I said, I am able to draw a texture to screen space at the moment but I am lost as to what calculations or methods would be required to convert this to pixel-based drawing.

Thank you :)

# Answer
> 1 votes
The normal way to do this would be to create a matrix representing the transformation from game world coordinates to screen coordinates. Note that I never mention resolution here because it does not come in to play directly. For such a projection the only thing important is the aspect ration.

In your vertex shader you would just multiply the input position with the matrix and output the new position to your pixel shader. Alternatively if you are not using shaders (or well, if they are hidden from you) you could apply the matrix manually to each vertex before you send it to the graphics device.

How to create such a matrix requires just a few calculations on paper. For example: if your game world coordinates are from 0~100 and your screen coordinates are -1~1 you would need to scale by 0.02 and translate by -1.0 (in that order). Remember that you can combine multiple successive matrix operations by pre-multiplying the matrices.

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


title: Obfuscating Monogame assets

text:
# Question
Title: Obfuscating Monogame assets
I'm obfuscating spritesheets. I've already encrypted the .txt file dictionaries. Now I'd like to perform binary serialization on the image files. `Texture2D` does not allow for this though, probably because it's coupled to the `ContentManager` and by extension the `Graphicsdevice`.

The solution I'd like to go for would be serializing the image files in a single wrapper object in the obfuscation code, and deserializing it when the game is loading. However, `Content.Load<Texture2D>()` will only take the asset name as parameter. Is there a workaround, or am I looking at this problem the wrong way?

# Answer
> 2 votes
Probably the ideal extension point for something like this is to inherit from `ContentManager`. Here is a blog post (for XNA) that explains how to use `ReadAsset` to change the caching policy (not what you want).

What you probably want to do is inherit from `ContentManager` and override `OpenStream`. Then simply implement obfuscation at the stream level (ie: obfuscate the entire asset file).

Alternately you could just override `Load` and handle `Texture2D` explicitly to do whatever you want. You could, for instance, call `ReadAsset<ObfuscatedTexture2D>(...)` and then construct a `Texture2D` instance yourself and return that.

If you're creating the texture yourself, you'll need a graphics device to load it onto. It can be accessed through the `ContentManager.ServiceProvider` property. Like so:

```
var gds = ServiceProvider.GetService(typeof(IGraphicsDeviceService)) as IGraphicsDeviceService;
var graphicsDevice = gds.GraphicsDevice;

```

(Note: This will work in XNA. It should work in MonoGame, but if not... use the source.)

---
Tags: c#, monogame, assets, security
---


title: Determine speed of sprite

text:
# Question
Title: Determine speed of sprite
I'm trying to calculate the speed of my sprites in Cocos2d but I'm having some difficulties. I'm not sure which units of time/speed cocos2d uses.

My background sprite moves 2 positions to left each .004 seconds. I have a sprite that is generate each 3 seconds at position X0. The sprite moves until X1. I would like that his speed would be the same as the background.

This is how I'm scheduling the background movement and the other sprite generation:

```
this.schedule(this.gameLogic, 3);
this.schedule(this.moveBg,.004);

```

this is how I'm changing the position of the background

```
var X = bg.getPositionX();
      var X1 = bg1.getPositionX();
      //alert(X);
      //alert(bg.getBoundingBox().width);
      bg.setPosition(X-2, 0);
      bg1.setPosition(X1-2, 0);

      if ( X < -bg.getBoundingBox().width) {
        bg.setPosition(bg1.getPositionX() + bg1.getBoundingBox().width, bg.getPositionY() );
      }

      if ( X1 < -bg1.getBoundingBox().width) {
        bg1.setPosition(bg.getPositionX() + bg.getBoundingBox().width, bg1.getPositionY() );
      }

```

And this is how I'm determining the X0, X1 and speed of sprite.

```
star.setPosition(winSize.width + star.getContentSize().width/2, Y);
        this.addChild(star);
        var from = winSize.width + star.getContentSize().width/2;
        var to = -(winSize.width+ star.getContentSize().width/2);

        // Create the actions
        //var actionMove = cc.MoveTo.create(2, cc.p(-star.getContentSize().width/2, Y)); // 3
        var actionMove = cc.MoveTo.create(14, cc.p(to, Y));

```

How can I determine the speed of star to be the same as bg?

# Answer
> 4 votes
There are a number of things to ask, but if you understand the basics you should be able to not just determine the speed your sprite is moving but dictate it.

Unless you are overtaxing the processor, or you schedule a routine to "update" less often, the game "loop" is going to execute 60 times per second. Assuming the routine that moves your sprite is being executed with each loop, then the number of pixels you move the sprite multiplied by 60 is the speed that your sprite moves in a second.

Now if you are using Cocos2d actions, such as "move to", where you must indicate a duration for the action, then the number of points between the starting and ending position divided by the duration is the speed that your sprite will move each second.

In short, you determine the speed that you want your sprite to move, not Cocos2d.

Based on your code, you appear to want your background sprite to move 2 pixels every .004 seconds. That is extremely fast, as it equates to 15,000 pixels per second. I can only assume this is not what you are intending.

In any event, have your game loop execute 60 times per second, or at whatever interval works for you, and move your sprite the number of pixels per iteration as desired.

I hope this helps.

---
Tags: physics, game-mechanics, cocos2d, cocos2d-x
---


title: DirectX 11 Updating Resolution

text:
# Question
Title: DirectX 11 Updating Resolution
Searched for a while thinking this would have some obvious tutorials but I can't find anything... which makes me think I must be using the wrong wording because it seems obvious.

Anyway, when I create my project, I have have a constant resolution of 800x600 set. This is used to set up:

my window buffer description swap chain description depth stencil description viewport

So, if I want to change my resolution to 1920x1080 what do I need to do?

Do I need to re-describe all of these things each time I change resolution and re-create them? Do I need to do it for just some of them? (I know resizing the window itself isn't a big deal)

Either way it seems like a lot of things use your window size so I was hoping there would be something that updates them all or a function for each that's used when you are changing resolution and nothing else.

# Answer
> 4 votes
This is documented at: **DirectX Graphics Infrastructure (DXGI): Best Practices** and further discussed at **DXGI Overview: Care and Feeding of the Swap Chain**.

There are 3 basic calls involved, as follows:

IDXGISwapChain::SetFullscreenState
This is used to switch between fullscreen and windowed modes; if you're not switching (i.e you're going from a fullscreen to a fullscreen mode, or from a windowed to a windowed mode) you don't need it.

IDXGISwapChain::ResizeTarget
In a fullscreen mode this changes the display resolution; in a windowed mode this changes the size of the window. However it doesn't resize any of the underlying D3D objects (such as your backbuffer, your depth/stencil buffer, etc), so for that you need:

IDXGISwapChain::ResizeBuffers
This will resize the backbuffer to match either an application-provided size **or** the size of the client rect of your window, depending on parameters you specify. It will **not** resize your depth/stencil buffer.

To resize your depth/stencil buffer you should destroy it and recreate it. You already have the code needed to destroy it in your program's shut down code, and you already have to code needed to recreate it in your program's startup code, so it's highly recommended that you reuse those.

You will also need to reset your viewport manually, as well as manually recreate any render targets you're using which need to match the window size/video mode.

It's also **highly** recommended that you read the first two links I've provided very carefully, as well as the individual documentation for each call. There are some corner-cases where things may not work as you expect (it's best to ask separate questions about them if you run into them) and DXGI will operate in one of two modes: either it will handle most things automatically for you (but it may not do so the way you want) or you will have to do all the work yourself, depending on if you've used IDXGIFactory::MakeWindowAssociation or not.

My recommendation is to **not** put this code into your own program just yet. Instead make a standalone program that just draws a black screen, and work through mode changing in that until you have a good understanding of what needs to be done and when and how to do it.

DXGI has it's own logic and if you use it the way it was designed to be used you'll do fine; if you try to fight against it or try to shoe-horn a different way of working onto it, you'll create a mess. It's best to have that learning experience in a separate program.

---
Tags: directx11, resolution
---


# Question
Title: How do I make a puzzle piece move smoothly between locations?
I'm building a 2048 clone to sharpen my Libgdx skills, but I don't know how to ease a tiles between board locations. When I slide my finger, the tile moves rather swiftly. How I can make the movement smoother?

This is the code I'm using to make it move to the left:

```
 for(float t=0;t<getMax(currentTile);t++
 {
  shapeRenderer.begin(ShapeType.Filled);
  shapeRenderer.setColor(230/255.0f, 220/255.0f, 230/255.0f, 1);
  shapeRenderer.rect(q-t, r, a, b);
  shapeRenderer.end();
 }

```

# Answer
> 4 votes
At the moment, you're moving the piece with a *linear interpolation*.

That means that every timestep, the tile's position changes by the same amount.

```
position = position + translation * timestep

```

You could use any function there:

```
position = position + translation * f(timestep)

```

Then the position changes by an amount determined by the function `f`.

There are a bunch of easing functions that people have found to work well for producing smooth transitions.

Robert Penner maintains implementations in various languages. *Expo out* and *expo in-out* are quite pleasant for puzzle pieces, though you might want to try *elastic in-out* for a stretchier, more playful effect.

The original 2048 seems to interpolate linearly between positions though.

# Answer
> 1 votes
Just to expand on Anko's answer - Easing functions are great, but they aren't necessary in every situation. Although not really initially meant for this purpose, Linear interpolation can also be used to create a simple easing effect, you simply have to call your interpolation function every frame with the same fraction given.

Think about it like this: your object will move half of the distance to the destination, then half of the *new* distance the next frame, and so on, until it reaches its destination (or approximates it well enough). This is a quick and easy way to approximate an easeOut function in what's essentially a single line of code.

I'm going to paste my own Lerp function and how I call it to achieve this effect, but with a bit of searching you can find a bunch of different ways to achieve the same thing.

```
float Lerp(float a, float b, float fraction)
{
    return (a * (1.0f - fraction)) + (b * fraction);
}

```

This is how I call the function every time the game updates:

```
playerVelocity.x = Omega2D::Lerp(playerVelocity.x, 0.0f, 0.2f);

```

Though my example uses the function to decrease my player's velocity vector on one axis, the way you'd use it to change positions is identical. Essentially, you're telling it to change your value to 0.0f, and to move 0.2f of the distance every frame. The higher the fraction (0.2f) is, the 'faster' your movement will seem.

---
Tags: android, libgdx, tiles, movement, puzzle
---


# Question
Title: Shadow map: depth texture always returns 0
I'm implementing a shadow map for the sun light in my voxel engine using a depth texture attached to a framebuffer. But when I sample the depth texture during the normal pass, the value returned is always 0.

Here is the shadow map initialization :

```
    // Create and configure the depth texture
    shadowMapTextureId = GL11.glGenTextures();
    GL11.glBindTexture(GL11.GL_TEXTURE_2D, shadowMapTextureId);
    GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_DEPTH_COMPONENT, shadowMapWidth, shadowMapHeight, 0, GL11.GL_DEPTH_COMPONENT, GL11.GL_FLOAT, (FloatBuffer) null);
    GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR);
    GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR);
    GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL13.GL_CLAMP_TO_BORDER);
    GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL13.GL_CLAMP_TO_BORDER);
    GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL14.GL_TEXTURE_COMPARE_MODE, GL30.GL_COMPARE_REF_TO_TEXTURE);
    GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL14.GL_TEXTURE_COMPARE_FUNC, GL11.GL_LEQUAL);
    GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);

    // Create the framebuffer and attach the depth texture
    shadowMapFramebufferId = GL30.glGenFramebuffers();
    GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, shadowMapFramebufferId);
    GL30.glFramebufferTexture2D(GL30.GL_FRAMEBUFFER, GL30.GL_DEPTH_ATTACHMENT, GL11.GL_TEXTURE_2D, shadowMapTextureId, 0);
    GL11.glDrawBuffer(GL11.GL_NONE);
    GL11.glReadBuffer(GL11.GL_NONE);

    if (GL30.glCheckFramebufferStatus(GL30.GL_FRAMEBUFFER) != GL30.GL_FRAMEBUFFER_COMPLETE)
        Voxer.error("Shadow map framebuffer creation");
    GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, 0);

```

And the fragment shader sampling the depth texture :

```
    #version 330 core

    uniform sampler2DArray diffuseTextures;
    uniform sampler2D shadowMap;

    in vec3 pass_TextureCoord;
    in vec4 pass_ShadowCoord;
    in float pass_Lighting;

    out vec4 out_Color;

    void main(void)
    {
        out_Color = texture(diffuseTextures, pass_TextureCoord);

        float shadowFactor = 1.0;
        vec4 shadowCoordPostW = pass_ShadowCoord / pass_ShadowCoord.w;

        if (pass_ShadowCoord.w > 0.0f && shadowCoordPostW.x > 0 && shadowCoordPostW.y > 0 && shadowCoordPostW.x < 1 && shadowCoordPostW.y < 1)
        {
            float shadow = texture2D(shadowMap, shadowCoordPostW.xy).x;
            float epsilon = 0.00001;
            if (shadow + epsilon < shadowCoordPostW.z)
                shadowFactor = 0.5;
            // I can replace with this to show that the value is always 0
            // if(shadow == 0)
            //  shadowFactor = 0.5;
        }

        out_Color.rgb *= shadowFactor * pass_Lighting;
    }

```

I use the same projection matrix for the main camera and the sun camera (it's a perspective matrix), so I know the terrain is in the view frustum.

I used this example : https://github.com/cforfang/opengl-shadowmapping

# Answer
### You are using `sampler2D` with a texture that has `GL_TEXTURE_COMPARE_MODE` != `GL_NONE`.

That is not going to work, you are invoking undefined behavior.

### This line:

```
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL14.GL_TEXTURE_COMPARE_MODE, GL30.GL_COMPARE_REF_TO_TEXTURE);

```

Tells OpenGL that when you fetch something from this texture, rather than returning the actual value, what it is ***supposed*** to do is fetch a value and then perform a comparison against the `R` coordinate in your texture coordinates.

*What `R` coordinate, you ask?* ***Precisely!***

Using `sampler2D` with a texture that performs comparison produces undefined results because you sample a `sampler2D` with 2D texture coordinates. There is no 3rd coordinate to perform any comparison using.

---

### You have two options here:

1. You switch to `sampler2DShadow` and add a depth value to test to your texture coordinates
2. You remove the line of code mentioned above, and perform shadow comparison yourself.

Personally, I would go with approach **#1**:

```
uniform sampler2DShadow shadowMap;

...

float epsilon = 0.00001;
float shadow  = texture (shadowMap,
                         vec3 (shadowCoordPostW.xy, shadowCoordPostW.z + epsilon));

// The result of the above `texture (...)` will be a floating-point value between
// 0 (fully blocked) and 1 (fully unblocked)
if (shadow < 1.0)
  shadowFactor = 0.5;

```

If you enable linear filtering of your shadow map, instead of returning ***exactly*** **1.0** or **0.0**, `sampler2DShadow` will fetch the 4 nearest depths, perform 4 individual tests against your `R` coordinate and then return the average value. This gets you rudimentary shadowmap anti-aliasing; unfortunately a 2x2 window (like this uses) is not adequate in most cases, but it is a cheap form of anti-aliasing.
> 7 votes

---
Tags: opengl, lwjgl, shadow-mapping, frame-buffer
---


title: file:write restarts Corona app

text:
# Question
Title: file:write restarts Corona app
I am attempting to implement an auto-save feature into a mobile game. I have the following code writing to the save file:

```
function saveFunc(input)
local saveData=input
local file = io.open( "saveFile.txt", "w" )

for i,val in ipairs(saveTable) do
    saveData=saveData.."\n"..val
end

file:write( saveData )
io.close( file )
end

```

This writes to the file correctly. The problem is that after the function finishes, the whole app restarts. Watching the output console, it re-prints the "Copyright (C)..." as if I had Relaunched the app.

I know it is this specific function because if I comment out the call for this function the game continues as normal. I also tried commenting out the `io.close(file)` but the program still restarted.

How can I write to a file and not restart the app?

# Answer
> 0 votes
The code used is saving the document to the local folder. This means that every update of that file will re-launch the app (at least in the emulator). To prevent this, save to `system.DocumentsDirectory` like so:

```
local file = io.open(system.pathForFile("pokedex.txt", system.DocumentsDirectory), "w" )

```

---
Tags: lua, corona-sdk
---


# Question
Title: Why are cube map axes sometimes labelled incorrectly?
In both 3ds Max (which uses a right-handed coordinate system) and Unity (which uses a left-handed coordinate system), the cube map faces labelled "left" and "right" show the view facing the opposite direction. This is not the case with the front, back, up, or down directions.

In 3ds Max, this is in the context of rendering cube map images from a Reflect/Refract map. In Unity, both cube map textures and skyboxes exhibit the same left/right "confusion". Oddly, however, the GUI labels for cube maps indicate that left is the -X direction and right is the +X direction - which is correct in Unity - while skyboxes indicate the opposite (all other axial labels are consistent between the two).

The upshot of this is that cube map images rendered by 3ds Max (which each have a suffix indicating their viewing direction) can be assigned to the texture slots in Unity with the same name and everything will work, but only because both programs label the left view as "right" and vice versa.

The only discussion of this I was able to find online was in a blog post on floored.com (search for "Unity Skybox Weirdness" and it should come up; I'd post a link but I lack sufficient reputation to include more than two). Here's an image from the post that illustrates the issue:

Is there a reason why the left/right axes of cube maps are mislabelled in both of these programs? Although it's trivial to ignore once you're aware of it, it seems like there should be a good (or at least historical) explanation for it, unless it's simply a case of a long-overlooked bug in 3ds Max that the Unity developers decided to accommodate.

Any thoughts would be appreciated!

# Answer
> 4 votes
This could be a confusion over whether one thinks of oneself as being inside or outside the cube for the purposes of labeling things. You're thinking of yourself as inside the cube, and you note that left/right are reversed. However, imagine yourself outside the cube; rotate it 180 degrees so that the "front" side is facing you; now the left/right sides are correctly labeled from your POV.

You might think that for a skybox, you would only ever want to think of yourself as being inside the cube. However, if cubes are used as environment maps for specular reflection, it can make sense to think of yourself as outside. That's probably the origin of the 3DS Max convention, I'd guess.

IMO, instead of using words like "front", "back", "left", "right" it's better to simply refer to cube faces as +X, -X, +Y, -Y, etc. This avoids the left/right ambiguity as well as the ambiguity of which axis is thought of as "front".

---
Tags: unity, 3dsmax, cubemap
---


# Question
Title: Unity3d not allowing endpoint to save cookies
So I'm using an external DLL with Unity to login to a web service and access functions from it.

The DLL works perfectly fine in a command prompt project, but when run in Unity I can log in successfully, but when I try to use any commands I get a session has expired error.

The DLL stores session cookies in the endpoint, so it appears that Unity isn't allowing this custom endpoint to store cookies.

Does anyone know how to make Unity allow custom endpoints to store cookies? Or where in an endpoint I could parse the cookie from so I could feed it in with any service commands?

For reference, here's a link to the main DLL, and here's a link to ContentService. The main DLL is compiled for .NET 3.5 so as to work with Unity.

Just as a reference, here's the exact error code I'm getting in Unity:

```
FaultException: Your session has expired.
System.ServiceModel.ClientRuntimeChannel.Request (System.ServiceModel.Description.OperationDescription od, System.Object[] parameters)
System.ServiceModel.ClientRuntimeChannel.DoProcess (System.Reflection.MethodBase method, System.String operationName, System.Object[] parameters)
System.ServiceModel.ClientRuntimeChannel.Process (System.Reflection.MethodBase method, System.String operationName, System.Object[] parameters)

```

# Answer
I recommend using a tool, such as Chrome's Advanced REST client or WireShark to see what needs to be communicated to your server. There is a learning curve, but you will see both sides of the HTTP session.
> 1 votes

# Answer
I found these links to be helpful. The first describes how to deal with cookies. The second is a nice tutorial showing how to send login and registration data to a php-based web server. The tutorial focus on the client side, no info on what you have to do on the server side.

http://plyoung.wordpress.com/2011/08/05/unity-3d-and-session-cookies/

http://unity-tutorials.blogspot.com/
> 0 votes

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