Opengl程序无法识别第二个顶点输入

时间:2016-06-09 16:05:14

标签: opengl fragment shader vertex-shader

我正在阅读着色器和颜色,它们如何被定义为顶点输入。所以我接受了这个教程并且弄得一团糟,因为该程序只是向前阅读而不是进入下一行:

GLfloat vertecies[] = {
    //vertices              colors
    0.5f, -0.5f, 0.0f,      1.0f, 0.0f, 0.0f,// Bottom Right
    -0.5f, -0.5f, 0.0f,     0.0f, 1.0f, 0.0f,// Bottom Left
    0.0f,  0.5f, 0.0f,      0.0f, 0.0f, 1.0f,// Top 
};

以下代码应该将第二个顶点输入设置为颜色:

glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertecies), vertecies, GL_STATIC_DRAW);

glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(index), index, GL_STATIC_DRAW);

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(0);

glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
glEnableVertexAttribArray(1);

glBindVertexArray(0);

这是我的顶点着色器代码:

const char* VertexShaderCode =
 "#version 330 core\r\n"
 ""
 "layout(location=0) in vec3 position;"
 "layout(location=1) in vec3 color;"
 ""
 "out vec3 theColor;"
 ""
 "void main()"
 "{"
 "  gl_Position = vec4(position, 1.0);"
 "  theColor = color;"
 "}";

这是碎片着色器代码:

const char* FragmentShaderCode =
 "#version 330 core\r\n"
 ""
 "in vec3 theColor;"
 ""
 "out vec4 color;"
 ""
 "void main()"
 "{"
 "  color = theColor;"
 "}";

告诉我,如果我做错了什么。

1 个答案:

答案 0 :(得分:2)

你的步幅乘数对于属性索引0是错误的。它应该是6,因为一个顶点包含3个位置元素和3个颜色元素。取代

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0);