Thursday, July 7, 2011

Mapping Texture (Raw image) into Object

//fstream declaration
//glut header declaration

GLuint texture; //as global variable

//function only works for RAW format image
GLuint loadtex(const char *filename, int w, int h)  //unasigned integer
{
    GLuint tex;
    FILE *file;
    unsigned char *data;
   
    file=fopen(filename,"rb");
    if(file==NULL) return 0;
   
    //preparation
    data=(unsigned char *)malloc(w*h*3);
    fread(data,w*h*3,1,file);
    fclose(file);

    //generate texture name
    glGenTextures(1,&tex);
    glBindTexture(GL_TEXTURE_2D,tex);

    //texture environment
    glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_MODULATE);

    //set texture environment parameters
    glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT);
    glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT);

    //connect data to GL_TEXTURE_2D
    glTexImage2D(GL_TEXTURE_2D,0,GL_RGB,w,h,0,GL_RGB,GL_UNSIGNED_BYTE,data);
    free(data);

    return tex;
}

void renderscene()
{
    glClear(GL_COLOR_BUFFER_BIT);
    glLoadIdentity();
    gluLookAt(0,0,-3,0,0,0,0,1,0);

    //enable
    glEnable(GL_TEXTURE_2D); //activate the texture
    glBindTexture(GL_TEXTURE_2D,texture);  //bind the texture   

    //do something
    glBegin(GL_QUADS);
        glTexCoord2f(0,0);
        glVertex2f(0,0);
        glTexCoord2f(1,0);
        glVertex2f(1,0);
        glTexCoord2f(1,1);
        glVertex2f(1,1);
        glTexCoord2f(0,1);
        glVertex2f(0,1);
    glEnd();
    glutSwapBuffers();
}

void reshape(int w, int h)
{
    glViewport(0,0,(GLsizei)w,(GLsizei)h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(60,(GLfloat)w/(GLfloat)h,1.0,100.0);
    glMatrixMode(GL_MODELVIEW);   
    glLoadIdentity();
}

void keypress(unsigned char key, int x, int y)
{
    if(key==27) exit(0);
}

int main(int argc, char **argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
    glutInitWindowPosition(200,200);
    glutInitWindowSize(500,500);
    glutCreateWindow("Texture Example");
   
    glutDisplayFunc(renderscene);
    glutReshapeFunc(reshape);   
    glutKeyboardFunc(keypress);   

    texture=loadtex("texture.raw",256,256);
    glutMainLoop();
    glDeleteTextures(1,&texture); //reclean the memory and under glutMainLoop()
    return(0);
}

No comments:

Post a Comment

Question 1: Introduction to Variable

Based on code below, create a dynamic program that solve problem below: Source Code: #include <iostream> using na...