3-1 加载纹理

本文介绍了使用Qt与OpenGL实现的项目中,如何准备坐标VAO,配置着色器以关联纹理坐标,并通过stb_image加载和设置材质。重点讲解了顶点着色器和片段着色器的编写,以及如何使用glTexImage2D加载外部图片数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

本系列文章是以Qt + OpenGL方式完成的
本文参考视屏 链接

一、准备坐标VAO

  1. 每个顶点关联一个纹理坐标(texture coordinate),之后再图形的其他片段上进行差值(fragment interpolation)

  2. 我们需要告诉OpenGL该对纹理如何采样

  3. 样例VBO

float vertices[] = { 
    //坐标               color              texture coord
    0.5f,0.5f,0.0f,      1.0f,0.0f,0.0f,   1.0f,1.0f,  //右上
    0.5f,-0.5f,0.0f,     0.0f,1.0f,0.0f,   1.0f,0.0f,  //右下
    -0.5f,-0.5f,0.0f,    0.0f,0.0f,1.0f,   0.0f, 0.0f, //左下
    -0.5f,0.5f,0.0f,     1.0f,1.f,0.0f,    0.0f, 1.0f, //左上
};
  1. 设置VAO
    说明:
    有三个属性,所以需要调用三次glVertexAttribPointer
    glVertexAttribPointer(序号,几个,什么类型值,需要标准化吗,一行多少数据,本属性从几开始);
    对于VAO的理解参考:GLSL Layout
 		glVertexAttribPointer(1,3,GL_FLOAT,GL_FALSE,8*sizeof(float),(void*)0);
        glVertexAttribPointer(2,3,GL_FLOAT,GL_FALSE,8*sizeof(float),(void*)(3*sizeof(float)));
        glVertexAttribPointer(3,2,GL_FLOAT,GL_FALSE,8*sizeof(float),(void*)(6*sizeof(float)));
       
        glEnableVertexAttribArray(1);
        glEnableVertexAttribArray(2);
        glEnableVertexAttribArray(3);

二、 着色器

  1. 顶点着色器 shader
#version 330 core
layout(location=1) in vec3 aPos;
layout(location=2) in vec3 aColor;
layout(location=3) in vec2 aTextureCoord;

out vec4 ourcolor;
out vec2 texcoord;

void main()
{
  gl_Position = vec4(aPos.x,aPos.y,aPos.z,1.0f);
  //vertexColor = vec4(0.0f,1.0f,0.0f,1.0f);

  ourcolor = vec4(aColor.rgb,1.0f);

  texcoord = aTextureCoord;

};

  1. 片段着色器
#version 330 core
out vec4 FragColor;

in vec4 ourcolor;
in vec2 texcoord;
uniform sampler2D ourTexture;
void main()
{
    FragColor = texture2D (ourTexture,texcoord);
    //FragColor = texture2D (ourTexture,texcoord)*vec4(ourcolor.xxx,1.0f);
}

三 加载材质

  1. stb_image
    下载 链接

  2. 设置第0个texture

GLuint int texture;
glGenTexture(1,&texture);
glBindTexture(GL_TEXTURE_2D,texture);

//stb_image
int width,height,nrChannels;
unsigned char* data = stbi_load("container.jpg",&width,&height,&nrChannels,0);

//设置texture
if(data)
{
  glTexImage2D(GL_TEXTRUE_2D,0,GL_RGB,width,height,0,GL_RGB,GL_UNSIGNED_BYTE,data);
}

stbi_image_free(data);
  1. glTexImage2D
序号内容说明
1GL_TEXTRUE_2D2d材质
glTexImage2D 这个控制好几个槽
20多级材质,可以由近到远,指定不同级别的材质
3GL_RGB这个格式,指定转换到显卡内部材质的格式
这个格式就是openGL内部texture要保存的内部格式
4-5width,height宽/高
60边框
7-9GL_RGB,GL_UNSIGNED_BYTE,data描述外部加载来的data,这个data需要openGL函数能看懂
data通过stb加载而来,成了unsigned char,
这个data是RGB这种颜色格式
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值