OpenGL载入DDS压缩纹理

网络上的图像库很多,如 FreeImage Devil 等,库很强大且支持多种格式,当然也包括 DDS 纹理。例如 FreeImage ,但是它这里所说的支持 DDS 格式是指将压缩格式的数据重新解压成 RGBA 像素数据,将数据解压后再绑定到 OpenGL 中就失去了其作为压缩纹理的高效性(因 OpenGL 直接支持此压缩纹理数据)。 FreeImage 作者建议参考 Ogre DDS 纹理载入实现,但那部分实现与 Ogre 切合太紧不便 Ogre 之外应用,需要的是一个方便的压缩纹理绑定函数。多方查找后发现 Nvidia 的一个小类库 nv_dds 挺好用的,就把它封装了一下,附上源码 (可根据实际需要扩充功能)。

/** DDS 纹理绑定函数

  * @param[in] filePath 纹理路径

  * @param[out] texID 纹理 ID

  * @return 数据信息

  * - 0 打开失败

  * - 1 RGB 格式

  * - 2 RGBA 格式

  */

unsigned BuildDDS (char *filePath , unsigned &texID )

{

    nv_dds ::CDDSImage image ;

    if (!image .load (string (filePath )))

    {

        return 0;

    }

 

    glGenTextures (1, &texID );

    glEnable (GL_TEXTURE_2D );

    glBindTexture (GL_TEXTURE_2D , texID );

 

    glCompressedTexImage2D (GL_TEXTURE_2D , 0, image .get_format (),

        image .get_width (), image .get_height (), 0, image .get_size (), image );

 

    for (int i = 0; i < image .get_num_mipmaps (); i ++)

    {

        glCompressedTexImage2D (GL_TEXTURE_2D , i +1, image .get_format (),

            image .get_mipmap (i ).get_width (), image .get_mipmap (i ).get_height (), 0,

            image .get_mipmap (i ).get_size (), image .get_mipmap (i ));

    }

    return image .get_components () < 4 ? 1 : 2;

}

源码中使用到了 glext.h 头文件、 glut glew 两个 OpenGL 相关库,需自行添加到 VC2010 的相关目录中,同时将 dds 纹理置于 C 盘或自行修改路径。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章