Saturday 13 November 2010

Sun rays








Writing shaders is one of the things that I enjoy most in making games. Kind of surprising, really, because generally I dislike doing low-level coding and optimisation. Shaders are among the worst in terms of dirty hacks and hardware specific code. So why do I enjoy writing them, then? I think shaders attract me because of this: they are so limited, that science and optics become totally useless. The way real light works is so much more complex than what you can do in a shader, that you need to just make something up that kind of looks similar, although it is often totally unrealistic. Physically, most shaders are utter nonsense. So instead of being all about knowledge and math, shaders centre on creativity and experimenting. Now that's fun! (At least, to a special kind of people, also known as Joosts.)

One of the nicest examples of creativity in shaders is how light shafts are rendered in games. Light shafts are also known as god rays, volume light, sun rays or Jacob's ladders. They are what you see when a light shines through misty air. The microscopic particles in the air are lit and become visible.



Rendering volume light realistically takes a lot of computation time. You need to trace rays through air, take into account the density of the mist, and for a large number of points in the air you need to calculate whether the particles there are illuminated by your light. This includes doing shadow calculations for each of these points in the air. This is way too complex to do well in real-time.

So, some clever programmer somewhere (not me) came up with a trick that looks great and is a whole lot simpler to do. The idea is really simple: you just walk over the image from the pixel towards the sun, and look how much light there is in the image.



Click here for the original article about this technique, which is also the source of these images.

Things like volume, fog density and shadow are completely ignored. There is hardly any relation between this technique and how real volume light works, but somehow it looks very similar and really convincing. Games like Far Cry 2 and Crysis use it to create beautiful lighting effects through the leaves.

There are some limitations to this technique, though. Most importantly, it only works if the light source itself is actually in view. For example, using this technique, it is impossible to render the effect of a flashlight that is pointing away from the viewer.

Rendering light shafts this way not only looks awesome; it is also one of the most beautiful, simple and ingenious shader techniques I know of. Since I like this effect so much, I couldn't help myself but add it to Proun's third track. The track's graphics are far from final, but the light shafts are there. The little video at the beginning of this post shows how dynamic the effect looks in motion.

2 comments: