OpenGL - 纹理无法正确渲染

时间:2021-01-25 04:17:51

标签: c++ opengl

我正在尝试渲染一个具有木质纹理的立方体(立方体的所有面都具有相同的纹理),但纹理没有按预期渲染(看起来纹理在某些部分是透明的):< /p>

outside the cube

但如果查看立方体内部,它似乎渲染正常:

:enter image description here

这是我正在读取的 .obj 文件(带有纹理坐标和顶点):

mtllib crate.mtl
o Cube_Cube.002
v -1.000000 -1.000000 1.000000
v -1.000000 -1.000000 -1.000000
v 1.000000 -1.000000 -1.000000
v 1.000000 -1.000000 1.000000
v -1.000000 1.000000 1.000000
v -1.000000 1.000000 -1.000000
v 1.000000 1.000000 -1.000000
v 1.000000 1.000000 1.000000
vt 1.000000 0.000000
vt 0.000000 1.000000
vt 0.000000 0.000000
vt 1.000000 0.000000
vt 0.000000 1.000000
vt 0.000000 0.000000
vt 1.000000 0.000000
vt 0.000000 1.000000
vt 0.000000 0.000000
vt 1.000000 0.000000
vt 0.000000 1.000000
vt 0.000000 0.000000
vt 1.000000 0.000000
vt 0.000000 0.000000
vt 0.000000 1.000000
vt 1.000000 1.000000
vt 1.000000 1.000000
vt 1.000000 1.000000
vt 1.000000 1.000000
vt 1.000000 1.000000
vn -1.0000 0.0000 0.0000
vn 0.0000 0.0000 -1.0000
vn 1.0000 0.0000 0.0000
vn 0.0000 0.0000 1.0000
vn 0.0000 -1.0000 0.0000
vn 0.0000 1.0000 0.0000
usemtl Material
s off
f 6/1/1 1/2/1 5/3/1
f 7/4/2 2/5/2 6/6/2
f 8/7/3 3/8/3 7/9/3
f 5/10/4 4/11/4 8/12/4
f 2/13/5 4/11/5 1/14/5
f 7/4/6 5/15/6 8/12/6
f 6/1/1 2/16/1 1/2/1
f 7/4/2 3/17/2 2/5/2
f 8/7/3 4/18/3 3/8/3
f 5/10/4 1/19/4 4/11/4
f 2/13/5 3/17/5 4/11/5
f 7/4/6 6/20/6 5/15/6

这是我将纹理加载到 OpenGL 的方式:

unsigned char* localBuffer = stbi_load(filepath.c_str(), &this->width, &this->height, &this->bitsPerPixel, 4);

glGenTextures(1, &this->id);
glActiveTexture(GL_TEXTURE0 + this->slot);
glBindTexture(GL_TEXTURE_2D, this->id);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, this->width, this->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, localBuffer);
glBindTexture(GL_TEXTURE_2D, 0);

这里是顶点着色器:

layout (location = 0) in vec3 aPos;
layout (location = 1) in vec2 textureCoords;

out vec2 vTextureCoords;

uniform mat4 Mvp;

void main()
{
   vTextureCoords = textureCoords;
   gl_Position = Mvp * vec4(aPos, 1.0);
}

这是片段着色器:

out vec4 FragColor;

in vec2 vTextureCoords;

uniform sampler2D textureSlot;

void main()
{
    FragColor = texture(textureSlot, vTextureCoords);
} 

谁能告诉我我在这里做错了什么?

2 个答案:

答案 0 :(得分:1)

感谢@Sync,我发现解决方案是启用深度测试。

glEnable(GL_DEPTH_TEST);

答案 1 :(得分:1)

我遇到了一个非常相似的问题,但我使用的是 DirectX。原因是我没有设置深度模板缓冲区,所以像素深度值被它们首先绘制的任何顺序覆盖。检查以确保您在 OpenGL 中启用了一些等效的功能。