我的OpenGL程序的着色器不会影响多边形的几何或颜色

时间:2017-05-03 05:00:16

标签: c++ opengl glsl shader

我有一个顶点和片段着色器,很久以前工作得很好,但我试图实现骨架动画,沿线的某处打破了某些东西。我甚至没有使用我的自定义函数,只是设置了一个简单的“绘制一个三角形并着色它”的代码块,但它不起作用。

绘图代码:

GLfloat vertices[] = {
    0.5f,  0.5f, 0.0f,  // Top Right
    0.5f, -0.5f, 0.0f,  // Bottom Right
    -0.5f, -0.5f, 0.0f,  // Bottom Left
    -0.5f,  0.5f, 0.0f   // Top Left 
};
GLuint indices[] = {  // Note that we start from 0!
    0, 1, 3,  // First Triangle
    1, 2, 3   // Second Triangle
};
GLuint VBO, VAO, EBO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glGenBuffers(1, &EBO);
// Bind the Vertex Array Object first, then bind and set vertex buffer(s) and attribute pointer(s).
glBindVertexArray(VAO);

glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

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

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

glBindBuffer(GL_ARRAY_BUFFER, 0); // Note that this is allowed, the call to glVertexAttribPointer registered VBO as the currently bound vertex buffer object so afterwards we can safely unbind

glBindVertexArray(0); 

while (!win.windowShouldClose) {

    win.clearScreen(glm::vec4(1.0f,1.0f,1.0f,1.0f));
    newShader.Use();
    GLint mvpLoc = glGetUniformLocation(newShader.Program, "MVP");
    glUniformMatrix4fv(mvpLoc, 1, GL_FALSE, glm::value_ptr(camera.proj * camera.view));
    glBindVertexArray(VAO);
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
    glBindVertexArray(0);

    win.display();

}

顶点着色器:

#version 430
layout (location = 0) in vec3 position;
layout (location = 1) in vec3 normal;
layout (location = 2) in vec2 texCoords;

out vec2 TexCoords;
out vec3 ourColor;

uniform mat4 MVP;

void main()
{
    gl_Position =  MVP * vec4(position,1.0f);
    TexCoords = texCoords;
    ourColor = vec3(1.0f, 0.0f, 1.0f);
}

片段着色器:

#version 430

in vec2 TexCoords;
in vec3 ourColor;
out vec4 color;
uniform sampler2D texture_diffuse1;
void main() {
  color = vec4(ourColor,1.0f);
}

我花了几天时间研究这个问题,而且我也没有找到解决方案了。我认为这是我发送到着色器的数据的一个问题,但即使使片段的输出如图所示恒定,三角形仍然是黑色的,并且根本不受顶点着色器的影响,就好像它们要去的一样直接从NDC到屏幕空间。

1 个答案:

答案 0 :(得分:2)

由于你没有显示camera属性,我怀疑你的投影和视图矩阵有任何问题(即MVP矩阵可能会将对象转换出屏幕)。我刚刚在我的计算机上使用glfw库测试了您的程序,我的测试结果显示您的代码没问题。也就是说,“我认为这是我发送到着色器的数据存在问题”没有问题

enter image description here

尝试删除顶点着色器的MVP矩阵:

#version 430
layout (location = 0) in vec3 position;
layout (location = 1) in vec3 normal;
layout (location = 2) in vec2 texCoords;

out vec2 TexCoords;
out vec3 ourColor;

uniform mat4 MVP;

void main()
{
    // Remove MVP matrix
    gl_Position = vec4(position,1.0f);
    TexCoords   = texCoords;
    ourColor    = vec3(1.0f, 0.0f, 1.0f);
}