为什么我只能看到一种颜色?

时间:2018-11-18 13:30:29

标签: c++ opengl-3

我正在尝试在使用OpenGL 3.3绘制的矩形的背景上放置颜色或图像。 我正在尝试自己生成图像颜色以进行测试,但是我的代码似乎有问题,我只能看到一种颜色。

顶点着色器:

#version 330 core
layout(location = 0) in vec2 VertexPosition;
layout(location = 1) in vec2 VertexUV;
out vec2 UV;
void main() {
    gl_Position = vec4(VertexPosition.x, VertexPosition.y, 0.0, 1.0);
    UV = VertexUV;
}

片段着色器:

#version 330 core
in vec2 UV;
out vec3 Color;
uniform sampler2D TextureSampler;
void main() {
    Color = texture(TextureSampler, UV).rgb;
}

我生成纹理的方式:

GLuint data[3] = {64, 128, 192};
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1, 1, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);

我绘制元素的方式:

glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, tex);
glUniform1i(TextureSamplerID, 0);

glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, VertexBuffer);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, nullptr);

glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, UVBuffer);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, nullptr);

glDrawArrays(GL_TRIANGLES, 0, 6);

glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);

glBindTexture(GL_TEXTURE_2D, 0);

我生成缓冲区的方式:

glGenBuffers(1, &VertexBuffer);
glGenBuffers(1, &UVBuffer);

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

const GLfloat uv_coordinates[] = {
        0.0f, 0.0f,
        1.0f, 0.0f,
        1.0f, 1.0f,

        1.0f, 1.0f,
        0.0f, 1.0f,
        0.0f, 0.0f
};
glBindBuffer(GL_ARRAY_BUFFER, UVBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(uv_coordinates), uv_coordinates, GL_STATIC_DRAW);

当我使用它们创建并绘制矩形时,会看到以下内容: enter image description here

我尝试用这些生成纹理数据:

GLuint data2[192];
for(int i = 0; i < 192; i++) data2[i] = i;
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 8, 8, 0, GL_RGB, GL_UNSIGNED_BYTE, data2);

,我看到了: enter image description here

1 个答案:

答案 0 :(得分:3)

由于传递给glTexImage2D的枚举数的类型为GL_UNSIGNED_BYTE,因此像素数据数组的数据错字必须为GLubyte(对应于GL_UNSIGNED_BYTE ),而不是GLuint

GLubyte data2[192];
for(int i = 0; i < 192; i++) data2[i] = i;
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 8, 8, 0, GL_RGB, GL_UNSIGNED_BYTE, data2);