0

I've written a fragment shader that works with one variable declaration but breaks with another that is mathematically identical. I have edited the code snippet to highlight the two alternatives for thetastrt_2. PI is properly defined and partsnum is a float that equals 3.0 -

fragmentShader: [

    "uniform vec3 mixfinal;",
    //more uniforms

    "vec3 mixer () {",
    "   vec3 lightOG = vec3 ( 0.0 );",          
    "   float thetastrt_0 = PI / 2.0;",
    "   if ( partsnum >= 2.0 ) {",
    "       float thetastrt_1 =  thetastrt_0 + ( PI * 2.0 / partsnum );",
            //more code
    "   }",
    "   if ( partsnum >= 3.0 ) {",

    "       float thetastrt_2 =  thetastrt_0 + ( PI * 4.0 / partsnum );", //shader works

    "       float thetastrt_2 =  thetastrt_1 + ( PI * 2.0 / partsnum );", //shader breaks

            //more code
    "   }",
    "   return lightOG;",
    "}",    //end mixer ()

    "void main() {",
    "   vec3 outgoingLight = vec3( 0.0 );", 
    "   outgoingLight = mixer();",
        //more code
    "}"

With no debugger this was hard to find. Is this a run/compile time issue? Is the problem that thetastrt_2 depends on thetastrt_1 depends on thetastrt_0?

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
pprchsvr
  • 168
  • 2
  • 13
  • OpenGL ES compiler time errors generally include very good error messages, just a like a C compiler. https://www.khronos.org/opengl/wiki/Shader_Compilation#Shader_error_handling – solidpixel Mar 08 '18 at 17:15
  • @solidpixel Thank you and also to Rabbid76. I'm in a Visual Studio - Cordova - WebGL environment, and the error messages were "invalid shader" with no detail. And I've just learned that if statements have scope in C. Thank you. – pprchsvr Mar 08 '18 at 17:28
  • 1
    @Rabbid76 Thank you for your comment. I've programmed mostly in javascript and have now learned that the scoping rules for js - https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript?rq=1 - are different than for other languages - https://stackoverflow.com/questions/8543167/scope-of-variables-in-if-statements If you want to post your comment as an answer, I'll accept it with many thanks. – pprchsvr Mar 08 '18 at 19:09

1 Answers1

2

In

if ( partsnum >= 2.0 ) {
    float thetastrt_1 =  thetastrt_0 + ( PI * 2.0 / partsnum );
    ....
}

float thetastrt_1 is declared in the scope of the if-statement, so it is not accessible anymore outside the if-statement block.

See OpenGL ES Shading Language 3.20 Specification; 4.2.2 Types of Scope; page 44 and 45

The scope of a variable is determined by where it is declared. .....

Representing the if construct as:

if if-expression then if-statement else else-statement,

a variable declared in the if-statement is scoped to the end of the if-statement. A variable declared in the else-statement is scoped to the end of the else-statement.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174