Wednesday, July 9, 2014

Fading with Shaders

This is a fun little post I thought I could do really quick.  While I'm still getting the hang of using shaders and such, recently I thought of something that I thought was kind of clever to do with shaders.  This is a quick post about what the problem was and how I solved it.  Shout out to Michael C. Johnson for suggesting to blog about this!


The Problem

While not the game I am working on, still a neat example of
all the cool things shaders can create.
In a recent game I've been working on, I needed to do a quick fade-in and fade-out effect in various parts of the game.  The problem is that I didn't have a ton of resources to work with to do so on the hardware.  My original thought was to simply draw a quad on top of everything, and then fade it in and out by editing the individual pixels transparencies.  Then I remembered I had shaders available, and thought about drawing the quad on top of everything, and fading it out with a shader.  This would have worked very well, except again, I was working with limited resources, specifically a limited amount of memory.  Drawing a whole extra quad was a whole extra object I would then have to manage, and it was also more things in memory as a result.  Then, I thought of another idea.

The Solution

Instead of drawing a quad on top of everything to fake this fading effect, why don't I just actually fade everything?  I could simply add a uniform transparency value to the shader file, and then set that for every object once and it would fade each object equally!  The results were astounding, because I could also change the color by just changing the screen's clear color glClearColor.  Suddenly I could fade out to any color, without any extra resources being needed outside of that one uniform value!

The Issues

While this method is pretty good with reducing memory usage, and also is a lot easier to implement, it does have its downsides.  Because you are multiplying the alpha values for each object, you are technically using more clock cycles with the multiplication of each fragment.  This means you'll want to be cautious if you want everything processed in a timely manor.  Luckily I did not run into that issue in this case, but that's a big thing to keep in mind.

Conclusion

While I'm sure this is nothing revolutionary, I still thought it was worth sharing and hope it is of use to someone out there.  Feel free to leave any comments or other suggestions below!