Image loaded from TGA texture isn't displayed correctly

Posted by Ramy Al Zuhouri on Game Development See other posts from Game Development or by Ramy Al Zuhouri
Published on 2012-12-12T18:49:29Z Indexed on 2012/12/12 23:22 UTC
Read the original article Hit count: 250

Filed under:
|
|

I have a TGA texture containing this image:

enter image description here

The texture is 256x256. So I'm trying to load it and map it to a cube:

#import <OpenGL/OpenGL.h>
#import <GLUT/GLUT.h>
#import <stdlib.h>
#import <stdio.h>
#import <assert.h>


GLuint width=640, height=480;
GLuint texture;
const char* const filename= "/Users/ramy/Documents/C/OpenGL/Test/Test/texture.tga";




void init()
{

    // Initialization

    glEnable(GL_DEPTH_TEST);
    glViewport(-500, -500, 1000, 1000);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(45, width/(float)height, 1, 1000);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    gluLookAt(0, 0, -100, 0, 0, 0, 0, 1, 0);

    // Texture

    char bitmap[256][256][3];
    FILE* fp=fopen(filename, "r");
    assert(fp);
    assert(fread(bitmap, 3*sizeof(char), 256*256, fp) == 256*256);
    fclose(fp);

    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 256, 256, 0, GL_RGB, GL_UNSIGNED_BYTE, bitmap);

}


void display()
{
    glClearColor(0, 0, 0, 0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, texture);
    glColor3ub(255, 255, 255);

    glBegin(GL_QUADS);
    glVertex3f(0, 0, 0);
    glTexCoord2f(0.0, 0.0);

    glVertex3f(40, 0, 0);
    glTexCoord2f(0.0, 1.0);

    glVertex3f(40, 40, 0);
    glTexCoord2f(1.0, 1.0);

    glVertex3f(0, 40, 0);
    glTexCoord2f(1.0, 0.0);

    glEnd();

    glDisable(GL_TEXTURE_2D);
    glutSwapBuffers();
}


int main(int argc, char** argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
    glutInitWindowPosition(100, 100);
    glutInitWindowSize(width, height);
    glutCreateWindow(argv[0]);
    glutDisplayFunc(display);
    init();
    glutMainLoop();
    return 0;
}

But this is what I get when the window loads:

enter image description here

So just half of the image is correctly displayed, and also with different colors.Then if I resize the window I get this:

enter image description here

Magically the image seems to fix itself, even if the colors are wrong.Why?

© Game Development or respective owner

Related posts about opengl

Related posts about textures