Search code examples
glslwebgl

how do I solve the error of loop in webgl shader


When I pass in an uniform int variable for a for loop, it reports an error

When I define a constant, it doesn't report an error,

How to solve it

// error INVALID_OPERATION
uniform int myLen;
for (int i = 0; i < myLen; i += 1)

// success
const int myNum = 10;
for (int i = 0; i < myNum; i += 1)

Solution

  • I am guessing you are targeting WebGL 1.

    If we look at the specification for The OpenGL® ES Shading Language, version 1.00, which is what WebGL uses, and look at the section "Appendix A: Limitations for ES 2.0" (OpenGL ES 2.0 is what WebGL 1 is based on), it says:

    In general, control flow is limited to forward branching and to loops where the maximum number of iterations can easily be determined at compile time.

    […]

    for loops are supported but with the following restrictions:

    […]

    • The for statement has the form:
      for ( init-declaration ; condition ; expression ) statement

    […]

    • condition has the form
      loop_index relational_operator constant_expression
      where relational_operator is one of: > >= < <= == or !=

    Note the "constant_expression". This unfortunately means that you aren't allowed* to use a uniform variable for your loop bound, like you did.

    I believe this is different in WebGL 2. You might want to try using that if it's an option.


    * The GLSL ES spec does say "Within the GLSL ES specification, implementations are permitted to implement features beyond the minima described in this section, without the use of an extension." However, unfortunately WebGL's specification prohibits this:

    A WebGL implementation must only accept shaders which conform to The OpenGL ES Shading Language, Version 1.00 [GLES20GLSL], and which do not exceed the minimum functionality mandated in Sections 4 and 5 of Appendix A