Can't set uniform value in OpenGL shader

≯℡__Kan透↙ 提交于 2019-12-04 04:01:03

问题


I am currently learning OpenGL programming, and I have made some good progress, but I seem to be stuck now.

Currently, I am trying to get simple shaders to work. To be more specific, I am trying to set a uniform value of the shader. The shaders compile successfully, and work correctly if I eliminate the uniform value. Here is the (vertex) shader code:

#version 440 core

layout(location = 0) in vec3 vertex;

uniform mat4 mvp;

void main()
{
    gl_Position = mvp * vec4(vertex, 1);
}

And the code I use to set the value (glGetUniformLocation returns 0 as expected):

mvp = glm::mat4(
    glm::vec4(3.0f, 0.0f, 0.0f, 0.0f),
    glm::vec4(0.0f, 1.0f, 0.0f, 0.0f),
    glm::vec4(0.0f, 0.0f, 1.0f, 0.0f),
    glm::vec4(0.0f, 0.0f, 0.0f, 2.0f)
);

GLuint matrix = glGetUniformLocation(program, "mvp");
glUniformMatrix4fv(matrix, 1, GL_FALSE, glm::value_ptr(mvp));

The problem is that it doesn't seem to set the value at all. If I query the uniform's value using glGetUniformfv, it returns the default value (not the one I just set), and the geometry doesn't show up at all (but that is just a consequence, that's not the problem here).

If I hardcode the uniform's value in the shader, the application displays the geometry correctly, and when asked for the value (again, using glGetUniformfv), it returns the correct value.

#version 440 core

layout(location = 0) in vec3 vertex;

uniform mat4 mvp = mat4(
    vec4(1.0f, 0.0f, 0.0f, 0.0f),
    vec4(0.0f, 1.0f, 0.0f, 0.0f),
    vec4(0.0f, 0.0f, 1.0f, 0.0f),
    vec4(0.0f, 0.0f, 0.0f, 2.0f)
);

void main()
{
    gl_Position = mvp * vec4(vertex, 1);
}

Any idea why does this happen? I am using OpenGL 4.4, but I have tried many different versions with the same result.

Thanks for your time and efforts,
Levente


回答1:


Are you calling glUseProgram before setting the uniforms ? A full working listing can be found in many examples online, including what I had written sometime back (https://github.com/prabindh/sgxperf/blob/master/sgxperf_gles20_vg.cpp) that shows the sequence to be:

glCreateProgram();

glAttachShader()

glLinkProgram

glUseProgram()

glGetUniformLocation()

glUniformMatrix4fv



来源:https://stackoverflow.com/questions/21967506/cant-set-uniform-value-in-opengl-shader

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!