纹理

纹理坐标

float texCoords[] = {
		1.0f, 1.0f, //右上
		1.0f, 0.0f, //右下
		0.0f, 1.0f, //左上
		0.0f, 0.0f  //左下
	};

纹理环绕方式

把纹理坐标设置在(0,0)到(1,1)之外,会产生循环铺满

纹理过滤

邻近过滤:选择离纹理坐标最近的像素(默认)
线性过滤:线性插值

加载纹理

下载stb_image之后放到项目文件夹里,然后头文件

#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"

加载图片:

int width, height, nrChannels;
unsigned char *data = stbi_load("container.jpg", &width, &height, &nrChannels, 0);	//path
	if (data)
	{
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
		glGenerateMipmap(GL_TEXTURE_2D);
	}
	else
	{
		std::cout << "Failed to load texture" << std::endl;
	}

生成纹理

纹理也是ID引用的

glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);

然后在顶点上面加纹理坐标,加到最后之后

glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float)));
glEnableVertexAttribArray(2);

在顶点shader里面,加第三个layout

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

out vec4 color;
out vec2 TexCoord;

void main()
{
	gl_Position = vec4(aPos, 1.0f);
	color = vec4(aColor, 1.0f);
	TexCoord = aTexCoord;
}

片段着色器加uniform采样器

#version 330 core
in vec4 color;
in vec2 TexCoord;
out vec4 fragColor;
uniform sampler2D ourtexture;
void main()
{
	fragColor = texture(ourtexture, TexCoord) * color;
}

注意顶点坐标一定要仔细检查对应对,要不纹理会乱
一定要在加载图片之前glBindTexture与GL_TEXTURE_2D

纹理单元

一个纹理的默认纹理单元是0,它是默认的激活纹理单元
随后需要active并把这个纹理加入texture_2D里

glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture1);

然后说明哪个纹理对应哪个纹理单元:
ourShader.setInt("texture2", 1);
sampler传入的是一个int,也就是纹理单元几

posted @ 2022-08-22 16:51  IamIron-Man  阅读(217)  评论(0)    收藏  举报