glGetAttribLocation有时只能工作

时间:2013-08-14 09:23:08

标签: opengl glsl

我可以编译,链接和运行GLSL程序,但无法提取所有属性的句柄。

const std :: string v = shaders .read_file (VERTEX_SHADER);
const std :: string f = shaders .read_file (FRAGMENT_SHADER);

std :: cout
    << "Vertex shader:\n" << v
    << "Fragment shader:\n" << f
    << "End of shaders.\n";

// Create objects
auto f_id = glCreateShader (GL_FRAGMENT_SHADER);
auto v_id = glCreateShader (GL_VERTEX_SHADER);
auto p = glCreateProgram ();

// Success flags
GLint v_ok, f_ok, p_ok;

// Compile vertex shader
const GLchar * source = v .c_str ();
GLint length = v .size ();
glShaderSource (v_id, 1, & source, & length);
glCompileShader (v_id);
glGetShaderiv (v_id, GL_COMPILE_STATUS, &v_ok);

// Compile fragment shader
source = f .c_str ();
length = f .size ();
glShaderSource (f_id, 1, & source, & length);
glCompileShader (f_id);
glGetShaderiv (f_id, GL_COMPILE_STATUS, &f_ok);

// Link
glAttachShader (p, v_id);
glAttachShader (p, f_id);
glLinkProgram (p);
glGetProgramiv (p, GL_LINK_STATUS, &p_ok);

if (f_ok && v_ok && p_ok)
{
    std :: cout << "Build OK\n";

    for (auto n : {"normal", "position", "xxx", "fail"})
    {
        auto a = glGetAttribLocation (p, n);

        std :: cout << n <<" is " << a << std :: endl;
    }
}
else
    std :: cout << "Build failed.\n";

assert (GL_NO_ERROR == glGetError ());

我希望找到“正常”,“位置”和“xxx”属性,但不要“失败”。这是输出。

Vertex shader:
#version 130

attribute vec3 normal;
attribute vec3 position;
attribute vec3 xxx;

void main ()
{
        gl_Position = vec4 (position, 1);
}
Fragment shader:
#version 130

out vec4 finalColor;

void main ()
{
        finalColor = vec4 (1.0, 1.0, 1.0, 1.0);
}
End of shaders.
Build OK
normal is -1
position is 0
xxx is -1
fail is -1

当我实际运行它时,我得到了一个未转换的白色三角形,如预期的那样。为什么只能正确加载“位置”?

1 个答案:

答案 0 :(得分:5)

出于同样的原因,制服只有在使用时才能保证存在。如果您尝试查询它们,则着色器未使用的任何制服,属性或其他已定义资源可能不存在。

相关问题