图形变换是计算机图形学中的重要内容,大体上又可以分为三类:几何变换、坐标变换和显示变化。
以下为图形变换流程:
其中比较常用的基本几何变换有平移(glTranslationf)、缩放(glScalef)和旋转(glRotatef)等,其中旋转与平移组合又可以形成公转或自转的效果,即旋转点不同。
以下是关于OpenGL基本几何变换实验的程序(以nehe OpenGL为整体框架)部分关键代码,其完成了窗口中绘制一个四面体,并使其左右平移、周期旋转和缩放。
//定义以下变量控制对象的运动(即在窗口中绘制的位置)
GLfloat rtri=0.0f; //旋转角度
GLfloat i=0.0f; //缩放比例
GLfloat x=0.0f; //临时变量
GLfloat y=0.0f; //对象沿x轴平移的位置变量
GLfloat z=0.0f; //临时变量
int DrawGLScene(GLvoid) //用于窗口绘制的函数
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glTranslatef(0.0,0.0f,-10.0f); //将绘制起点向屏幕里平移10个单位,保证最后能够看清整个四面体
glTranslatef(y,0.0f,0.0f); //平移函数用于控制四面体的移动,这里的变量y的值影响对象在x轴方向上平移
glScalef(i,i,i); //缩放函数,参数均为i表示在各个方向上等量缩放,其值也可不相同
glRotatef(rtri,0.0f,1.0f,0.0f); // 旋转函数,表示在y方向上进行旋转,rtri表示旋转的角度
glBegin(GL_TRIANGLES); //开始绘制四面体
glColor3f(1.0f,0.0f,0.0f);
glVertex3f( 0.0f, 1.0f, 0.0f);
glColor3f(0.0f,1.0f,0.0f);
glVertex3f(-1.0f,-1.0f, 1.0f);
glColor3f(0.0f,0.0f,1.0f);
glVertex3f( 1.0f,-1.0f, 1.0f);
glColor3f(1.0f,0.0f,0.0f);
glVertex3f( 0.0f, 1.0f, 0.0f);
glColor3f(0.0f,0.0f,1.0f);
glVertex3f( 1.0f,-1.0f, 1.0f);
glColor3f(0.0f,1.0f,0.0f);
glVertex3f( 1.0f,-1.0f, -1.0f);
glColor3f(1.0f,0.0f,0.0f);
glVertex3f( 0.0f, 1.0f, 0.0f);
glColor3f(0.0f,1.0f,0.0f);
glVertex3f( 1.0f,-1.0f, -1.0f);
glColor3f(0.0f,0.0f,1.0f);
glVertex3f(-1.0f,-1.0f, -1.0f);
glColor3f(1.0f,0.0f,0.0f);
glVertex3f( 0.0f, 1.0f, 0.0f);
glColor3f(0.0f,0.0f,1.0f);
glVertex3f(-1.0f,-1.0f,-1.0f);
glColor3f(0.0f,1.0f,0.0f);
glVertex3f(-1.0f,-1.0f, 1.0f);
glEnd();
//将控制平移、选择、缩放的变量进行操作,使得每次渲染时四面体的位置方向有所变化
rtri+=0.2f; //旋转角度自加0.2
x+=0.01f;
i=1+0.5*sin(x); //控制缩放的比例,利用三角函数的值域控制会循环放大缩小,而不是无限放大或无限缩小。当然这部分的实现也可以利用if语句控制放大还是缩小
z+=0.01f;
y=5*sin(z); //控制平移后的位置,利用三角函数保证不会出界,而是在一定的范围内来回运动
return TRUE;
}
以下为该程序运行时的截图: