openGL使用纹理贴图显示图片的时候,出现图片上下颠倒的情况,解决方案

在学习opengl纹理题图的时候,使用stb_image加载jpg文件,出现了图片显示出现颠倒的情况,如下图所示

出现这种情况的原因是,在默认的情况下。std_image是从图片的最后一行进行存储。  所以在显示图片的时候需要将图片进行翻转。

解决方案:

1. 翻转定点信息中的纹理图标

float vertices[] = {
        // positions          // colors           // texture coords
         0.5f,  0.5f, 0.0f,   1.0f, 0.0f, 0.0f,   1.0f, 1.0f, // top right
         0.5f, -0.5f, 0.0f,   0.0f, 1.0f, 0.0f,   1.0f, 0.0f, // bottom right
        -0.5f, -0.5f, 0.0f,   0.0f, 0.0f, 1.0f,   0.0f, 0.0f, // bottom left
        -0.5f,  0.5f, 0.0f,   1.0f, 1.0f, 0.0f,   0.0f, 1.0f  // top left 
    };
float vertices[] = {
        // positions          // colors           // texture coords
         0.5f,  0.5f, 0.0f,   1.0f, 0.0f, 0.0f,   1.0f, 1 - 1.0f, // top right
         0.5f, -0.5f, 0.0f,   0.0f, 1.0f, 0.0f,   1.0f, 1 - 0.0f, // bottom right
        -0.5f, -0.5f, 0.0f,   0.0f, 0.0f, 1.0f,   0.0f, 1 - 0.0f, // bottom left
        -0.5f,  0.5f, 0.0f,   1.0f, 1.0f, 0.0f,   0.0f, 1 - 1.0f  // top left 
    };

2.翻转顶点

#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aColor;
layout (location = 2) in vec2 aTexCoord;

out vec3 ourColor;
out vec2 TexCoord;

void main()
{
	gl_Position = vec4(aPos.x,aPos.y,aPos.z, 1.0);
	ourColor = aColor;
	TexCoord = vec2(aTexCoord.x, aTexCoord.y);
}
#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aColor;
layout (location = 2) in vec2 aTexCoord;

out vec3 ourColor;
out vec2 TexCoord;

void main()
{
	gl_Position = vec4(aPos.x,-aPos.y,aPos.z, 1.0);
	ourColor = aColor;
	TexCoord = vec2(aTexCoord.x, aTexCoord.y);
}

3.从第一行进行图片的存储

// @OPTIMIZE: use a bigger temp buffer and memcpy multiple pixels at once
        for (row = 0; row < (h >> 1); row++) {
            for (col = 0; col < w; col++) {
                for (z = 0; z < depth; z++) {
                    temp = result[(row * w + col) * depth + z];
                    result[(row * w + col) * depth + z] = result[((h - row - 1) * w + col) * depth + z];
                    result[((h - row - 1) * w + col) * depth + z] = temp;
                }
            }
        }

,最后一种方法在stb_image中已经进行了封装。我们只需要调用

stbi_set_flip_vertically_on_load(true);

这段代码就可以实现。

下图是翻转之后运行的结果

猜你喜欢

转载自blog.csdn.net/qq_15024587/article/details/88639267
今日推荐