title: C++ OpenGL ShadowMap Issue/Artifacts

text:
# Question
Title: C++ OpenGL ShadowMap Issue/Artifacts
I am currently implementing basic **shadow mapping** in my C++ Custom Engine using **GLSL 4.10**. It is currently working with basic PCF anti-aliasing and very minimal reduction for unwanted artifacts. Here is a screenshot for reference:

Recently, I have started modifying my shadow map pipeline to reduce **shadow acne**. After reading through various articles, many suggest either using a bias value, which is subtracted from the depth value being compared to the shadow map

```
// Shadows
float bias = 0.0005;
vec4 shadowCoordinate = u_worldToShadowMapSpaceTransform * vec4( worldPosition.xyz, 1.0 );
shadowCoordinate.z -= bias;
float shadowValue = textureProj( u_shadowMap, shadowCoordinate );

```

and or to cull front faces when rendering to the shadow map.

```
glCullFace( GL_FRONT )
// Render to ShadowMap FBO
glCullFace( GL_BACK )
// Render Scene

```

Culling front faces reduces most of the shadow acne but creates another problem that none of the articles have mentioned. The screenshot below shows the issue. If you look at the white box in front of horned creature, you will notice the creatures's shadow is cast upon the other side of the box. This is because the front faces of the box are culled which leads the back faces to compare their depth values against geometry to the north of the box.

Naturally, this also leads to these shadows also being cast below the floor as well as above. Here is a screenshot of the bottom of the floor. It is difficult to see but you can see the shadows being cast.

I believe many 3D engines utilize variations of these artifact reduction techniques. So, how do they avoid the shadow casting issue described above?

# Answer
try using a multiplicative "bias" instead of additive:

```
shadowCoordinate.z *= 0.98;

```

If you're doing the sampling yourself rather than using the shadow comparator interpolating the shadow map helps reduce acne a lot.

There shouldn't be any shadow visible behind the object as the light should not affect it with the light being completely occluded by the object itself.

Global ambient light should not be affected by shadows, shadows should only cuts off the light that is casting the shadow not the other lights.

```
vec3 output_color = ambient * material_diffuse;
foreach(light){
  float shadow_masking = light.CalculateShadow();
  output_color += light.Calculate(material_diffuse, material_specular) * shadow_masking;
}

```

Here's 3 colored point lights using cubemap shadow casting and 1 directional. Shadow maps are rendered front-face (the usual back-face culling). Single-pass forward-shading. And a multiplicative "bias" of 1.02 applied to the shadow depth. Shadow map depth is interpolated. The columns grooves are actually modeled (not normal maps) to stress test self-shadowing and shadow acne issues. The 3 small spheres are the point light sources. Rendered on an nVidia GTX 560M. The minimum requirement is GLSL 1.1 (OpenGL 2.0).

Edit: Adding pseudo-code of the internals of sample2DShadow vs sampler2D

sample2DShadow:

```
float A = Nearest(tex, floor(coord.xy + vec2(0, 0))).r < coord.z ? 1.0 : 0.0;
float B = Nearest(tex, floor(coord.xy + vec2(1, 0))).r < coord.z ? 1.0 : 0.0;
float C = Nearest(tex, floor(coord.xy + vec2(0, 1))).r < coord.z ? 1.0 : 0.0;
float D = Nearest(tex, floor(coord.xy + vec2(1, 1))).r < coord.z ? 1.0 : 0.0;
return Lerp( Lerp(A, B, fract(coord.x)), Lerp(C, D, fract(coord.x)), fract(coord.y));

```

sampler2D on depth texture:

```
vec4 A = Nearest(tex, floor(coord.xy + vec2(0, 0))).rrrr;
vec4 B = Nearest(tex, floor(coord.xy + vec2(1, 0))).rrrr;
vec4 C = Nearest(tex, floor(coord.xy + vec2(0, 1))).rrrr;
vec4 D = Nearest(tex, floor(coord.xy + vec2(1, 1))).rrrr;
return Lerp( Lerp(A, B, fract(coord.x)), Lerp(C, D, fract(coord.x)), fract(coord.y));

```

Both types of samplers do 1 bilinear interpolation, but the sampler2DShadow does it on the boolean result.
> 5 votes

---
Tags: opengl, c++, glsl, shadows, shadow-mapping
---


# Question
Title: Fastest way to find closest triangle of mesh from specified point
I have two triangle meshes (let me call them A and B). The meshes may be really big (10.000 - 100.000 polygons). I want to find for every point in A the closest triangle from mesh B.

Is there a fast way to do it? Does a near real time solution exist?

I found several papers that describe ways to find distance from a point to a triangle and I know a little bit about kd-tree/bvh-tree. Hence I may be able to find several triangles that are close enough to the specified point and then I can find triangle by brute force.

But I guess that this method will be not fast enough.

# Answer
> 8 votes
Create an octree and in each leaf cells put the list of all triangles from B that intersect the cell, mark at each levels whether or not the cell is empty. If one cell at any level has only 1 poly note the poly so you can stop the search early (large floor/wall triangles). You can keep sub-dividing cells until you have a reasonable number of triangles in each cells.

Using the octree find the closest non-empty cell.

Find the closest triangle in this cell, note the distance.

For each non-empty cells that are within this distance: Find the closest triangle in these cells, keeping the closest distance, ignoring cells that are further than this each time.

The reason for this last iteration is that a triangle at the far end of a cell might be further than a triangle in a neighbor cell.

If you need more speed you can use this with GPGPU (e.g.: OpenCL) to both build the octree and to iterate over every points of A in parallel once your octree is built.

Note that GPGPU performance varies greatly between GPUs. So what is realtime on one might be barely faster (or even slower) than the CPU.

---
Tags: mathematics, algorithm, mesh
---


title: How do you save Path2D data?

text:
# Question
Title: How do you save Path2D data?
I am making a java game using path geometry. Is there any way to save the data stored in a Path2D to a file?

# Answer
I have not tried any of these, but the following three solutions should work.

## Save the input data

Instead of saving the Path2D object, save the values you have used to create the objects. As you said in the comments that you are creating the Path2D objects yourself using the API, you have the source data and you can control what to do with that.

## Java serialization

If the first method sounds too complicated to fit to your application or you just prefer alternative solutions, Java's own serialization mechanism should do the trick. Path2D.Float and Path2D.Double implementations implement the Serializable interface, which means that they can be saved and loaded easily using ObjectOutputStream and ObjectInputStream. There are plenty of tutorials online if needed.

## PathIterator

You can also use Shape.getPathIterator() to return an instance of PathIterator. This interface gives you the individual line and curve segments of the Path2D object, which you can save to a file. PathIterator and Path2D use the same types of segments, so this method should allow reconstructing the paths without losing any information. Note that while the getPathIterator() doesn't guarantee to return the exact same shape, checking the source code of Path2D seemed to return the internal model in their exact form. In contrast e.g. Ellipse2D can't be exactly represented with a PathIterator.
> 0 votes

---
Tags: java, 2d, savegame
---


# Question
Title: Player acceleration formula and using it with authoritative server
I know the theory behind authoritative client-server architecture, it works very well for character movement in a tile-based world: you send messages like "I moved one square to the right", the server double checks that and sends the correction. But what if I need acceleration-based system like for a race car game? You start slowly and gradualy increase your speed over time and when you release throtle, you loose speed depending on how fast you are moving right now.

When we tried implementing this system with our naive acceleration formula we ran into a problem: pawns move differently on server and client. That does NOT mean the sever's pawn (obviously) lags, that means after any movement action they end up in different places in the world. We only pass messages with the actions for the movement: that is if the player pressed "forward" we send "forwardON" and raise that flag on the server, similarly when the "forward" action key is released we send the appropriate message. I believe that is the way to do it for the acceleration system, right? You cannot send velocity as you will need to send 60 packets per second and you might still have trouble syncing everything.

So my question is: what sort of movement formula do you need to use for such scenarios and how do you send messages to make sure client and server are syncronized?

UPDATE: we already use smoothing, that is wenever the server and client is not far appart, we smooth the client's position to prevent client "jumping" from place to place. But the client's movement are often VERY different from the server's and that depends on how big lag is, that is why we need to improve our system.

# Answer
Skew happens.

This is a clock synchronization problem.

Two nodes on a network can't know *for sure* what each other's clocks are. You can send the current time, but the receiver can't know for sure how old that value is. A good guess, though, is that it's stale by half the ping time. See http://en.wikipedia.org/wiki/Round-trip\_delay\_time.

One approach then, is to measure the ping time, and update it regularly. When the server gets a velocity-change message from the client, assume that the action occurred half the ping time in the past, and back compute it up to the present. The client must make similar assumptions about messages from the server. Include world time stamps on all the messages in both directions. Send regular "absolute position" updates as well, at whatever rate you can achieve.

And then your occasional smoothing-fixups, where absolute position is used, will be *less* pronounced.

Also relevant: http://en.wikipedia.org/wiki/Network\_Time\_Protocol

---

EDIT: Just saw this answer also, haven't viewed the answerer's link to a GDC presentation yet, but it sounds very interesting...

Why is there a huge update-delay in my client/server code?

GDC Presentation: http://www.gdcvault.com/play/1014345/I-Shot-You-First-Networking
> 2 votes

# Answer
Even in a fixed time-step environment(yes, you should use some sort of "turn based system" instead of timer, as you can easily slow down/up your turn duration), you will see math diverge.

This is a really trick problem called "determinism". Modern different hardware is non deterministic, especially when it comes to float math, due to specific acceleration adopted by HW.

One of the solution is to use flag or instruct your code-compiler-watever to stick to a less-fast-but-deterministic-math, like ieee745.

But sometimes this is not enught; on some system, specifically physic engine, there are a lot of things going on and sharing state and such, that in the end even on the same hardware, if the simulation is "replicated" and run you may see it diverge.

For example, in math z=x+y and then z+=k is the same as z=x+k, z+=y; but on computer work this is not true, as if the operation truncate parts of mantissa (see ieee754) you will get a (really small) difference. That will add up. Every step, and when an objects with a little error come touching another object with a little error... Here you have.

Technically, a full deterministic system (physic, AI, logic, same random seed) only need to synchronize user inputs, with a drastically reduction of needed bandwidth, and great smooth experience is case of great lag but low player density; but it comes with really enormous problem.

Already talked about using your own time system (aka turn) if the client hardware is fine and make a turn in 1ms, and youbwant logic run at 60fps, you have a lot of spare time. If timer are off, you can easily double the logic fps to catch up the missed frame, or slow it down to wait server.

Now talking about lag. One system is that server physic is old of about 200/300ms; when it get an action, if it is older than current state will be dropped, if newest put in queue, then execute the queue for that turn, and send, if needed, some info about what happened to client (like: at turn 10 x is dead) to be sure to have client synchronized about important things.

