应用OpenGL和GLUT制作动画

应用OpenGL和GLUT制作动画

效果

clip_image002

clip_image004

clip_image006

代码

 

/*
 * File:   bounce.c
 * Author: leo
 *
 * Using  GLUT  for OpenGL program
 *
 *使用GLUT来演示一个动画
 */
 
#include <stdio.h>
#include <stdlib.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
 
//初始化正方形的位置和大小
GLfloat x1 = 100.0f;
GLfloat y1 = 150.0f;
GLsizei rsize = 50;
 
//设置移动的步进大小
GLfloat xstep = 1.0f;
GLfloat ystep = 1.0f;
 
//记录改变的窗口宽度和高度
GLfloat windowWidth;
GLfloat windowHeight;
 
//called to draw scene
void RenderScene(void)
{
    //使用当前的清除色清除窗口
    glClear(GL_COLOR_BUFFER_BIT);
    //设置以后绘制的颜色为红色
    glColor3f(1.0f,0.0f,0.0f);
    //使用当前色绘制一个填充的矩形
    glRectf(x1,y1,x1+rsize,y1+rsize);
    //flush drawing commands and swap
    glutSwapBuffers();//在执行缓冲区交换时,隐含执行了一次刷新操作
}
 
//当窗口idle时,调用此函数
void TimerFunction(int value)
{
    //当到达左右边缘时,反向移动
    if(x1 > windowWidth-rsize || x1 < 0)
        xstep = -xstep;
    //当到达上下边缘时,反向移动
    if(y1 > windowHeight-rsize || y1 < 0)
        ystep = -ystep;
 
    //check bounds. This is in case the window is made
    //smaller and the rectangle is outside the new
    //clipping volume
    if(x1 > windowWidth - rsize)
            x1 = windowWidth - rsize -1;
    if(y1 > windowHeight - rsize)
            y1 = windowHeight - rsize -1;
 
    //actually move the square
    x1 += xstep;
    y1 += ystep;
 
    //使用新的坐标重绘场景
    glutPostRedisplay();
    glutTimerFunc(33,TimerFunction,1);
}
 
 
//set up the rendering state
void SetupRC(void)
{
    glClearColor(0.0f,0.0f,1.0f,1.0f);
}
 
//called by GLUT library when the window has changed size
void ChangeSize(GLsizei w, GLsizei h)
{
    //prevent a divide by zero
    if(h == 0)
        h = 1;
    //set viewport to window dimensions
    glViewport(0,0,w,h);
 
    //reset coordinate system
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();//在每次进行任何矩阵处理之前都“复位”坐标系
 
    //keep the square ; this time ,save calculated
    //width and height for later user
    if(w <= h)
    {
        windowHeight = 250.f*h/w;
        windowWidth = 250.0f;
    }
    else
    {
        windowHeight = 250.f*w/h;
        windowWidth = 250.0f;
    }
//set the clipping volume
    glOrtho(0.0f,windowWidth,0.0f,windowHeight,1.0f,-1.0f);
 
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}
 
int main(int argc, char** argv) {
    glutInit(&argc,argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);//绘图代码都在画面外缓冲区进行渲染
    //双缓冲可以使得反弹矩阵的移动很光滑,单模式下就有些粗糙。
    glutCreateWindow("Bounce Rect. using GLUT");
    glutDisplayFunc(RenderScene);
    glutReshapeFunc(ChangeSize);//窗口大小发生变化,就重新设置坐标系
    glutTimerFunc(33,TimerFunction,1);
 
    SetupRC();
 
    glutMainLoop();
 
    return (EXIT_SUCCESS);
}
posted @ 2011-08-23 11:14  郭—大—侠  阅读(441)  评论(0编辑  收藏  举报