2013-02-27 64 views
0

這是我的代碼加載紋理。我試圖用這個例子加載一個文件;它是一個gif文件。我可以問一下gif文件是否可以加載,還是隻有原始文件可以加載?OpenGL紋理搞砸了

void setUpTextures() 
{ 

    printf("Set up Textures\n"); 
    //This is the array that will contain the image color information. 
    // 3 represents red, green and blue color info. 
    // 512 is the height and width of texture. 
    unsigned char earth[512 * 512 * 3]; 

    // This opens your image file. 
    FILE* f = fopen("/Users/Raaj/Desktop/earth.gif", "r"); 
    if (f){ 
     printf("file loaded\n"); 
    }else{ 
     printf("no load\n"); 
     fclose(f); 
     return; 
    } 

    fread(earth, 512 * 512 * 3, 1, f); 
    fclose(f); 


    glEnable(GL_TEXTURE_2D); 

    //Here 1 is the texture id 
    //The texture id is different for each texture (duh?) 
    glBindTexture(GL_TEXTURE_2D, 1); 
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); 
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); 
    //In this line you only supply the last argument which is your color info array, 
    //and the dimensions of the texture (512) 
    glTexImage2D(GL_TEXTURE_2D, 0, 3, 512, 512, 0, GL_RGB, GL_UNSIGNED_BYTE,earth); 

    glDisable(GL_TEXTURE_2D); 
} 


void Draw() 
{ 

    glEnable(GL_TEXTURE_2D); 
    // Here you specify WHICH texture you will bind to your coordinates. 
    glBindTexture(GL_TEXTURE_2D,1); 
    glColor3f(1,1,1); 


    double n=6; 
    glBegin(GL_QUADS); 
    glTexCoord2d(0,50);  glVertex2f(n/2, n/2); 
    glTexCoord2d(50,0);  glVertex2f(n/2, -n/2); 
    glTexCoord2d(50,50); glVertex2f(-n/2, -n/2); 
    glTexCoord2d(0,50);  glVertex2f(-n/2, n/2); 
    glEnd(); 
    // Do not forget this line, as then the rest of the colors in your 
    // Program will get messed up!!! 
    glDisable(GL_TEXTURE_2D); 
} 

而且我得到的是這樣的: enter image description here

我能知道爲什麼嗎?

+3

'GL_TEXTURE_2D,0,3'無論你從哪裏複製此代碼,***停止閱讀它***。使用「3」作爲[內部格式](http://www.opengl.org/wiki/Image_Formats)是非常糟糕的OpenGL實踐。你不應該遵循任何使用它的編碼例子。 – 2013-02-27 12:20:23

+0

你知道,那紋理看起來很酷! – 2013-02-27 13:37:33

+0

@NicolBolas:或者這是一個非常過時的教程,覆蓋OpenGL-1.0(注意。零),格式參數確實是組件的數量。格式令牌是在OpenGL-1.1中引入的 – datenwolf 2013-02-27 14:45:09

回答

5

基本上,不,你不能只給GL任意紋理格式 - 它只需要像素數據,而不是編碼文件。

您發佈的代碼清楚地聲明瞭24位RGB數據的數組,但隨後您打開並嘗試從GIF文件讀取大量數據。 GIF是一種壓縮和格式化的格式,包含標題信息等,所以這絕不會奏效。

您需要使用圖像加載器將文件解壓縮爲原始像素。

此外,您的紋理座標看起來不正確。有四個頂點,但只使用3個不同的座標,並且2個相鄰的座標彼此對角相對。即使你的紋理加載正確,這可能不是你想要的。