Sunday, June 12, 2011

Sun Shafts / God Rays

hi

this time i talk about nice effect called: sun shafts/god rays/sun rays...
to save words explaining what it is, i found a nice picture that shows how this effects looks like in reality:

notice how the sun "enters" between the trees and block by others, this create the light shafts you see in the picture.
so how do we going to do this effect in real-time you ask?
well, very simple, good old demo scene effect called radial blur as post process effect will do the work (well, with a little help of some Gaussian blur)
so the main steps is:
1. compute light position in screen space (this is our sun light pos)
2. compute radial blur on our image, this is done by blurring the image using normalized pixel to light direction.
something like this:

blur_dir = (sun_pos_2d - pixel_pos) / NUM_SAMPLES
sum = 0
for i = 0 to NUM_SAMPLES do
{
sum += sample(image, uv)
uv += blur_dir
}
return sum / NUM_SAMPLES

this is just an example of the radial blur idea, keep in mind that in order to make the effect looks good you need to weight the samples to give you the best look that you are looking for.
3. combine both sun shafts result we got in 2, with our original image.
thats it.
here is some pictures to show the effect in action:

no sun shafts

with sun shafts

if you follow exactly by the steps i wrote, you probably need a lot of samples to get nice results, so here is few tips to make the effect fast and smooth:
1. try to down sample your image and apply the sun shafts effect on it
2. blur the sun shafts result with your favorite blur (should be fast enough)
3. because it a post effect, the effect will apply the sun shafts on all the image resulting shafts from none sun light pixels, to overcome this, you should mask out all pixels that shouldn't be effected by the sun shafts effect, techniques to consider:
* stencil buffer
* depth buffer
whatever fits you engine...
that's it for now, if you have any question, feel free to ask...
cya until next time