OpenGLES 3.0:"Only consts can be used in a global initializer "

OpenGLES 3.0: "Only consts can be used in a global initializer "

我是 chapter2这本书的新手,但是我在安装演示APP时遇到了这个错误:

2020-12-06 16:16:10.888 7549-7578/com.demo.hellosquare E/glOpenGLES3Native: Could not compile shader 35633:
ERROR: 0:6: 'RadianAngle' : Only consts can be used in a global initializer 
ERROR: 0:6: 'RadianAngle' : Only consts can be used in a global initializer 
ERROR: 0:6: 'RadianAngle' : Only consts can be used in a global initializer 
ERROR: 0:6: 'RadianAngle' : Only consts can be used in a global initializer 
ERROR: 4 compilation errors.  No code generated.

问题是,我不明白该消息试图告诉我什么(Google 没有相关结果)。

代码中涉及“RadianAngle”的地方如下:

在我的单个 CPP 文件的顶部,我声明:

GLuint radianAngle;

然后我的着色器也在同一文件的顶部:

static const char vertexShader[] =
    "#version 300 es                                          \n"
    "in vec4        VertexPosition;                           \n"
    "in vec4        VertexColor;                              \n"
    "uniform float  RadianAngle;                              \n"

    "out vec4       TriangleColor;                            \n"
    "mat2 rotation = mat2(cos(RadianAngle),sin(RadianAngle),  \
                 -sin(RadianAngle),cos(RadianAngle)); \n"
    "void main() {                                            \n"
    "  gl_Position   = mat4(rotation)*VertexPosition;         \n"
    "  TriangleColor = VertexColor;                           \n"
    "}\n";

最后在我的渲染函数中(将通过 JNI 调用)在同一个文件中:

radianAngle          = glGetUniformLocation(programID, "RadianAngle");
glUniform1f(radianAngle, radian);

奇怪的是,我完全是从书上抄的,叹气..

问题与行有关:

mat2 rotation = mat2(cos(RadianAngle),sin(RadianAngle),
                     -sin(RadianAngle),cos(RadianAngle));

rotation 是全局范围内的变量。全局变量只能用常量表达式初始化。 RadianAngle 不是常数,因为它是一个统一变量。这会导致错误:

ERROR: 0:6: 'RadianAngle' : Only consts can be used in a global initializer

错误出现4次,因为RadianAnglerotation的初始化器中使用了4次。

您必须在 main 中设置 rotation 的值:

mat2 rotation;

void main()
{
    rotation = mat2(cos(RadianAngle),sin(RadianAngle),
                    -sin(RadianAngle),cos(RadianAngle));

    // [...]
}