OpenGL着色器无法从glVertexAttribPointer()获取值

时间:2019-07-02 00:38:45

标签: c++ opengl glm-math

尽管我分别调用glEnableVertexAttribArrayglVertexAttribPointer,但我的顶点着色器似乎无法访问该值(之所以说是value,是因为我不确定它的名称是Attribute?)。

我很困惑,因为顶点着色器可以通过执行完全相同的操作来访问其他值。

在以下代码中,着色器可以很好地访问属性位置0的“顶点”位置和属性位置1的“顶点法线”,但是当我将属性位置2的“顶点”颜色值用作网格的颜色时,它是黑色的即使另有设置。

//Vertex Position
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, vertexPosition));

//Vertex Normal
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, vertexNormal));

//Vertex Colour
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, vertexColor));

这是顶点结构

struct Vertex {

    glm::vec3 vertexPosition;
    glm::vec3 vertexNormal;
    glm::vec3 vertexColor;

    glm::vec2 textureCoords;

    glm::vec3 vertexTangent;
    glm::vec3 vertexBitangent;

    Vertex() {}

    Vertex(glm::vec3 vertexPosition, glm::vec3 vertexNormal = glm::vec3(0), glm::vec3 vertexColor = glm::vec3(0), glm::vec2 textureCoords = glm::vec2(0)) {
        this->vertexPosition = vertexPosition;
        this->vertexNormal = vertexNormal;
        this->textureCoords = textureCoords;
    }

};

这里是着色器代码。如果我取消注释该行,则网格将按预期呈现红色

#version 330 core

uniform mat4 uModelMatrix;
uniform mat4 uViewMatrix;
uniform mat4 uProjectionMatrix;
uniform vec3 uLightPosition;

layout(location = 0) in vec3 aVertexPosition;
layout(location = 1) in vec3 aVertexNormal;
layout(location = 2) in vec3 aVertexColor;

out vec3 viewDirection;
out vec3 lightPosition;
out vec3 fragmentPosition;
out vec3 materialColor;
flat out vec3 fragmentNormal;

void main(){

    materialColor = aVertexColor;
    //materialColor = vec3(0.5, 0, 0);

    mat4 modelViewMatrix = uViewMatrix * uModelMatrix;

    vec3 viewSpacePosition = (modelViewMatrix * vec4(aVertexPosition, 1)).xyz;
    viewDirection = normalize(viewSpacePosition);

    vec3 viewSpaceNormal = normalize(modelViewMatrix * vec4(aVertexNormal, 0)).xyz;
    fragmentNormal = viewSpaceNormal;
    fragmentNormal = aVertexNormal;

    lightPosition = uLightPosition;

    fragmentPosition = vec3(uModelMatrix * vec4(aVertexPosition, 1.0));

    gl_Position = uProjectionMatrix * modelViewMatrix * vec4(aVertexPosition, 1);
}

即使vertexColor默认为glm::vec3(1)而不是glm::vec3(0),它仍然是黑色的。在使用着色器绘制之前,我已经检查了vertexColor的值,并且颜色为 not 黑色。

1 个答案:

答案 0 :(得分:2)

似乎您没有在Vertex构造函数中设置vertexColor值。

Vertex(glm::vec3 vertexPosition, glm::vec3 vertexNormal = glm::vec3(0), glm::vec3 vertexColor = glm::vec3(0), glm::vec2 textureCoords = glm::vec2(0)) {
        this->vertexPosition = vertexPosition;
        this->vertexNormal = vertexNormal;
        this->vertexColor = vertexColor;
    }