纹理常用API简介

2022-12-19  本文已影响0人  buding_

1. 读取文件

GLbyte *gltReadTGABits(const char *szFileName, GLint *iWidth, GLint *iHeight, GLint *iComponents, GLenum *eFormat, GLbyte *pData = NULL);

2. 载入纹理

void glTexImage2D(GLenum target,GLint level,GLint internalformat,GLsi
zei width,GLsizei height,GLint border,GLenum format,GLenum type,void 
* data);
*target: GL_TXTURE_2D
*level: 指定加载的mip贴图层次,一般设置为0
*internalformat: 每个纹理单元中存储多少颜色成分
*width、height、depth: 指加载纹理的宽度、高度、深度;习惯使用2的整数次方去设置
*border: 允许纹理贴图指定一个边界宽度
*format、type、data: 

3. 纹理对象

//使用函数分配纹理对象
void glGenTextures(GLsizei n,GLuint * textTures);

//绑定纹理状态
void glBindTexture(GLenum target,GLunit texture);

//删除纹理对象
void glDeleteTextures(GLsizei n,GLuint *textures);

//测试纹理对象是否有效
GLboolean glIsTexture(GLuint texture);
//设置纹理相关参数 【重点】
//放大/缩小过滤(临近过滤/线性过滤)
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);

//设置x/y轴上的环绕方式
// (x,y,z,w) - > (s,t,r,q)
glTextParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAR_S,GL_CLAMP_TO_EDGE);
glTextParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAR_T,GL_CLAMP_TO_EDGE);
环绕方式参数.png
环绕方式效果图.png

4. 例子

// 将TGA文件加载为2D纹理
bool loadTGATexture(const char *szFileName, GLenum minFilter, GLenum magFilter, GLenum wrapMode) {
    GLbyte *pBits;
    int nWidth, nHeight, nComponents;
    GLenum eFormat;
    //1 读取纹理,读取像素
    //参数1:纹理文件名称
    //参数2:文件宽度地址
    //参数3:文件高度地址
    //参数4:文件组件地址
    //参数5:文件格式地址
    //返回值:pBits,指向图像数据的指针
    pBits = gltReadTGABits(szFileName, &nWidth, &nHeight, &nComponents, &eFormat);
    if (pBits == NULL) {
        return false;
    }
    
    //2 设置纹理参数
    //参数1:纹理维度
    //参数2:为S/T坐标设置模式
    //参数3:wrapMode,环绕模式
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapMode);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapMode);
    
    //参数1:纹理维度
    //参数2:线性过滤
    //参数3:wrapMode,环绕模式
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilter);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magFilter);
    
    
    //3.载入纹理
    //参数1:纹理维度
    //参数2:mip贴图层次
    //参数3:纹理单元存储的颜色成分(从读取像素图是获得)
    //参数4:加载纹理宽
    //参数5:加载纹理高
    //参数6:加载纹理的深度
    //参数7:像素数据的数据类型(GL_UNSIGNED_BYTE,每个颜色分量都是一个8位无符号整数)
    //参数8:指向纹理图像数据的指针
    glTexImage2D(GL_TEXTURE_2D, 0, nComponents, nWidth, nHeight, 0, eFormat, GL_UNSIGNED_BYTE, pBits);
    
    //使用完毕释放pBits
    free(pBits);
    
    //4.加载Mip,纹理生成所有的Mip层
    //参数:GL_TEXTURE_1D、GL_TEXTURE_2D、GL_TEXTURE_3D
    glGenerateMipmap(GL_TEXTURE_2D);
    
    return true;
    
}

上一篇 下一篇

猜你喜欢

热点阅读