openGL 纹理贴图
时间: 2023-12-11 14:31:51 浏览: 92
OpenGL纹理贴图是将一张图片贴到3D模型表面的过程。具体步骤如下:
1. 生成OpenGL纹理对象
```c++
GLuint textureID;
glGenTextures(1, &textureID);
```
2. 绑定纹理对象
```c++
glBindTexture(GL_TEXTURE_2D, textureID);
```
3. 加载纹理图片
```c++
int width, height, nrChannels;
unsigned char *data = stbi_load("texture.jpg", &width, &height, &nrChannels, 0);
```
4. 将纹理图片数据传递给OpenGL
```c++
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
```
5. 设置纹理参数
```c++
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
```
6. 清除纹理图片数据
```c++
stbi_image_free(data);
```
7. 在渲染循环中绑定纹理对象并启用纹理
```c++
glBindTexture(GL_TEXTURE_2D, textureID);
glEnable(GL_TEXTURE_2D);
```
8. 在绘制3D模型时,将纹理坐标传递给顶点着色器
```c++
glVertexAttribPointer(texCoordLocation, 2, GL_FLOAT, GL_FALSE, 0, texCoords);
glEnableVertexAttribArray(texCoordLocation);
```
9. 在片段着色器中使用纹理坐标和纹理采样器
```c++
uniform sampler2D textureSampler;
...
vec4 textureColor = texture(textureSampler, texCoord);
```
阅读全文