May 8, 2016

Tutorial,god rays.

Hello!

As I said yesterday,here is the tutorial on how to make god rays.

First,lets understand what god rays are: Crepuscular rays also known as god rays , are rays of light that seem to come from the sun.They pass trought clouds and dust giving that effect:


God rays (real)

God rays are frecuently used in videogames as they look really god and make a scene look more "realistic".


Now lets talk about implementing it on our game/engine.

In this tutorial I´m going to do 3 passes to do it:

Zero pass:

Render the scene as normal and save an image of it,we will need it later.

First pass:

We render all the objects in the scene as black.We paint the light with the color we want for the god rays.


Second pass:

Now is time to make the rays,to do that,we take the image from the last pass and extend the rays from the light point.
The algorithm that I use is the one shown in GPU Gems 3.


vec4 GetColor()
{
  //Sun pos in texture coordinates
  vec2 sunPos =  uSunPosition.xy * 0.5 + 0.5;

  //Extend the rays
  vec4 finalColor = vec4(0.0);
  vec2 deltaTc = oUv - sunPos;
  vec2 curTc = oUv;
  deltaTc *= 1.0 / float(uSamples) * uDensity;
  float illumDecay = 1.0;

  for(int i=0;i<uSamples;i++)
  {
    curTc -= deltaTc;
    vec4 color = texture2D(uScreenTexture,curTc);
    color *= illumDecay * uWeight;

    finalColor += color;
    illumDecay *= uDecay;
  }

  return finalColor * uExposure;
}

The params used are:

  • Exposure (0.578):it determines the total brightness of the image.
  • Decay (0.92):lower values will make the rays shorter,as they will decay faster.
  • Density(2.0):the density of the rays
  • Weight(0,97):the effect of the ray in the final image
  • Samples(90):how many samples should we take for each pixel


Third pass:

Now we are going to use the image from the zero pass and the image of the last pass.We are just going to add each other.
As the image of the rays will have mostly black,it wont "break" the result image.
And thats all! You will end with good looking rays :D


Performance:

I have to say that this effect is kinda expensive as we end up performing a lot of samples.
Screen:1024x720 Samples:100 = 73.728.00 total samples!

You can try to reduce the number of samples if it goes slow and tweak the other params.


I hope you found this tutorial useful!


God rays in my demo.