In my case, I add a varying to my .vert and .frag:
varying float my_z;
I also have a uniform for fog color and I use the alpha channel of the fog color for distance.
And then in the main of my .vert after gl_Position is calculated:
my_z = gl_Position.z;
Then in my .frag’s main at the end:
float fogDensity = 1.2;
vec4 fogColor = m_FogColor;
float fogDistance = fogColor.a;
fogColor.a = 1.0;
float depth = my_z / fogDistance;
float fogFactor = exp2( -fogDensity * fogDensity * depth * depth * LOG2 );
fogFactor = clamp(fogFactor, 0.0, 1.0);
gl_FragColor =mix(fogColor,gl_FragColor,fogFactor);
I don’t know if it’s the best way but it works for me. I calculate material alpha separately and apply it after the fog mix.
And if forking the lighting material and adding the above sounds scary then it’s best to steer clear. Editing GLSL is not for the faint of heart.