webgl shader中loop的错误如何解决

how do I solve the error of loop in webgl shader

当我为for循环传入一个uniform int变量时,报错

当我定义常量时,它不报错,

如何解决

// 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)

我猜你的目标是 WebGL 1。

如果我们查看 WebGL 使用的 The OpenGL® ES Shading Language, version 1.00 规范,并查看“附录 A:ES 2.0 的限制”部分(OpenGL ES 2.0 是 WebGL 1 所基于的) ,它说:

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 !=

注意“constant_expression”。不幸的是,这意味着您不允许*像您一样为循环绑定使用统一变量。

我相信这在 WebGL 2 中有所不同。如果可以的话,您可能想尝试使用它。


* GLSL ES 规范确实说“在 GLSL ES 规范中,允许实现实现超出本节中描述的最小值的功能,而无需使用扩展。”然而,不幸的是 WebGL 的规范 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