2D Post Processing and You!

Here's a handy tip on how to make your 2D games nice and pretty. Lighting is generally an expensive and complicated operation, but if we take a simplified approach we can make a bland looking game into a good looking one without too much effort.

The first step is to clear the screen and draw into an FBO the lights. In my case I had tiles so I used a circular gradient texture for the player's field of view (shown left), and a white tile texture with heavily blurred edges for the tiles themselves (shown right). These are semi-transparent but I put a black background so that you can see easier here. light-textures-demo.png

So for each glowing tile the glow texture was drawn into the FBO with a colour tint, and each glowing entity would have the circle gradient tinted.

Since lights are additive and do not override the lights drawn before them, I had to set the glBlendFuncSeparate with parameters GL_SRC_ALPHA, GL_DST_ALPHA for the colours, and GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA for the alpha (you can see documentation of this openGL function here: https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glBlendFuncSeparate.xhtml

After that was drawn, set the blend function back to normal with glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA) so that images drawn in front override images in the back. Also clear the screen again and draw your normal game with its entities and tiles.

Then we end up with the two views (on the left what is now drawn to the screen, on the right stored in the FBO) on top shown here: Postprocessing-demo.png

Lastly to combine these two, draw the FBO (i.e the lighting) with the blend function glBlendFunc(GL_DST_COLOR, GL_ONE_MINUS_SRC_ALPHA) so that the lighting produces a multiply effect as is done in image processing, darkening non-lit areas, and then you are done! To draw a UI, simply repeat the normal drawing step again with only your UI elements so it is not affected by the lighting.

I hope you can take from this and make prettier 2D games! If you want to see my compo entry where I used this technique go to https://ldjam.com/events/ludum-dare/47/keys-and-goblins where the source code is linked as well to see how this works in code.