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 盤或自行修改路徑。



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