Client will have one world, synchronized from server, then every turn it will create a copy and step it for the missing turn (remember server is 200/300ms old) adding its own queue, and then display the results if that "estimation".

That is gonna prevent YOURSELF from jumping around, as long as your ping is \< 200/300ms.

Smooth still need be applied to smooth out lag from others player, (their command may get to you with 200/300ms late worst case) but will be less visible, especially if in low-player density area, as the mob moves should be deterministic.

This is obviously only one way of doing it, there are a lot of great resource about this problematic, and one of the most complete I've found is the official valve engine's doc. Read about professional with a great knowledge and skill "solve" the problem here https://developer.valvesoftware.com/wiki/Source\_Multiplayer\_Networking
> 0 votes

# Answer
From what I understand your question can be boiled down to one simple problem: the input from each player is applied to the shared game state in different order.

In the image above I am illustrating this problem with the coloured dots (which represent the players' input). Assuming 3 players, their shared game state should be the one labeled "real order". This would be the case only if there was no lag. Because of the lag though, we end up with the last line of game state where the players' inputs are delayed and out of order.

I think that to solve this problem one has to think about the basic game loop: gather input -\> update state -\> render. The server's game loop would probably look like this: receive input -\> update state -\> send state. Storing the inputs and the states would provide the advantage of being able to "rewrite history":

* receive input with time info and store it
* update the corresponding state and store it
* update all subsequent states until the current one and store them
* send the current state to players

What this allows us not is to store multiple states and storing multiple states will allow us to solve the problem of applying player input at the wrong frames.

Let's take a simple example to illustrate my point:

* t1
    + Player 1 (no lag) inputs something (P1-t1)
    + Player 2 (1 frame lag) inputs something (P2-t1)
    + Player 3 (2 frames lag) inputs something (P3-t1)
    + server receives input P1-t1
    + server evaluates input P1-t1 on f0 producing f1
    + server sends f1 to players
* t2
    + server receives lagged input P2-t1
    + server evaluates input P1-t1 and P2-t1 on f0 producing a new f1
    + server evaluates no input on f1 producing f2
    + server sends f2 to players
* t3
    + Player 1 inputs something (P1-t3)
    + server receives input P1-t3 and lagged input P3-t1
    + server evaluates input P1-t1, P2-t1 and P3-t1 on f0 producing a new f1
    + server evaluates no input on f1 producing f2
    + server evaluates input P1-t3 on f2 producing f3
    + server sends f3 to players
* t4
    + server receives no input
    + server evaluates no input on f3 producing f4
    + server sends f4 to players

Using this technique on the server side would make sure that the game state is in sync on the server. Using the same technique on the client side would make sure the game state is in sync on the clients as well. All this though is assuming that the game is deterministic.

Of course some kind of housecleaning will have to be done to free some memory. I think a simple technique for that would be to force each client to send a "noop" whenever there has been no input from the player to know which states have been fully evaluated.

I hope this helps.
> 0 votes

---
Tags: movement, multiplayer, client-server
---


# Question
Title: Steam hammer.exe Load custom textures for other players?
I sometimes make maps with custom textures, models, materials, sounds, etc. and I showed one of my map creations to my friend, and the custom textures were pink-and-black. It was intended to be a 'display-case' map with custom sprays & sounds upon clicking a button, but he just saw black and pink textures. Is there a way to make it built-in to the map and have it auto-download? I had the textures in its own folder, like "cars/materials/texture1.vtf"; it wasn't in the actual materials folder of my steam, it was just in its own folder. If I place the textures in the Steam materials/models/etc folder, will it automatically download it for other users?

**ON SINGLEPLAYER/LAN, BUT KNOWLEDGE FOR MULTIPLAYER WILL BE NICE FOR FUTURE REFERENCE**

# Answer
> 1 votes
Yes it is possible and no its not always the best idea.

If you store materials models and sounds, the person will be downloading 1 file which is much simpler but it bloats the map file to incredible sizes. Some custom mappers have noted going with a resource downloader when their maps reached 500+ megabytes in size which causes problems when downloading a single file on an unstable connection.

If your going to do this anyway then use this link. Valve Software Wiki Pakrat info

This video here is from a Guy I've learned some decent stuff in the past. 3kliksphilip

First step shows simple uploading to the workshop while step 2 uses pakrat to add the materials. You can do step 2 without step 1 but this video has merit because everything pretty much goes on the workshop these days.

Now the better way is sending all the files separately. The advantage to this is if you change the map but not any textures, they only need to redownload the map and not the textures. This is considered advanced and I can't find a way to explain it simply.

---
Tags: steam, hammer
---


# Question
Title: Does compressing data before transfer make a game run faster?
I want to make my game as fast as possible as it is real time and fast paced. I have already decided to encrypt my data here and I was wondering whether compressing it would be faster for the client and the server? Also I was wondering if it is better to encrypt data before or after compression.

# Answer
> 3 votes
It depends where the bottle neck is.

If you IO bound (the game is always waiting on network IO) then yes compressing will help.

If your game is CPU or memory bound then it will just run slower.

You should compress before encrypting because cipher text is less compressible as a result of trying to remove patterns that could be used to reverse engineer the cipher.

A better solution would be to make the protocol as compact as possible to begin with, for example by using a binary transfer method; binary data is easier to parse than text data and can be more compact (a double fits into 8 bytes while most doubles printed out take more than that).

---
Tags: java, client-server, data, compression
---


# Question
Title: convert image to spritesheet of tiles for isometric map?
is there a way to convert an isometric image (like the first image) to a spritesheet (like the second image), in order to place each image on the isometric map with the code?

The map looks like the first image, but some buildings are bigger than just one tile, so I need several squares (let's say the first image is a building, made of multiple tiles with different colors), and each square is placed with an offset of 64x32. The building is created in Blender and I save the image with the isometric perspective. But I have to split each square from this image in order to have the spritesheet, maybe there is smarter way, or a java software that would make the conversion for me?

# Answer
> 1 votes
Hopefully I understand correctly what you are trying to do.

First get all the 128 x 64 rectangles with each tile by iterating through the big image and taking subimages.

Then, use an alpha map to keep only the tile you are trying to separate. If you don't know what an alpha map is, there should be plenty of tutorials online explaining how to use them.

---
Tags: java, tiles, tilemap, isometric
---


title: Is it worth it to encrypt data?

text:
# Question
Title: Is it worth it to encrypt data?
I am using Java to write a moderately simple video game and I need to transfer some large files (edit: Live game data and possibly assets.) between the client and the server. I need to decide whether I want to encrypt the data even though no sensitive information is being transferred. If I were to encrypt the data what method would be the best? Also, does encrypting data make cheating harder?

# Answer
> 2 votes
Encrypting the data each player receives makes cheating and ripping of assets a bit harder, but not impossible. The data needs to be decrypted by your game client anyway, so the encryption algorithm and key must exist on the users machine. That means the users have everything they need to decode the network traffic. So you only add a layer of security through obscurity, which isn't any *real* security.

It could get interesting, however, when you have cheaters who are eavesdropping or even manipulating the connection of *other* players to get an advantage. Attacks of that level of sophistication are quite uncommon in gaming, but certainly not inconceivable, especially when cheater and target are on the same network. When you encrypt the data for each player separately with a key only known to the receiver, you can prevent that.

But make sure you use a cryptographically secure algorithm. There are libraries available for most common algorithms in most programming languages. In Java, you even have hard encryption in the standard library.

# Answer
> 2 votes
I see the following reasons to encrypt data:

1. Protect your users' *actual* sensitive data by adding to the amount of encrypted traffic. If hackers have to wade through not sensitive game assets, they're much less likely to find a user's actual sensitive data.
2. Protect *your* servers. Using asymmetric key encryption (like TLS, what people still commonly refer to as "SSL") usually ensures that the user is not tricked into giving their password to a man-in-the-middle, who can then use it to get a level deeper into your server. (assuming you verify who you're talking to)
3. Protect users' in-game purchases, e.g. in so-called "free to play" games. If your game has micro-transactions, attackers like to hack a user and transfer in-game items to another account under the attackers' control, where it can then be sold. Proper encryption makes it harder to spot the password in the traffic.
4. Protect yourself from stupid ISPs. Some ISPs (Hotel Wifi) look at clear-text traffic and modify it. E.g. replacing banner ads with their own. Also, certain mobile carriers will re-compress image files to save bandwidth. If your game assumes all assets are true-color PNGs and they convert them to 4-bit to save space, your game will crash. Using TLS encrypted connection ensures that the files your server sends are what your client gets, because ISPs can't introspect them. This is even more important if your downloaded assets contain scripts that an attacker could replace to run malicious code on your user's machine (esp. if you have automatic patches to your game engine that gets run as root via an installer, or so).

Whatever reason sways you, **do not roll your own encryption**. It's too easy to subtly get something wrong and do a lot of work but leave the barn wide open. Go with the established standard (i.e. use a TLS connection) to protect the data in transit, and verify the server certificate against its public certificate to be sure you're talking to the right machine (that's a thing commonly forgotten).

**Regarding cheating:** Your client has to be able to decrypt the data it gets and make requests. The client runs on the user's machine. If the client app can do that, it can do anything else. Reverse-engineering that is trivial. Is it harder to have *any* encryption compared to plain text? Sure. But it'll barely deter anyone. If your game has a network component, make all the game-relevant calculations happen on the server, and only transfer data to the user that they should have at this point in the game.

For speed, you can have the client pre-calculate the likely result of an action and display that while it asks the server to verify that and actually write it into the server's storage. If someone is trying to cheat, the server will thus catch it and the client's display will immediately reset to the "un-cheated" state.

Encryption is not an anti-cheat measure.

# Answer
> -4 votes
Do you care if people can get your assets? Do you transfer gameplay data? If any of the questions is true, then encrypt.

I would use XOR cipher. It's super simple, super efficient, not super secure but you apparently don't care (it WILL make cheating harder of course, if you send gameplay data though). It works with streaming data, and the encryption is the same as the decryption -- just apply it twice to get the original.

XOR cipher C++ code example:

```
char * key = "whatever";
int keylen = strlen(key);
int i, string_length = strlen(string);
for(i=0; i<string_length; i++)
    string[i]=string[i]^key[i%keylen];

```

where "key" is your cipher key. What it does is for each character of your string, you select a character from your key and you XOR it. when you XOR it again you get the original. Replace "whatever" with .. whatever :)

---
Tags: java, client-server, data, encryption
---


# Question
Title: Intersection between moving circle and some squares
I'm developing a 2D game made of squares.

What I need to do is check if a circle collides with any of the squares as it moves.

I have a raycast function to check the same idea, but using a point. I think the best idea would be to do a circle-raycast, but I have no idea how to do it.

The information I have:

* Starting coordinates of the center of circle
* Last coordinates of the center of the circle
* Radius of the circle

Given some coordinates, I can check if there is a square in those coordinates.

# Answer
First thing you should do to save some time is eliminate the ones that *can not* match. To do this, calculate the smallest rect that contains the circle. Intersect that with whatever rect you think might intersect with it (loop over all of them, most likely). Two rectangles intersect if they overlap both horizontally or vertically. There are three ways an intersection can happen:

Left edge of rect A is between left and right edges of rect B

Right edge of rect A is between left and right edges of rect B

Left edge of rect A \<= left edge of rect B and right edge of rect A \> right edge of rect B

And the same for vertical (i.e. swap top for left and bottom for right). If you have an intersection in both directions, the rectangles overlap.

If that doesn't match, they can't be intersecting. If it does, you can do more expensive, more complicated tests:

If the circle's surrounding rect fits into the rect you're intersecting with, you know they intersect.

The only cases left are whether the center of the circle lies inside the rect (point-in-rect test) and whether one of the rect's edges intersect the circle. For that, you use a circle equation. If your centre is a,b and your radius is r, you'd have to solve

```
(x-a)*(x-a) + (y-b)*(y-b) = r

```

to find out if a point (x,y) lies within the circle. So loop over each point in the line for each edge and plug it into the above equation as x,y. If any of them solve, you know that the rect intersects the circle.
> 2 votes

# Answer
This is a problem that has several solutions and optimizations to it, especially in 3d. 2d, there are fewer but still more than one "right answers". If you understand the first answer, but not this one, it has a good chance of being "Fast enough" on modern hardware there won't be a problem.

Another solution is Quadtrees: http://gamedevelopment.tutsplus.com/tutorials/quick-tip-use-quadtrees-to-detect-likely-collisions-in-2d-space--gamedev-374

Also linked in that article (at the bottom) is a good article on the general problems and optimizations

This is an area it's easy to over optimize if you are writing your own engine. Consider using a library such as http://box2d.org if *writing the game engine* isn't what you're concerned with.
> 2 votes

---
Tags: c++, raycasting, intersection
---


# Question
Title: How can I attach a libGDX actor to a box2D body?
I'm creating game like hill climb racing.

I created my car with the help of shapes and joints but I don't know how to attach graphics to it. I used actors and sprites before for the sake of learning, but I don't know how to use those with box2d bodies.

How can I?

# Answer
I have seen two ways of achieving this, one is to let the **UserData** of the **Box2D** `Body` hold the `Sprite`.

```
body.setUserData(mySprite);

```

And in the update you retrieve that and apply position and rotation to the `Sprite` according to the `Body`'s transform;

```
Sprite sprite = (Sprite)body.getUserData();
Vector2 position = body.getPosition();
// Center body is center sprite here
float hw = sprite.getWidth() / 2.0f;
float hh = sprite.getHeight() / 2.0f;
float a = body.getAngle() * MathUtils.radiansToDegrees;
float x = position.x - hw;
float y = position.y - hh;

sprite.setPosition(x, y);
sprite.setRotation(a);

```

The other approach is to keep track of an object that is the amalgamation of the `Sprite` and the `Body`;

```
public class MyGameObject {
  private Body body;
  private Sprite sprite;

  public void update() {
    Vector2 position = body.getPosition();
    // Center body is center sprite here
    float hw = sprite.getWidth() / 2.0f;
    float hh = sprite.getHeight() / 2.0f;
    float a = body.getAngle() * MathUtils.radiansToDegrees;
    float x = position.x - hw;
    float y = position.y - hh;

    sprite.setPosition(x, y);
    sprite.setRotation(a);
  }
}

```

I think it's largely a matter of preference, I prefer the **UserData** approach myself as I need to "manually" keep track of less things that way.
> 2 votes

# Answer
You can use the setUserData method to attach an Object to the box2D body (like for example a Sprite or an Actor):

```
body.setUserData(sprite);

```

Accordingly you can get your Sprite back like this:

```
(Sprite) body.getUserData();

```

Note that you need to cast to Sprite.
> 1 votes

---
Tags: java, libgdx, box2d
---


title: Transformations and basis vectors

text:
# Question
Title: Transformations and basis vectors
I've been reading this very nice tutorial on OpenGL, and I encountered a statement which I can't wrap my head around. In Chapter 6, it states:

> Transformation from one space to another ultimately means this: taking the basis vectors and origin point from the original coordinate system and re-expressing them relative to the destination coordinate system. The transformation matrix from one space to another contains the basis vectors and origin of the original coordinate system, but the values of those basis vectors and origin are relative to the destination coordinate system.

This is reaffirmed in Chapter 7:

> ... And this makes sense; a transformation matrix contains the basis vector and origin of the source space, as expressed in the destination coordinate system.

... But isn't it the other way around?

Take a look at this example from the tutorial:

The transformation Matrix to transform from the space on the left to the space on the right is

```
[1   0   0   1  ]
[0   1   0  -1.5]
[0   0   1   0  ]
[0   0   0   1  ]

```

The last column of the transformation matrix is the origin of the *destination* space, expressed relative to the *source* space.

What am I missing?

**Note** The above transformation matrix is not from the notes, so feel free to correct it.

# Answer
> The transformation Matrix to transform from the space on the left to the space on the right is

```
[1   0   0   1  ]
[0   1   0  -1.5]
[0   0   1   0  ]
[0   0   0   1  ]

```

Well this is not correct, the matrix you have shown is actually to transform any point from the space on the right to the space on the left. The correct matrix to transform from the space on the left to the right is actually

```
[1   0   0  -1  ]
[0   1   0  1.5 ]
[0   0   1   0  ]
[0   0   0   1  ]

```

Think about it like this. The `[0,0]` point on the left figure is actually `[-1,1.5]` **relative to the new space (right figure),** remember when you change a basis it's easier to think about it as actually transforming basis not the points, meaning you're actually representing the *same* points relative to a different basis.

Even though you can think of it the other way around, as of actually taking the inverse transform of the points, it's actually easier to think about it as transforming the basis, either way pick a convention and stick with it. You can also check my other answer, for better explanation of spaces.
> 1 votes

---
Tags: opengl, graphics, matrix, transformation
---


# Question
Title: How can I stop my collision detection from registering multiple times per frame?
I am working on a side-scroller shooter right now. Everything is working fine along with the collision detection however, my problem is that the collision triggers my health deduction code multiple times per bullet. Here is the code where the bullet hits a turret. Supposedly doing 5.0 damage but instead it randomly does a lot more damage since the collision runs multiple times with just one bullet. How could I prevent this?

```
void TurretCollision()
{
 int BulletNo = 0;
        int MissileNo = 0;

for (BulletNo = 0; BulletNo < MAX_BULLETS; BulletNo++)
{
    if (Turret[1] == true)
    {
        //cout << TurretH[1];
        if ((BulletX[BulletNo] >= 103 && BulletX[BulletNo] <= 103.09) && (BulletY[BulletNo] <= -38 && BulletY[BulletNo] >= -45))
        {
            BulletActive[BulletNo] = false;
            TurretTrial = TurretTrial - 5.0;

            if (TurretTrial <= 0.0)
            {
                Turret[1] = false;
            }
        }
    }

}

```

}

# Answer
Add a BulletCheck\[BulletNo\] == true condition.

```
if ((BulletX[BulletNo] >= 103 && BulletX[BulletNo] <= 103.09)
&& (BulletY[BulletNo] <= -38 && BulletY[BulletNo] >= -45 && BulletActive[BulletNo]) == true)
    {
        BulletActive[BulletNo] = false;
        TurretTrial = TurretTrial - 5.0;

        if (TurretTrial <= 0.0)
        {
            Turret[1] = false;
        }
    }

```
> 2 votes

---
Tags: c++, collision-detection
---


title: Rotate OpenGL quad around its center

text:
# Question
Title: Rotate OpenGL quad around its center
Sorry, I searched it but couldn't figure how to apply it to my code reading the other answers to similar questions. I what to rotate a quad, my code is the following:

```
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, player_texture);
glBegin(GL_QUADS);
    glColor4ub(255, 255, 255, 255);
    glTexCoord2d(0,0); glVertex2f(hero.xValue(), hero.yValue());
    glTexCoord2d(1,0); glVertex2f(hero.xValue()+hero.lValue(), hero.yValue());
    glTexCoord2d(1,1); glVertex2f(hero.xValue()+hero.lValue(), hero.yValue()+hero.hValue());
    glTexCoord2d(0,1); glVertex2f(hero.xValue(), hero.yValue()+hero.hValue());
glEnd();
glDisable(GL_TEXTURE_2D);

```

I'm not sure about how to use the glTranslatef function, I tell it what is the center of my object?

In that case it would be: *hero.xValue()+hero.lValue()/2* **(x)** and *hero.yValue()+hero.hValue()/2* **(y)**

I know I have to use both glTranslatef and glRotate, by the way. When I try, setting glTranslatef with the values I mentioned above, I get a texture floating far from where the hero actually is.

Any help on this matter will be appreciated, thank you.

Obs: hValue = height, lValue = lenght

Edit: New information to show the changes I made after @user55564's comment:

I call init() once, on there I set basic openGL and SDL stuff, among them:

```
glViewport(0, 0, WIDTH, HEIGHT);
glMatrixMode(GL_MODELVIEW);

```

then I call my draw function, it has in it:

```
while (running) {
    glLoadIdentity();

.
. stuff non-related to drawing
.

glClear(GL_COLOR_BUFFER_BIT);
    glClearColor(0, 0, 0, 0);
    glPushMatrix();
    glOrtho(0, WIDTH, HEIGHT, 0, -1, 1);

    // draws the player
    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, player_texture);
    glTranslatef(hero.xValue(), hero.yValue(), 0);
    glRotatef(0, 0, 0, 1);
    glTranslatef(-(hero.xValue()+hero.lValue()/2), -(hero.yValue()+hero.hValue()/2), 0);
    glBegin(GL_QUADS);
        glColor4ub(255, 255, 255, 255);
        glTexCoord2d(0,0); glVertex2f(hero.xValue(), hero.yValue());
        glTexCoord2d(1,0); glVertex2f(hero.xValue()+hero.lValue(), hero.yValue());
        glTexCoord2d(1,1); glVertex2f(hero.xValue()+hero.lValue(), hero.yValue()+hero.hValue());
        glTexCoord2d(0,1); glVertex2f(hero.xValue(), hero.yValue()+hero.hValue());
    glEnd();
    glDisable(GL_TEXTURE_2D);
    glPopMatrix();

// then I use pushmatrix again to draw the enemies and the health bars of both enemies and player (these don't need rotation);
glPushMatrix();
    glOrtho(0, WIDTH, HEIGHT, 0, -1, 1);
.
.
.

```

# Answer
> 3 votes
What you need to do to draw a quad with x,y as its top left coords, r as rotation, and cx and cy as the center of rotation (relative to its x,y coord) :

```
- translate(x,y)
- rotate(r)
- translate(cx, cy);
- draw.
- (reverse/pop the matrix if required. etc)

```

For your case, try this:

```
...
glTranslatef(hero.xValue(), hero.yValue(), 0);
glRotatef(0, 0, 0, 1);
glTranslatef(+hero.lValue()/2, +hero.hValue()/2);
glBegin(GL_QUADS);
    glColor4ub(255, 255, 255, 255);
    glTexCoord2d(0,0); glVertex2f(-hero.lValue()/2, -hero.hValue()/2);
    // do the same for other 3 corners.

glEnd();

```

After the transformations, your (0,0) coord is at where the object's center is. Suppose if object is at (50,50). In your function after the transformation the (0,0) is at (50,50) So if you draw at (50,50) again then in reality you are drawing your object at (100,100).

See http://creativejs.com/2012/01/day-10-drawing-rotated-images-into-canvas/ for more detailed explanation.

---
Tags: opengl, graphics
---


title: How to reverse gravity in Unity

text:
# Question
Title: How to reverse gravity in Unity
I'm trying to figure out how script gravity reversal on collision with an object. How can I reverse gravity?

# Answer
If it's 2D then you can simply use: `rigidbody2D.gravityScale = -1;`. You tagged the question `2D` so this should be all you need to do. To toggle isntead of simply set you can change it to `rigidbody2D.gravityScale *= -1;`

If it's 3D and you want the entire scene to have gravity reversed you can do: `Physics.gravity = new Vector3(0, -1.0F, 0);`

If it's 3D and you want only that single object to have its gravity reversed you'll have to manually do something like @SteakOverflow points out in his answer. I believe what you'll have to do is add a constant `rigidbody.AddForce` call in your `FixedUpdateFunction`.
> 5 votes

# Answer
You should try to disable the rigidbody's useGravity property when the collision happens and use AddForce to fake your upwards gravity, pretty much like the example in AddForce documentation.
> 2 votes

---
Tags: unity, 2d
---


# Question
Title: Specular banding with high specular power
We're having some issues with our ray tracing in DirectX, especially with some serious banding issues with specular. With high specular power (above 8) banding starts. I'm wondering if this is an HDR/LDR issue or could be related to something else, such as normals or other vectors?

# UPDATE

Look below for updates.

Here's the relevant shader code for Blinn-Phong on a sphere:

```
float3 hitPoint = thisRay.origin + thisRay.direction * bestHit.hitT;
float3 normal = normalize(hitPoint - spheres[bestHit.hitID].center);
float3 toLight = pointLights[0].position.xyz - hitPoint;
float d = length(toLight);
toLight = normalize(toLight);

float diffuse = max(dot(normal, toLight), 0.0f);

float3 v = normalize(thisRay.origin - hitPoint);
float3 h = normalize(v + toLight);

float spec = 0;
if (diffuse > 0)
    spec = pow(max(dot(normal, h), 0.0f), specPower) * diffuse;

output[threadID.xy] = spheres[bestHit.hitID].colour * diffuse + spheres[bestHit.hitID].specColour * spec;

```

specPower equals 8 in this image

specPower equals 9 in this image

Is this as simple as an HDR/LDR issue or is it somehow related to normal precision? I believe I have encountered this issue before in a deferred renderer where normals were of low precision and improperly packed/unpacked but in this case normals are generated on the fly and the whole thing is rendered directly to the backbuffer.

## Update 1

I would like to add to the above that triangles suffer the same artifact and they have their normal currently generated in the following way:

```
float3 normal = normalize(cross(triangles[bestHit.hitID].vertices[1] - triangles[bestHit.hitID].vertices[0],
                                    triangles[bestHit.hitID].vertices[2] - triangles[bestHit.hitID].vertices[0]));

```

I'd say this makes it even more unlikely that the normal of the surface is the problem. The following image shows what happens when specPower reaches 2048.

# Answer
Looks like an issue with the pow function implementation on this particular GPU.

When suspecting a bug in a math function replace the math function by its equivalent, for example replace:

```
spec = pow(max(dot(normal, h), 0.0f), specPower) * diffuse;

```

With the bug showing up at specPower=9.0, hard-code it to

```
float temp = max(dot(normal, h), 0.0f);
spec = pow(temp, 8.0) * temp * diffuse;

```

Or

```
float temp = max(dot(normal, h), 0.0f);
spec = temp * temp * temp * temp * temp * temp * temp * temp * temp * diffuse;

```

If the issue goes away this means there's probably an underflow bug in the pow function regarding the exponent on this GPU or driver.

What you can do as a work around, **assuming** the fragment shader calculation is done internally with 16bit floats. If I calculate this right you should do

```
pow(max(temp, (Nth root of (1.0/16384.0))), N);

```

It could be 32768 or 8192: I might be off by one bit or the GPU might be using more or less precision. for pow(x, 9.0) the clamping would be pow(max(temp, 0.3401975), 9.0) Values of X below this would underflow the exponent range (+15 to -14) of IEEE 16bit floating points (again, I'm assuming this is what the GPU uses.)

from rosetta code ( http://rosettacode.org/wiki/Nth\_root#C.2B.2B )

```
double NthRoot(double value, double degree)
{
    return pow(value, (double)(1 / degree));
};

my_shader->SetUniform("specular_minimum", NthRoot((1.0/16384.0), specPower));

```

You'll have to calculate this on the CPU and feed the value in a uniform: the GPU will probably have the same precision issue if you calculate this right in the shader.

If you can confirm this, try contacting the GPU driver team with a sample shader source code that replicate the issue give them the exact driver version, OS, and GPU model revision, an executable might help but don't send it as your email will get trapped in the virus/spam checker. Just build one and keep a copy in case they ask for a pre-built sample executable. As a courtesy, give them a chance to fix it before naming it publicly. It could simply be an optimization bug in their shader compiler that only happen with your particular shader. It might take a while (months) to get in contact with them, these guys are often understaffed.
> 1 votes

---
Tags: normals, raytracing, hdr, shading
---


# Question
Title: Render-to-texture doesn't work on nvidia cards. OpenGL 3.3
I've implemented some postprocessing effects (DOF, HDR, Bloom) into my engine. I've tested it on AMD card which supports OpenGL 4.2. Yesterday I've made a test on NVidia card which supports only OpenGL 3.3. I tried to write my code to works also in OpenGL 3.3 but I was suprised when I saw something like on the screen:

It seems that textures are filled with random values and never change during app life (only when I'm changing dimensions of textures so basically recreate them). It happens mostly when I want downscale texture to some size (I use 2 textures to do that and a shader). Here is some examples of my code which implements Bloom effect:

Creating framebuffer:

```
if (!_p_buffer)glGenFramebuffers(1, &_p_buffer); // generate postprocess buffer
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, _p_buffer);

    for (int i = 0; i < 2; i++){
        _lens[i].create(x / D.lensDownsample(), y / D.lensDownsample(), 0, IMAGE_16F_3, IMAGE_2D, true, FILTER_LINEAR); // create Lens Flare texture (with half resolution)
        glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT2 + i, GL_TEXTURE_2D, _lens[i].get(), 0);
    }

```

Render-to-texture:

```
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, _p_buffer);

// first downsample image
glDrawBuffer(GL_COLOR_ATTACHMENT2);
glClear(GL_COLOR_BUFFER_BIT);

glActiveTexture(GL_TEXTURE0);
_aux[_aux_number].lock();

Shaders["ScaleBias"].set(true);
Shaders["ScaleBias"].set("scale", Vector4(1.2f));
Shaders["ScaleBias"].set("bias", Vector4(-0.4));
Shaders["ScaleBias"].set("texelSize", Vector2(1 / (float)D.x() * D.lensDownsample(), 1 / (float)D.y() * (float)D.lensDownsample()));

glViewport(0, 0, D.x() / D.lensDownsample(), D.y() / D.lensDownsample());
Quad();

```

ScaleBias shader:

```
void main() {
    FragColor = max(vec4(0.0), texture(col, gl_FragCoord.xy*texelSize) + bias) * scale;
}

```

What "create" method actually does here:

```
if(!_image)glGenTextures(1, &_image);

glBindTexture(GL_TEXTURE_2D, _image);

glTexParameteri(_gl_target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(_gl_target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(_gl_target, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glTexParameteri(_gl_target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(_gl_target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, x, y, 0, GL_RGB,GL_FLOAT, NULL);

```

I used debug extension to check if there is any invalid parameters but debuging shows nothing interesting. I tried make G-Buffer textures as GL\_FLOAT but they works ok. I tried make shader as simple as possible (return color texture) but error still was valid. I've observed similar problem on newer NVidia cards but the only difference was that textures are clear (black). But they still didn't update. Framebuffer doesn't output any errors.

Could you point me out the cause of this bug or give some clue?

# Answer
> 3 votes
There isn't much info to go on so I'm going to throw out a few things to try and see if the driver/card likes it better that way:

RGBA instead of RGB

```
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, x, y, 0, GL_RGBA, GL_FLOAT, NULL);

```

Check that GL\_MAX\_COLOR\_ATTACHMENTS is 4 or more on this graphic card (GL\_COLOR\_ATTACHMENT2 + 1 == 4th color attachment)

Try attaching starting at GL\_COLOR\_ATTACHMENT0

try different locations for FragColor (does it matches GL\_COLOR\_ATTACHMENTn ?)

```
layout(location = 2) out vec4 FragColor;

```

Did you unbind the texture before trying to render to it?

```
glBindTexture(GL_TEXTURE_2D, 0);

```

Cheers,

# Answer
> 0 votes
Thank you Stephane for your answer. It helped me find the real problem source. I'll explain it in this answer and will provide short answers to your post. Maybe it will be useful for someone.

My AMD card is Radeon HD5770 (supporting OpenGL 4.2) and my NVidia card GeForce 9500GT (supporting OpenGL 3.3). Both cards support max 8 color attachments.

> try different locations for `FragColor` (does it matches `GL_COLOR_ATTACHMENTn` ?)
>
> ```
> layout(location = 2) out vec4 FragColor;
>
> ```

I played with `glBindFragDataLocation` function, because I had to dynamically change output location (for example when blurring I had 2 passes - one for vertical and one for horizontal blur - and 2 color attachements used).

I observed that I didn't need to set location — OpenGL draws to the color attachment set in `glDrawBuffer()` without any extra hints.

---

# Solution

I stored all textures used in postprocessing in one framebuffer. These textures have different dimensions. The smallest texture has size 1x1. I've found text which could explain why I had these artifacts:

> When you use more than one buffer, some restrictions apply: All attachments to the FBO must have the same width and height. All color buffers must use the same format. For example, you cannot attach a RGBA8 and a RGBA16f Texture to the same FBO, even if they have the same width and height. OpenGL 3.0 does relax this restriction, by allowing attachments of different sizes to be attached. But only the smallest area covered by all attachments can be written to.

So possibly only one pixel was changing and newer versions of OpenGL seem to have removed this restriction, since it works on my AMD card.

So to solve my problem, I simply created separate framebuffers for each postprocess effect. And it works!

---
Tags: opengl, rendertargets, nvidia, frame-buffer
---


# Question
Title: How do I handle rope physics with fixed ends and a sliding weight?
I've been interested in rope physics recently—I've successfully implemented a simple Verlet rope with moveable ends. Now I am trying something a little different: I want to start by recreating the mechanic from the game *Sky Tourist* (video here):

I assume *Sky Tourist* uses Verlet integration for its rope, but it also has the main character sliding along the rope as a moving weight. How can I recreate that?

Is it just done by applying different gravity to where the character is? Also, how is the collision detection handled between the character and the rope? If the game uses a physics engine like Box2D, how does it make it play nice with the rope, considering it's not a part of the Box2d world?

# Answer
> 1 votes
Assuming the rope has no weight, this problem is about finding the lowest point of an ellipse (http://en.wikipedia.org/wiki/Ellipse ) where (PF1+PF2 == rope length)

This image show how the ellipse is rotated.

From there you can figure out the lowest point by tracing the ellipse with a binary search to find the lowest point. That's where the weight should end up, move the weight toward its target with the usual inertia smoothing.

calculate how the drawn rope is going to stretch and pull to accomodate the weights' inertia and you can add some bouncyness.

Add a little bezier sagging to the drawn ropes for realism and you're done.

Cheers,

---
Tags: c++, 2d, box2d, cocos2d-x, rope-physics
---


# Question
Title: Blank texture in Frame Buffer Object in Deferred Rendering
I'm running the tutorial 35 from olgdev.atspace.co.uk, and it's so strange that the result is a blank screen. This tutorial is performing the first step of Deferred Shading, which means decoupling of geometry calculations and lighting calclation. This process includes following steps.

2. Bouding logical texture to Frame Buffer Object
3. Rendering 1: Only writing vertex attributes to such textures.
4. Rendering 2: Copy data from such textures, which included inside Frame Buffer Object onto the screen.

At the first step, I bound the texture to the Frame Buffer Object as following:

```
    // Create the FBO
glGenFramebuffers(1, &m_fbo);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fbo);

// Create the buffer textures
glGenTextures(ARRAY_SIZE_IN_ELEMENTS(m_textures), m_textures);
glGenTextures(1, &m_depthTexture);
//Set up texture format and bound to FBO
for (unsigned int i = 0 ; i < ARRAY_SIZE_IN_ELEMENTS(m_textures) ; i++) {
    glBindTexture(GL_TEXTURE_2D, m_textures[i]);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F, WindowWidth, WindowHeight, 0, GL_RGB, GL_FLOAT, NULL);
    glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, m_textures[i], 0);
}

// depth
glBindTexture(GL_TEXTURE_2D, m_depthTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32F, WindowWidth, WindowHeight, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, m_depthTexture, 0);

GLenum DrawBuffers[] = { GL_COLOR_ATTACHMENT0,
                         GL_COLOR_ATTACHMENT1,
                         GL_COLOR_ATTACHMENT2,
                         GL_COLOR_ATTACHMENT3 };
//Set such textures as the output receiver from Fragment Shader
glDrawBuffers(ARRAY_SIZE_IN_ELEMENTS(DrawBuffers), DrawBuffers);

```

The next is rendering processing, including two main steps.

```
virtual void RenderSceneCB()
{
    m_pGameCamera->OnRender();

    DSGeometryPass(); //The first step ==> Only write vertex attributes to logical texture
    DSLightPass(); //The second: copy data from such textures to the screen.

    RenderFPS();

    glutSwapBuffers();
}

```

At the first step, the fragment shader only pass on vertex attributes to the logical texture, which before bound to the Frame Buffer Object. This is the rendering code

```
void DSGeometryPass()
{
    m_DSGeomPassTech.Enable();

    m_gbuffer.BindForWriting();

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    Pipeline p;
    p.Scale(0.1f, 0.1f, 0.1f);
    p.Rotate(0.0f, m_scale, 0.0f);
    p.WorldPos(-0.8f, -1.0f, 12.0f);
    p.SetCamera(m_pGameCamera->GetPos(), m_pGameCamera->GetTarget(), m_pGameCamera->GetUp());
    p.SetPerspectiveProj(m_persProjInfo);
    m_DSGeomPassTech.SetWVP(p.GetWVPTrans());
    m_DSGeomPassTech.SetWorldMatrix(p.GetWorldTrans());
    m_mesh.Render();
}

```

And this is the shader code

```
struct FSOutput  //Fragment shader
{
    vec3 WorldSpacePos;    //which will be copied to position texture.
    vec3 Diffuse;          //which will be copied to diffuse texture.
    vec3 Normal;           //which will be copied to normal texture.
    vec3 TexCoord;         //which will be copied to texCoord texture.
};
shader FSmain(in VSOutput FSin, out FSOutput FSout)
{
    FSout.WorldSpacePos = FSin.WorldSpacePos;
    FSout.Diffuse      = texture(gColorMap, FSin.TexCoord).xyz;
    FSout.Normal       = normalize(FSin.Normal);
    FSout.TexCoord     = vec3(FSin.TexCoord, 0.0);
};

```

Therefore, the results we got from Fragment Shader are four textures, which is then copied onto the screen and should be seen as following
<sub>(source: atspace.co.uk)</sub>

However,the screen is going to blank. I used gDeDebugger for finding the values of such fours textures after Fragment Shader performed, and it shows that all of thems is blank. blank texture http://s10.postimg.org/y2dwd2h1j/texture.png My question is why the Fragment shader pass a blank input to the four textures? I hope to see your answer. Many Thanks!

# Answer
> 1 votes
Check if you have mipmaps enabled on the texture samplers ( GL\_LINEAR\_MIPMAP\_LINEAR, etc ).

If the texture is incomplete (only 1 mipmap level is rendered to by the FBO at a time) and mipmaps are enabled on the sampler you'll get white textures.

* Switch to GL\_LINEAR or GL\_NEAREST
* set GL\_TEXTURE\_MAX\_LEVEL to 0 so it only use the first mipmap (same as no mipmapping)
* or call glGenerateMipmap after calling glBindTexture.

---
Tags: opengl, glsl, deferred-rendering, deferred-shading
---


# Question
Title: Deferred rendering and gaussian blur - artifacts
I compute Gaussian blur in two passes (horizontally and vertically). Shaders look like this:

Horizontal blur - fragment shader:

```
#version 420
layout (location = 0) out vec4 outColor;
in vec2 texCoord;
float PixOffset[5] = float[](0.0,1.0,2.0,3.0,4.0);
float Weight[5] = float[]( 0.2270270270, 0.1945945946, 0.1216216216, 0.0540540541, 0.0162162162 );
float scale = 4.0;

uniform sampler2D texture0;
uniform vec2 screenSize;

void main(void)
{
    float dx = 1.0 / screenSize.x;
    vec4 sum = texture(texture0, texCoord) * Weight[0];
    for( int i = 1; i < 5; i++ )
    {
        sum += texture(texture0, texCoord  + vec2(PixOffset[i], 0.0) * scale * dx ) * Weight[i];
        sum += texture(texture0, texCoord - vec2(PixOffset[i], 0.0) * scale * dx ) * Weight[i];
    }
    outColor = sum;
}

```

I use deferred rendering and the following screens shows a diffuse material texture after blurring. I simplified a render loop for the sake of clarity(only one render target - a diffuse material).

A render loop - first case:

* bind fbo1
* gbuffer stage
* unbind fbo1
* bind fbo2
* read a diffuse texture, render to a temporary texture (full screen quad)
* read a temporary texture, horizontal blur, render to a temporary texture (full screen quad)
* read a temporary texture, vertical blur, render to a temporary texture (full screen quad)
* unbind fbo2
* read a temporary texture, render to the default framebuffer (full screen quad)

The final image has artifacts(flickering pixels). Some of them are placed between two triangles which create the full screen quad.

A render loop - second case:

* bind fbo1
* gbuffer stage
* unbind fbo1
* bind fbo2
* read a diffuse texture, render to a temporary texture (full screen quad)
* read a temporary texture, horizontal blur, render to a temporary texture (full screen quad)
* unbind fbo2
* read a temporary texture, vertical blur, render to the default framebuffer (full screen quad)

Some artifacts may appear between triangles:

A render loop - third case:

* bind fbo1
* gbuffer stage
* unbind fbo1
* bind fbo2
* read a diffuse texture, horizontal blur, render to a temporary texture (full screen quad)
* unbind fbo2
* read a temporary texture, vertical blur, render to the default framebuffer (full screen quad)

The final image doesn't contain artifacts.

How to fix that ? The above code is simplified but normally the first case(render loop order) is most useful, for example: I want to blur a glow texture and use it when shading.

# Answer
> 2 votes
This is probably the issue: https://www.opengl.org/wiki/Framebuffer\_Object#Feedback\_Loops

Using a texture that is currently bound to an FBO that is current bound as the rendering target is undefined.

You must unbind the FBO before using the texture. You can leave the texture bound to the FBO so long as the FBO itself is unbound. You need to bind a 2nd FBO with a 2nd temporary texture to do the vertical blur step.

The GPU is, in parallel, starting to reading old texture data while its still rendering to the FBO and/or the FBO result is still in the GPU render cache and hasn't yet been flushed to texture memory and the texture render cache contains old data.

Unbinding the FBO tells the GPU to finish and commit all its cached data to texture memory and invalidate the old texture sampling cache before starting to render the next step and properly sample the new texture data.

Cheers,

---
Tags: opengl, deferred-rendering, post-processing
---


# Question
Title: Failing to move exponential depth term to depth shader in exponential shadow mapping
I'm playing around in my little toy project to see if I can understand how exponential shadow mapping works. To begin, I have the following two fragment shaders:

### Light depth texture shader

```
layout(location = 0) out float fragmentdepth;

void main(){
  fragmentdepth = gl_FragCoord.z;
}

```

### Main shader

```
...
vec3 shadowDiv = shadowCoords.xyz / shadowCoords.w;
float lightDepth = texture(depthMap, shadowDiv.xy);
float visibility = clamp(exp(-70 * shadowDiv.z) * exp(70 * lightDepth), 0, 1);
...

```

This works fine - I have shadows where I expect them, and I'm using the approximation to the boolean function by taking the product of exponentials, as shown in the ESM paper.

However, my understanding is that the whole point of this, is that I can move `exp(70 * lightDepth)` out of this shader, and into the shader when I generate the depth texture at the light. That is:

### New light depth texture shader

```
layout(location = 0) out float fragmentdepth;

void main(){
  fragmentdepth = exp(70 * gl_FragCoord.z);
}

```

### Main shader

```
...
vec3 shadowDiv = shadowCoords.xyz / shadowCoords.w;
float lightDepth = texture(depthMap, shadowDiv.xy);
float visibility = clamp(exp(-70 * shadowDiv.z) * lightDepth, 0, 1);
...

```

When I make this change, the entire scene becomes shadowed. I'm sure I'm misunderstanding something somewhere, but I'm not sure where. I have tried varying the constant term (70) between 1 and 70, though this doesn't appear to make a difference. I have no errors reported by `KHR_debug`

I am creating my light depth texture as:

```
genLightDepthMap :: IO GLTextureObject
genLightDepthMap =
  do lightDepthMap <- overPtr (glGenTextures 1)
     glBindTexture GL_TEXTURE_2D lightDepthMap
     glTexParameteri GL_TEXTURE_2D GL_TEXTURE_MIN_FILTER GL_LINEAR
     glTexParameteri GL_TEXTURE_2D GL_TEXTURE_MAG_FILTER GL_LINEAR
     glTexParameteri GL_TEXTURE_2D GL_TEXTURE_WRAP_S GL_CLAMP_TO_EDGE
     glTexParameteri GL_TEXTURE_2D GL_TEXTURE_WRAP_T GL_CLAMP_TO_EDGE
     glTexImage2D GL_TEXTURE_2D
                  0
                  GL_DEPTH_COMPONENT24
                  shadowMapResolution
                  shadowMapResolution
                  0
                  GL_DEPTH_COMPONENT
                  GL_FLOAT
                  nullPtr

```

# Answer
> 1 votes
You are using GL\_DEPTH\_COMPONENT24 which is a fixed-point format clamped to the range \[0, 1\] inclusively.

The floating point formats are GL\_DEPTH\_COMPONENT32F and DEPTH32F\_STENCIL8.

```
 glTexImage2D GL_TEXTURE_2D
              0
              GL_DEPTH_COMPONENT32F
              shadowMapResolution
              shadowMapResolution
              0
              GL_DEPTH_COMPONENT
              GL_FLOAT
              nullPtr

```

You also need to call glDepthRange(-1, 1); to disable scaling & offsetting of the depth values.

It is unclear if you can call glClearDepth(INFINITY) or need to clear the depth using a full-screen quad as the ARB\_depth\_buffer\_float extension says *"ClearDepth takes a floating-point value that is clamped to the range\[0, 1\]."*

I don't know how supported it would be to clear the depth with a quad at depth near-infinity regarding clipping against the far plane: The clipping calculation might go nuts with rounding errors.

Your best bet is to draw a fullscreen quad at a reasonable depth (1.0) with depth-test disabled and FORCE the depth at INFINITY (or a very large non-infinity value) in the pixel shader so this will happen after primitive clipping.

Cheers,

---
Tags: opengl, glsl, shadow-mapping
---


title: Transparency behaviour on PowerVR

text:
# Question
Title: Transparency behaviour on PowerVR
I'm doing some graphics optimizing tests, especially on PowerVR transparency. Now I made a scene where there are two groups of simple objects. One group has the shape in geometry using **diffuse** shader and the other with quads using **transparency** shader. The camera looks through a plane towards a group.

The test was about the "lateness" of PowerVR's Z-tests. And whether or not use better geometry instead of transparencies for e.g leaves or flowers.

The results were not wholly what I expected. The transparency group benefitted from changing the plane from transparent to diffuse by increasing the FPS by 20(***expected***).

But why is the group without the plane infront so much faster than when the plane is in front?(***Not expected***) FPS was 38, screenshotting lowered it.

Tests on the geometry group were opposite of what I had learnt in the past few days. There was only 2FPS difference between transparent and diffuse planes. (***Not expected***). Shouldn't the transparent plane infront cause the whole scene to render as the Z-test is at the bottom of the pipeline?

# Answer
Because the plane in front is alpha-blended over the entire screen, after all the alpha leaves behind it have been drawn as objects they are depth-sorted by Unity to render properly with alpha-blending.

In your test without the front plane the cost of blending is minimal as all of the leaves use the same shader and texture which are in the cache and only cover a small part of the screen.

If you were to render each row with a different texture and different shader, performance would suffer much more.

Alpha blending tiny parts of the screen using the same texture does not affect performance much until you are not bound by the memory bottleneck.

The PowerVR gpu has some free time to wait while deferred tiles are being written to memory: it can't send another tile to memory while the first one hasn't been written. And since the texture is already in the cache it does not need to access memory for texture fetches letting it do the blending in parallel on the next tile while the memory is busy receiving the previously finished tile.
> 1 votes

---
Tags: shaders, rendering, gpu, transparency, pipeline
---


# Question
Title: How can I reverse the effect of a transformation matrix?
I have recently been working on a game with using OpenGL and C++ through GLFW.

In the game I have an airship with a turret mounted on it. The airship moves around in world space coordinates and the turret 'follows' it.

The turret has it's own coordinate space for its look/aim direction. Basically, when the turret aims in direction `(0,0,1)`, it aims parallel to the airships direction of movement.

To give the turret a world space target, I have a matrix that takes world space coordinates and transforms these to turret space coordinates.

As the turret fires, I want it to spawn projectiles in world space, so is there an elegant way of using my transformation matrix to convert turret space coordinates back to world space?

A more general way of asking the question might be: if I have a matrix `M` that takes coordinates from space `A` to space `B`. Is there an easy way to use `M` to get the coordinates from `B` to `A`?

# Answer
> 21 votes
So long as the matrix `M` is invertible (which it generally will be, unless you're doing something very unusual), then computing the matrix inverse of `M` will give you a matrix that does what you want.

That is, if `M` performs some transformation, `inverse(M)` performs the "opposite" transformation.

Most matrix/vector libraries provide a means for computing the inverse.

# Answer
> 5 votes
If your transformation matrix is a rotation matrix then you can simplify the problem by taking advantage of the fact that the inverse of a rotation matrix is the transpose of that matrix.

If your transformation matrix represents a rotation followed by a translation, then treat the components separately. The inverse is equivalent to subtracting the translation and then applying the transpose of the rotation matrix.

# Answer
> 2 votes
In your matrix lib there is probably a function called inverse. That is probably what you are looking for.

---
Tags: matrix, linear-algebra
---


# Question
Title: OpenGL ES Single Bitplane Texture (or something close)
I'm looking to use a texture to store single bits (or a low number of bits, two or three). This in of itself isn't hard if you're using nearest neighbor sampling with some bit plane unpacking. The kicker here is I need the values to abide to bilinear interpolation (or something that looks like interpolation), and manually emulating bilinear interpolation is rather slow and potentially prone to problems due to hardware differences.

This is an instance where I'm going to have a lot of similarly-sized textures. The best thing I've come up with is using a 4 x 4-bit channel texture and storing a texture in each channel. This isn't exactly great for texture cache, but it's near native-hardware supported. Unfortunately, this also requires four times the space (4 bits instead of 1 bit per texel) assuming the number of textures I have to store is divisible by 4.

Is there a better way to store 1 bit per texel? Or even 2 bits per texel?

# Answer
> 1 votes
You could use compressed textures to store your 1bpp image, they can all store 1bpp images without loss as each tiles can have 2 colors (and in-betweens).

PVRTC supports a 2bpp format, PVRTC is only supported on PowerVR devices.

ETC1 and S3TC (DXT1) are 4bpp which comes back to the same size as 4x4 in RGBA4444 format but you don't need to combine and then separate them, makes the shader code simpler and faster.

ASTC supports down to 0.89bpp, including 2bpp. (ARM Mali GPUs)

But there isn't 1 single compressed format that is usable on all GPUs (ETC2 is standard on OpenGL ES 3.0, not 2.0).

If all you're compressing are 1 bit textures (rather than full blown RGBA8888) its really easy to write a fast texture compressor function as all of those compression formats use a table of colors per cells and the hard part is always figuring out which colors to pick but since you only have 2 colors its really easy and fast.

You'll have to write one function per format so you can check what the OpenGL ES implementation supports and then convert to that format at loading time.

---
Tags: textures, shaders, opengl-es
---


# Question
Title: How can I make sure my game runs on older GPUs than mine?
My game must stay at 75fps to be playable (I'm developing for the Oculus Rift) and I'm optimizing with that hardware in mind.

My mid-range Nvidia GTX 650 Ti struggles a little with some Rift demos, but most do OK at medium-low graphics settings. I believe it's a reasonable optimization target if I want to enable more people to play my game.

Now, I've acquired a better-performing GTX 970, but I'd like to still optimize for older hardware. I don't want to be spoiled by my current better performance and develop something that could run only on high-end cards. In a few days, I won't have my old card available to me anymore.

While developing, how can I test if my game still runs at acceptable frame rate on older GPUs?

---

What I have in mind is to benchmark my GTX 650 now with some software, then underclock my GTX 970 until I get to the older card benchmark score. Is that a good approach? Would it effectively have the same performance?

If yes, what about memory and shader clocks? How can I objectively benchmark them separately?

(If relevant, I'm using Unity and Unreal Engine 4.)

# Answer
There is literally no good option other than testing on a range of target hardware.

Simply testing on slower hardware isn't enough. Older cards are often on different driver series, meaning that they support a lower version of Direct3D or OpenGL.

Cards of similar speeds but from different manufacturers will have different behavior. The behavior can differ because of loose specifications of semantics in the D3D or GL specs allowing vendors to do things differently, because of the vendor added some enabled-by-default extensions, or because of plain conformance bugs. For example, it's common to write GLSL code that works on an NVIDIA card but fails on Intel or AMD hardware because the GLSL code doesn't actually conform to the GLSL spec but which NVIDIA's drivers accept anyway.

Even aside from the hardware, there's various configurations to test. Users don't always install the latest drivers; the NVIDIA 34x drivers are different in key ways from the 30x legacy drivers. Users don't always have exact same version of the OS that you do, and software that works well in Windows 8 might perform poorly or not even run on Windows 7.

The only - *only* \- reliable way to ensure that your game runs well on target machines is to actually test it on them.

If you can't test it yourself, you're going to have to rely on getting others to help test it for you with pre-alpha nightly builds or the like. Plenty of hip indie games do that stuff these days.

A poor man's option you *might* have available would be the discrete GPU in your CPU. Most recent processors from either Intel or AMD have an integrated GPU. It might take some shenanigans (rebooting, changing BIOS settings, and moving monitor cables) to use. Some of the newer systems make it easier and can do the swap in software (maybe only under a VM or the like). Beware that even then, you're only testing your integrated GPU and not all the others you might want to stay compatible with. Just because it runs on your desktop's Haswell Intel GPU doesn't mean it'll run on a customers's older A10 AMD APU or mobile Sandy Bridge Intel GPU.

Short version: you have to test on the target machines to get meaningful feedback on compatibility.
> 5 votes

# Answer
If you want to stick with the hardware route, you may want to invest into a Dual-PCI motherboard specifically for this scenario. In my previous setup I had a GTX970 and an older GT640. Switching between GPUs will require you to reboot, go into BIOS and select a primary.

I've since dumped the 640 in favor of the built-in HD4400 in my i7 4770K. Check your CPU which may have an integrated GPU, it will be even a better representation of a low-end GPU than a dedicated GPU like the 650.
> 3 votes

---
Tags: optimization, frame-rate, gpu, testing, hardware
---


# Question
Title: Entity/Component System - Unique Behaviour
So, I decided to see what the Entity/Component system of game development was all about. I really liked it. So, I decided to implement my current game with it.

My problem: Unique Behaviour with the system. From what I have seen, the way to implement Unique Behaviour for a entity is to Create a unique Component, and a Unique System that only accepts Entities with that Component. This seems to be a lot of code, for what could be a very small feature.

My Solution: Have entities with "hooks" in them, so that they can define their own unique behaviour in them. They would still have the major things done for them by systems, such as Health, Rendering, and Movement.

e.g.:

```
public abstract class EntityLiving extends Entity{

    /**
     * Called when a entity is spawned in
     * @param map
     */
    public void onSpawn(Map map) {this.map = map;}

    /**
     * Called when an entity is killed
     * @param map
     */
    public void onDeath(Map map) {}

```

My Question: Is this bad programming practice? Could this be done in a 'better' way? I realize that this question is extremely subjective, but I would like some professional opinions.

EDIT: By better I mean, in order of priority:

1. Less Code for this scenario
2. Code Reusability
3. Code Efficency

# Answer
Entity/Component systems do allow for unique behavior. This will depend on how you design your components. Components contain data, and systems can change how they process components based on that data. There's no best practice when it comes to designing these things. It's going to depend on the requirements for your game and very much on your coding style and personal preference.

In an extreme example of unique behavior, you could have a component that simply contains some kind of script. The system for that component would read and execute that script. Since the script is contained in the data, it can be different for every entity that has that component. This is an extreme example because you could essentially implement your entire game just using that one component and system. But for usability's sake, you'd want to expand that into slightly more specific use cases.

For example, you could have a Spawn component that defines a limited set of spawn behaviors and the system will simply enumerate the options and perform the defined actions. You have lots of flexibility when it comes to creating components and systems. I'm sure you can think of numerous ways to create a component or system that doesn't require you to create a new component and system for each behavior you'd like.
> 2 votes

# Answer
I would normally just recommend avoiding an ECS and using a more flexible component model that isn't as constraining or filled with as much boilerplate. You can totally put polymorphic logic into an ECS, though, without altering the ECS design itself.

One possible approach is to create a `LogicComponent` and corresponding `LogicSystem`. This component's data would be an owned pointer to a polymorphic `ILogicBehavior` interface class or the like. The system iterates the components and invokes an `OnTick` virtual member function. Your data for game objects would describe which `ILogicBehavior` sub-class to actually load and instantiate and deserialize into, just like with other components.

The behaviors can still be allocated in a pool. The `LogicSystem` can sort components by their behavior's concrete type, giving you most of the same CPU cache access pattern advantages as a pure ECS.

Because it's only `LogicComponent` types that have a behavior that needs the `OnTick` function called you avoid the overhead of more naive component-based architectures that invoke such a function for every single active component in the game. With the `LogicSystem` approach, you don't need to make any changes to your other components or systems or core ECS architecture at all.

This approach is roughly equivalent in terms of object composition flexibility as a `ScriptComponent` and related system, which you might have as well. The script execution system will certainly be no more efficient than the logic component/system I just described (even if you go the naive implementation route) and will likely be far, far less efficient; you're still coming out ahead by having native-code polymorphic logic components than you are by shoving game logic out into scripts.
> 1 votes

---
Tags: libgdx, entity-system
---


# Question
Title: Camera bounds grow along with the game scene editor in Unity
I am extremely confused by the Unity editor. Look:

I have an image,

And I want my camera to fit it perfectly. I have achieved so by using a `size` property of `540`:

Notice how the viewport rect has 1 width and 1 height. If you run this game in a Samsung Galaxy S5, the sprite will fit perfectly in your device.

Now, **resize** the game scene view a bit (drag the Unity window border outwards to make it grow). Let's make it bigger. Then this happens:

The camera "white bounds" grew bigger! And the sprite no longer fits perfectly in the Galaxy S5!

My question is, then: **why did the camera's bounds grow along with the editor window, if the viewport rect property never changed (it is still at 1 width an 1 height)?**

# Answer
The ViewportRect properties are relative to the screen size. X, Y is a screen relative position to place the bottom-left corner of the camera view, and W, H is how big the camera view should be relative to the screen.

When you resize the game view, you are changing the size of the game screen, and the camera bound in the scene view adjust themselves to match.

You can set the game screen to a predefined resolution by hitting this button:

and selecting the desired resolution (like 1920x1080):

If your game view size is not the same size as the set resolution, it will downscale to fit, but will not affect your camera in your scene view.
> 0 votes

---
Tags: unity
---


# Question
Title: Why isn't my aspect ratio calculation working on Android platforms?
I have this method:

```
public final float aspectRatioHeight(float originalW, float originalH)
{
    float newHeight = (originalH / originalW) * (Gdx.graphics.getWidth()-20);
    return newHeight;
}

```

To calculate my an aspect ratio for the height of a sprite, but when i try run the app on an android device, the height still stretches out the app.

This is what im doing to set the size.

```
splashSprite.setSize(Gdx.graphics.getWidth() - 20, aspectRatioHeight(SW, SH) - 20);

```

# Answer
The problem is that there's two aspect ratios to take into account. You have the aspect ratio of the screen with you're calculating in the aspectRatioHeight method, but there's also the aspect ratio of the image.

Consider a image that is **100x100** pixels, and you want to place that with a **10**px margin on a screen that is **640x480**. If you set the width of the sprite to **640-10-10=620**px, what should the height be? What you're trying to do is to scale the sprite's height by the aspect ratio of the screen, which is this case is **480/640=0.75**, but as the image is **100x100** and therefore has an apsect ratio of **1** that will skew it.

If you have a source image with an aspect ratio different that the target viewport you will have to accept one of these compromises;

* Skew the image (but you don't want that)
* Letter box the image, i.e pad the top/bottom or left/right with something (this happens when watching wide screen movies on a 4/3 TV, sometimes).
* Stretch the image, by stretching you don't get the padding of letter boxing, but you'll miss some of the image as it stretches beyond the visible viewport.
> 1 votes

---
Tags: java, libgdx
---


# Question
Title: translate-scroll repeated 2d texture using opengl shader
I managed to implement an infinite 2d texture scrolling using the following shader. btw I'm using cocos2d-x 2.2.1.

The vertex shader:

```
attribute vec4 a_position;
attribute vec2 a_texCoord;

#ifdef GL_ES
varying mediump vec2 v_texCoord;
#else
varying vec2 v_texCoord;
#endif

void main()
{
    gl_Position = CC_MVPMatrix * a_position;
    v_texCoord = a_texCoord;
}

```

The fragment shader:

```
#ifdef GL_ES
precision lowp float;
#endif

uniform vec2 u_time;
uniform vec4 u_color;
varying vec2 v_texCoord;
uniform sampler2D CC_Texture0;

void main()
{
        gl_FragColor = texture2D(CC_Texture0, v_texCoord + u_time);
}

```

But once I try to add some uniform color the texture is no more repeated correctly (and performance decreases drastically):

```
/// Texture not repeated correctly and performance degradation
gl_FragColor = texture2D(CC_Texture0, v_texCoord + u_time) * u_color;

```

However the following repeat the texture correctly (but of course there's no scrolling)

```
gl_FragColor =  texture2D(CC_Texture0, v_texCoord) * u_color;

```

What am I doing wrong?

# Answer
I solved the problem by updating the texture coordinate in the vertex shader.

```
attribute vec4 a_position;
attribute vec2 a_texCoord;

uniform vec2 u_time;

#ifdef GL_ES
varying mediump vec2 v_texCoord;
#else
varying vec2 v_texCoord;
#endif

void main()
{
    gl_Position = CC_MVPMatrix * a_position;
    v_texCoord = a_texCoord + u_time;
}

```

Although it ran correctly on Android, updating the texture coordinate in the fragment shader didn't work on iOS.
> 0 votes

# Answer
The problem is probably:

```
precision lowp float;

```

Which causes u\_time to be 8bit unsigned fixed points with a range of only 0 to 1 or -2 to 2.

setting it to mediump would probably fix the scrolling issue but would still degrade performance greatly.

```
uniform mediump vec2 u_time;
uniform lowp vec4 u_color;

```

It's better to calculate UV coordinates in the vertex shader anyway as calculating them in the pixel shader prevents texture prefetching at the interpolation stage and stalls the GPU while it waits for the texture data in the pixel shader.
> 0 votes

---
Tags: opengl, shaders, cocos2d-x
---


# Question
Title: Collision detection with multiple polygons simultaneously
I've written a collision system which detects/resolves collisions between a rectangular player and a convex polygon world using the Separating Axis Theorem. This scheme works fine when the player is colliding with a single polygon, but when I try to create a level made up of combinations of these shapes, the player gets "stuck" between shapes when trying to move from one polygon to the other.

The reason for this seems to be that collisions are detected *after* the player has been pushed through the shape by its movement or gravity. When the system resolves the collision, it resolves them in an order that doesn't make sense (for example, when the player is moving from one flat rectangle to another, gravity pushes them below the ground, but the collision with the left hand side of the second block is resolved before the collision with the top of the block, meaning the player is pushed back left before being pushed back up).

Other similar posts have resolved this problem by having a strict rule on which axes to resolve first. For example, always resolve the collision on the y axis, then if the object is still colliding with things, resolve on the x axis. This solution only works in the case of a completely axis oriented box world, and doesn't solve the problem if the player is stuck moving along a series of angled shapes or sliding down a wall.

Does any one have any ideas of how I could alter my collision system to prevent these situations from happening?

# Answer
Your problem is the same as in Box2D. (https://www.iforce2d.net/b2dtut/ghost-vertices)

A solution is all the shape, character and floor, should be a bit enlarged and beveled i.e. make corner smooth.

If you have already found a better solution, please share.
> 1 votes

# Answer
Change your red square collision box to a circle collision (or a sphere in 3D, the same issue can happen in 3D).
> 1 votes

---
Tags: collision-detection, movement, collision-resolution, separating-axis-theorem
---


title: 32 bit or 16 bit textures

text:
# Question
Title: 32 bit or 16 bit textures
I'm trying to build some 2d character with Photoshop and Spine. By now, I have created some of my characters using 16 bit color depth images in Photoshop. Now, I wonder whether I have to use 32 bit or just create everything with 16 bit textures... How much does it affect my game? Considering a 2D Unity or Flash game.

# Answer
> 3 votes
Using a lower number of bits per pixel means you save filesize, loading time and texture memory. Also, sprite drawing will be faster because less data needs to be moved between graphic memory sections.

When you develop a 2d game and your target devices are desktop PCs, these factors can usually be ignored as any modern PC should handle 32bit graphics with ease. However, when you develop for less powerful devices, like low-end smartphones, these optimizations can matter. Not only do smartphones have much weaker hardware, many smartphone users have data-plans with very harsh traffic limitations. These users are reluctant to download apps which are several MB in size, so any trick to get the filesize down can result in more downloads (although when you use Unity, you already lost that battle, because the Unity mobile runtime alone is already almost 10MB in size).

Whether or not there will be a *visual* difference depends on your graphic style. With a retro pixel-art style, reducing the bit-depth is often completely invisible, even when you go as low as 256 colors. With graphics which are rasterized from rendered 3d models, it can be very visible. You will also have problems with any color gradients.

# Answer
> 0 votes
You can tell Unity to compress your textures on import and set this per texture and/or globally so you're free to create your assets at a higher quality.

You can then play with the settings, leaving your source assets as is. They'll be compressed when you build the game.

---
Tags: 2d, textures
---


# Question
Title: How to disable depth buffer in Directx11
For now i know what i must use OMSetDepthStencilState. In the beginning i must create two states and change them every time i need another. For now i have this and it doesn't work, i.e. *objects rendered in order i draw them*:

```
D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
depthStencilDesc.DepthEnable = TRUE;
depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
depthStencilDesc.StencilEnable = FALSE;
depthStencilDesc.StencilReadMask = 0xFF;
depthStencilDesc.StencilWriteMask = 0xFF;

// Stencil operations if pixel is front-facing
depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

// Stencil operations if pixel is back-facing
depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;

ID3D11DepthStencilState *m_DepthStencilState;
HR(m_Device->CreateDepthStencilState(&depthStencilDesc, &m_DepthStencilState));
m_ImmediateContext->OMSetDepthStencilState(m_DepthStencilState, 0);

```

# Answer
> 2 votes
Change

```
depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;

```

to

```
depthStencilDesc.DepthFunc = D3D11_COMPARISON_ALWAYS;

```

---
Tags: directx, directx11, depth-buffer
---


title: Multiplatform GLSL shader validator?

text:
# Question
Title: Multiplatform GLSL shader validator?
Im working on a multiplatform (Pc,Mac,Linux) game that uses shaders quite extensively. Since we do not have any funding, it is pretty hard to test our game on all possible hardware configurations.

While our engine seems to run fine on different platforms, its usually the slight differences in GLSL compiling that gives us headaches. We have things set up such that we can test the shaders on Ati/Nvidia cards, but since the new Macbooks have Intel graphics, I'm really looking for a tool that can simply validate my GLSL shaders for different hardware without the need of yet another system.

Does anyone know such a tool?

# Answer
> 7 votes
The GLSL specification defines how the language works. If you write a shader that conforms to that specification, and it does not work on a particular OpenGL implementation, then that OpenGL implementation has a bug in it. Which means that you are effectively asking for a tool that can reproduce the bugs in Apple's Intel drivers.

That is pretty much impossible. To do that, someone would have to have a list of every bug for every driver revision in Apple's Intel graphics drivers. Even if someone tried to get a list of those bugs and wrote a parser that reproduced them, that wouldn't guarantee you anything, since there could always be new bugs introduced. Or the "validator" could have implemented those bugs incorrectly.

The best you can hope for would be a shader validator that could tell if your GLSL shader conformed to the specification. But that's about it.

# Answer
> 10 votes
Khronos provides a reference GLSL compiler.

It is capable of validating GLSL up to version 3.50 (full support) and up to 4.50 (partial support). It also handles ESSL (OpenGL ES's GLSL).

The tool verifies that the shader conforms to the GLSL specification. This does not necessarily guarantee that it works with all drivers but it does guarantee that the shader will work with any compliant driver. This is a much stricter guarantee than merely checking the shader against a specific driver.

The tool does not validate that the results of the GLSL are what you expect. In particular, there are perfectly valid GLSL sequences that have weakly specified behavior. That can result in a perfectly valid shader having quite different output on different fully-conforming implementations.

A buggy driver may reject or miscompile compliant GLSL. There's no proof against that but - thankfully - it's increasingly rare as Khronos' conformance test suite has become more complete.

The standalone Khronos reference GLSL compiler is easy enough to integrate into a build system to validate stand-alone GLSL files. More intricate systems that load GLSL out of specialized container format or stitch GLSL together from other sources can use the library interface to validate things.

# Answer
> 1 votes
This might be bit far fetched but how about adding a screenshot feature to your game. The game would run with a script controlling game play so it follows predefined path and takes screenshots at critical points. After script is completed it sends them to you with specs of the machine.

Then just crowdsource the whole exercise.

# Answer
> 0 votes
Write your own botnet.

I faced the same problem of not being able to test if shaders even compiled and linked on GLSL implementations and it drove me to a crude solution.

I made small tools that ran in the background on a machine, waiting for JSON bundles with shaders sources to compile and link together using a windowless OpenGL context, returning the results and logs over the network.

Deploy those to people who trust you, and submit requests either directly to the nodes or via a command-and-control server, preferably with some sort of auth, as it's a huge security hole to compile arbitrary shader code, not to mention malicious shader code.

It's of course possible to extend the tool to render to texture to get some actual validation of shader effects back too, but that's far along my roadmap and just seeing if your shaders compile at all on different context versions, profiles and driver versions is worth a lot.

---
Tags: opengl, shaders, glsl, validation
---


# Question
Title: Should a socket server and game server be separate processes?
Assume a simple standard client/server game. For the server, is it worthwhile to have a separate process that listens for connections and messages from clients and sends the data via local sockets or stdin to another process that runs the actual game server?

The other option would be to have both things be done in a single process. Queueing incoming messages and executing them in the right order there shouldn't be a halting issue.

I am wondering if the extra resources to separate the two "activities" is actually worth it. How should I decide? I'd like to hear any pros/cons.

# Answer
> 17 votes
From an API design perspective, when deciding whether to make multiple separate communicating programs or just one, the question is: *can each program function meaningfully without the others?* The answer will vary based on your project and preferences.

**If they can't**, it's not worth thinking about. Clearly they're so heavily linked that they're not really separate processes.

**If they can**, and you can see yourself wanting to drop in different components to replace them in the future, then an OS-provided process abstraction might help.

How *much* it helps depends on the rest of your tech stack though. For example Erlang internally models things as processes already, so you won't gain much of a conceptual benefit from splitting it into OS-processes too. Unless you're thinking of maybe rewriting those parts of the server in a different language. A C++ program's internal components are typically coupled much tighter and hence be harder to swap out, hence splitting them into different OS processes can save you work later if you can foresee such rearrangements.

# Answer
> 11 votes
> is it worthwhile to have a separate process that listens for connections and messages from clients and sends the data via local sockets or stdin to another process that runs the actual game server?

To answer whether it is worthwhile, you had to first ask yourself, what is the problem you are trying to solve by adding a dedicated queuing service. If it solves that problem, then it is worthwhile; if it doesn't solve a problem or if you don't have a problem to solve to begin with, then it's probably not.

Let's see some reasons why some servers use a multi-tier architecture:

1. Load balancing - load balancing make sense if you want to spread your workload over to multiple worker machines. If your program have bottlenecks that you want to solve simply by having multiple concurrent worker process on the same machine, then it's best in the long run to actually solve the bottleneck, but as a short term workaround, spawning worker processes could be practical.
2. Privilege separation - Maybe you don't want a security breach into your chat server to automatically gain access of your game server or vice versa. If your game server is separate from your in-game chat server, you can configure your game server and chat server to live in separate security domain (e.g. run as different user, with different access privileges, different process limits, etc).
3. Zero downtime upgrade - if you want to achieve zero downtime upgrade, you need to have multiple tiers and configure the system such that when you take down a server for servicing, its requests will be redirected to the other servers in the same tier to ensure continuous service.
4. Breaking limit - if you reach the socket limit, file descriptor limit, a global interpreter lock, etc, you may be able to work around that limit by running multiple processes. Another way to solve this is to change the limit, but that's not always easy as you may have to recompile the kernel, or there may be security or performance implications.
5. Limiting resources leakage - you want to write software that doesn't leak resources, but even in fully garbage managed languages this is extremely hard in a long-lived processes, and worse this is hard to replicate in a development environment. A multitier architecture allows you to kill and respawn the game servers after certain amount of time or number of requests to limit the damages from resource leakages, without disrupting service.

# Answer
> 5 votes
I agree with ratchet freak. As long as you have a single gameserver, it's not worth the trouble.

However, this architecture might prove useful when you need to scale up horizontally. When one gameserver is no longer enough and you need to distribute your game on multiple gameservers for performance reasons, the "socket server" architecture could very easily be adapted to turn the socket server into a load balancer which automatically routes connections to one of many backend server.

But when you aren't sure you will ever need this, it is likely overengineering to develop two separate server applications at this point.

# Answer
> 4 votes
It probably isn't, most languages has asynchronous sockets that allow you to use multiple connections at a time without blocking while data is waiting. This shifts the "socket server" part to the OS/kernel.

With an explicit socket server you will incur the cost of a few extra copies as you pass the data through the local socket; one thing that will kill scalability is extra copies where you don't need them.

---
Tags: architecture, server, design-patterns, client-server
---