Tuesday, July 17, 2007

Shader Fog

Have found out how to do fog in the shader so this means that you can now have fog in your XBox 360 games as well as your Windows based games.

As usual it is a matter of adding the right semantic and setting the correct renderstate in the shader.

So, the code.

Shader Model 1.1 - 2
In your Shader's vertex return structure, add the following

float Fog : FOG;

In your vertex shader set the fog you require:

Output.Fog = 1.0f - ( length( Input.Position - EyePosition) / 50.0f);

Note: This is an example you can generate this how ever you need to.

Now all you have to do is set the render state for fog, so in the top of your pass add this

FOGCOLOR = (float4(.5,.5,.5,1));

Where 3 is Linear fog and float4(.5,.5,.5,1) would be the color gray.

Shader Model 3
To get fog working on SM 3 and/or the XBox 360 is a little different

  • Remove ALL state settings in the technique.
  • Swap the FOG simantic for a TEXCOORD.
  • As the FOGCOLOR state has been removed, you need to
       calulate this in the shader per vertex lerp between the
       calculated color and the fog color based on the FOG

    For Example:

    Out.Color = lerp(g_FogColor, color * ((In.Diffuse * g_MaterialDiffuseColor) * diffuse + g_MaterialAmbientColor), In.Fog);

    Thanks to Leaf at XNA UK User Group and Jon Watte for your help with this I am sure this will help many others in there XNA development. Jon's shader also has the ability to specify the height of the fog and so giving a much richer fog effect, nice...

    If you have any interest in the discussions we had then take a look here or the comments on this post.

    Leaf has also put up an example of Jon's shader in action and you can find that here.

    1. Hi, unfortunately this technique will not work on the Xbox 360 or when using shader model 3.0 on Windows. The .fx file as given wont compile in an Xbox 360 project.

      You are still using render states (FogColor, FogEnable) to do the fogging. Setting them in the .fx file is no different to setting them in your code.

      To do fogging on the Xbox 360 or shader model 3.0 in Windows requires that you do it completely manually - usually in the pixel shader using some depth based calculation.

    2. Ahh, right.

      Thanks for that, I will update the post.

      I have put this up on the XNA Creators Club here forum as a solution and it seemed to work for the guy that tried it.

      But then there is a post after mine saying how this should be done for shader 3.


    Note: Only a member of this blog may post a comment.