计算机图形学(2)——OpenGL几何变换

给《计算机图形学基础(OpenGL版)》实验三示例代码贴上自己写的注释,唔,方便理解。

// CG_3_opengl几何变换.cpp : 定义控制台应用程序的入口点。

#include "stdafx.h"

#include 

 

void init(void)

{

glClearColor(1.0,1.0,1.0,1.0);

glMatrixMode(GL_PROJECTION);

gluOrtho2D(-5.0,5.0,-5.0,5.0);  //设置显示的范围是X:-5.0~5.0, Y:-5.0~5.0

glMatrixMode(GL_MODELVIEW);    //设置当前操作的矩阵为模型视图矩阵

}

void drawSquare(void)             //绘制中心在原点,边长为2的正方形

{

glBegin(GL_POLYGON);          //顶点指定需要按逆时针方向

glVertex2f(-1.0f,-1.0f);      //左下点

glVertex2f(1.0f,-1.0f);       //右下点

glVertex2f(1.0f,1.0f);        //右上点

glVertex2f(-1.0f,1.0f);       //左上点

glEnd();

}

 

void myDraw(void)

{

glClear(GL_COLOR_BUFFER_BIT);   //清空

glLoadIdentity();               //将当前矩阵设为单位矩阵

 

glPushMatrix();                  //保存矩阵,相当于把当前矩阵压进栈

glTranslatef(0.0f,2.0f,0.0f);   //平移矩阵构造函数

glScalef(3.0,0.5,1.0);          //缩放矩阵构造函数

glColor3f(1.0,0.0,0.0);

drawSquare();                   //上面红色矩形

glPopMatrix();                  //从栈顶弹出一个矩阵为当前矩阵

 

glPushMatrix();

glTranslatef(-3.0,0.0,0.0);

 

glPushMatrix();

glRotatef(45.0,0.0,0.0,1.0);    //旋转矩阵构造函数

glColor3f(0.0,1.0,0.0);

drawSquare();                   //中间左菱形

glPopMatrix();

 

glTranslatef(3.0,0.0,0.0);

 

glPushMatrix();

glRotatef(45.0,0.0,0.0,1.0);

glColor3f(0.0,0.7,0.0);

drawSquare();                   //中间中菱形

glPopMatrix();

 

glTranslatef(3.0,0.0,0.0);

 

glPushMatrix();

glRotatef(45.0,0.0,0.0,1.0);

glColor3f(0.0,0.4,0.0);

drawSquare();                   //中间右菱形

glPopMatrix();

 

glPopMatrix();

 

glTranslatef(0.0,-3.0,0.0);

glScalef(4.0,1.5,1.0);

glColor3f(0.0,0.0,1.0);

drawSquare();                   //下面蓝色矩形

 

glFlush();

}

 

void main(int argc, char** argv)

{

glutInit(&argc,argv);

glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);

glutInitWindowPosition(0,0);

glutInitWindowSize(600,600);

glutCreateWindow("几何变换示例");

 

init();

glutDisplayFunc(myDraw);

glutMainLoop();

}

运行结果如下:

计算机图形学(2)——OpenGL几何变换_第1张图片

实验提高(改一下上面的代码的myDraw()函数,绘制如下图形)
计算机图形学(2)——OpenGL几何变换_第2张图片
关键部分代码:

void myDraw(void)

{

glClear(GL_COLOR_BUFFER_BIT);   //清空

glLoadIdentity();               //将当前矩阵设为单位矩阵

 

glPushMatrix();

glTranslatef(-1.6,-1.0,0.0);

 

glPushMatrix();

glRotatef(30.0,0.0,0.0,1.0);

glColor3f(0.0,1.0,0.0);

drawDiamond();                   //左菱形

glPopMatrix();

 

glTranslatef(1.7,3.0,0.0);

 

glPushMatrix();

glRotatef(90.0,0.0,0.0,1.0);

glColor3f(1.0,0.0,0.0);

drawDiamond();                   //中间中菱形

glPopMatrix();

 

glTranslatef(1.7,-3.0,0.0);

 

glPushMatrix();

glRotatef(150.0,0.0,0.0,1.0);

glColor3f(0.0,0.0,1.0);

drawDiamond();                   //右菱形

glPopMatrix();

 

glPopMatrix();

 

glFlush();

}


你可能感兴趣的:(计算机图形学(2)——OpenGL几何变换)