Loops in shaders are not the same loops as in regular programming languages.
Let's say you write:
for(i = 0; i < 5; i++)
{
value += i;
Color += tex2D(...,i*0.25);
}
into your code, then the compiler will unroll the for loop statement to something like
value += 0;
Color += tex2D(...,0*0.25);
value += 1;
Color += tex2D(...,1*0.25);
value += 2;
Color += tex2D(...,2*0.25);
value += 3;
Color += tex2D(...,3*0.25);
value += 4;
Color += tex2D(...,4*0.25);
As a result, shaders don't like dynamic for loop ranges that much. You can try one of 2 approaches (that I am aware of/ I use):
for ( int layer=0; layer<8; layer+=1 )
{
if(layer < layerCount) {...}
}
or
for ( int layer=0; layer<8; layer+=1 )
{
multiply with another value, let's say
float array_active_var[8];
which is non-zero if used
}
The first way should be faster but if loops are special in shader language too and are not as fast as in regular programming.
Salud!