c++ - OpenGL 着色器未从 glVertexAttribPointer() 获取值
问题描述
虽然我调用glEnableVertexAttribArray
and glVertexAttribPointer
,但我的顶点着色器似乎无法访问该值(我说值是因为我不确定它叫什么,属性?)。
我很困惑,因为我有顶点着色器可以通过做完全相同的事情来访问的其他值。
在下面的代码中,着色器可以很好地访问属性位置 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 的值,并且颜色不是黑色。
解决方案
看起来您没有在 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;
}