Wednesday, July 6, 2011

Turn On and Off the Light

//code for include glut header  goes here

void createcube(float,float,float); //function declaration

void display()
{
    //clearing
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //set type of display and depth color
    glEnable(GL_DEPTH_TEST);

    gluLookAt(-3,2,-10,0,0,0,0,2,0);

    createcube(-2,0,0);
    createcube(2,0,0);
    createcube(2,0,0);
    createcube(0,0,2);
    createcube(-2,0,0);
    createcube(-2,0,0);
       
    glutSwapBuffers();
    glLoadIdentity();
}

void createcube(float x, float y, float z)
{
    glTranslatef(x,y,z);
    glutSolidCube(1);   
}

void reshape(int w, int h)
{
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glViewport(0,0,w,h);
    gluPerspective(45,1,0.1,1000);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

void keypress(unsigned char key, int x, int y)
{
    //int mod;

    //mod=glutGetModifiers();
    if (key == 27) {exit(0); }
    if (key == 'a')
    {
        //prepare lighting
        glEnable(GL_LIGHTING);
        glEnable(GL_LIGHT0);

        //light position
        GLfloat lightpos[]={-2,3,-3,1};
        glLightfv(GL_LIGHT0, GL_POSITION, lightpos);

        //light color
        GLfloat lightcolor[]={1,1,0};
        glLightfv(GL_LIGHT0, GL_DIFFUSE, lightcolor);
       
        //light ambient
        GLfloat ambcolor[]={1.5,0.8,0.4};
        glLightfv(GL_LIGHT0, GL_AMBIENT, ambcolor);
    }
    glutPostRedisplay();
    else if (key == 's')
    {
        glDisable(GL_LIGHT0);       
    }
    glutPostRedisplay();
    else if (key == 'd')
    {
        //change color   
        //prepare lighting
        glEnable(GL_LIGHTING);
        glEnable(GL_LIGHT0);

        //light position
        GLfloat lightpos[]={-2,3,-3,1};
        glLightfv(GL_LIGHT0, GL_POSITION, lightpos);

        //light color
        GLfloat lightcolor[]={0,0,1};
        glLightfv(GL_LIGHT0, GL_DIFFUSE, lightcolor);
       
        //light ambient
        GLfloat ambcolor[]={0,0.8,0.4};
        glLightfv(GL_LIGHT0, GL_AMBIENT, ambcolor);
    }
    glutPostRedisplay();
   
}


int main(int argc, char **argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH);

    glutInitWindowPosition(100,100);
    glutInitWindowSize(500,500);
    glutCreateWindow("Exercise 1 Lighting");

    glutDisplayFunc(display);
    glutReshapeFunc(reshape);
    glutKeyboardFunc(keypress);
   
    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...