Hi!
I have some questions regarding performance that im quite confused about, wherever i read i get the impression that “if-statements” is a big no-no unless you really need them.
As I understand it it is because the GPU simply evaluates both branches of an “if-else” and just discard the result of the one on the loosing side of the condition.
For example if I do something like:
float someValue = value1 * value2;
if(someValue > someOthervalue)
... do some calculations "c1"...
else
... do some other calculations "c2"...
…both calculation “c1” and “c2” gets evaluated, thus performance take a hit. (At least thats what I thought)
What I found was that if the calculation “c1” was a very expensive one and “c2” was a very cheap one, having the condition there to stop some fragments entering “c1” calculation actually had a positive effect on performance.
How is that possible? Have I completely misunderstood something?
My scene took about 9.2 ms per frame to render before i started optimizing and after removing any branches from the code I ended up with 10ms per frame which is really not what I wanted
The code running (excluding implementation of functions) was the following. Removing these if-statements “should” not have a negative impact on the performance right?
void main()
{
vec3 color = vec3(0,0,0);
E = normalize(E_in);
L = normalize(L_in);
H = normalize(H_in);
float spotFactor = dot(L, -lightDirection_fs);
// Inside spot cone
if(spotFactor > lightCutoff)
{
vec2 UVs = GetTextureCoords(E);
vec3 N = FindNormal(E, UVs);
float visibility = GetShadowValue();
float lightAmount = GetAttenuationValue();
vec3 diffuse = vec3(0,0,0);
vec3 specular = vec3(0,0,0);
if(lightAmount >= 0.01)
{
vec3 diffuse = CalculateDiffuseLight(N, UVs);
if(visibility == 1.0)
specular = CalculateSpecularLightBlinnPhong(N, UVs);
color = (diffuse + specular) * visibility * lightAmount;
color *= (1.0 - (1.0 - spotFactor)/(1.0 - lightCutoff));
}
}
gl_FragColor = vec4(color, alpha);
}