Recently I was required to implement Overlay Blending in a video game to achieve a day/night effect. After some research I discovered that the easiest way to do this is through GLSL shaders. Up until now I’ve avoided shaders like I’m some sort of primitive caveman and they’re some crazy voodoo magic. But after some reading, it turns out they’re not so difficult to implement.

My current project uses mini2Dx and since that’s built on top of LibGDX it’s easy to load and apply shader effects to the OpenGL rendering pipeline (see ShaderProgram and Graphics#setShaderProgram). First let’s create our shader.

In OpenGL there are several types of shaders but the two most commonly used are vertex and fragment shaders. Vertex shaders operate on the individual vertices being rendered, while fragment shaders operate on a per pixel level. Since we need to modify colors on a per pixel basis, a fragment shader is required. However, if you’re using mini2Dx or LibGDX you need to also apply a vertex shader to the ShaderProgram. The default LibGDX 2D vertex shader will work fine.

Our fragment shader will require access to two textures bound to the OpenGL context – the main image to be rendered (u_texture) and the color to overlay on top of it (u_mask). After that just apply the blend logic and store the result to gl_FragColor.

If you’re using mini2Dx or LibGDX, there’s some work required to set up the OpenGL context correctly for this. First, you need to load your ShaderProgram and bind the u_texture and u_mask variable names.

Next, you’ll need to create a texture that is bound to OpenGL Texture 1 so that you can render the overlay color.

Now you can render your game (I’d recommend rendering your game to a FrameBuffer and then rendering the frame buffer’s texture) and simply render your overlay color to the overlay texture.

Leave a Reply

Your email address will not be published. Required fields are marked *