实验四:(2学时)
一、 实验目的:
掌握几何变换的原理,尤其是复合变换
二、 实验内容:
1、利用OpenGL函数画一个三维物体;
2、运用齐次坐标,采用矩阵相乘的方式自己编程实现几何变换,不能直接调用OpenGL几何变换函数;
3、利用鼠标或键盘控制三维物体在屏幕上移动、旋转和放缩;
三、 实现效果及步骤(或流程)
1、利用OpenGL函数画一个三维物体;
实现方法:
(1)初始化时给八个坐标,坐标之间两两相连画线,代码如下:
// 将立方体的八个顶点保存到一个数组里面
static float vertex_list[][3] =
{
-0.5f, -0.5f, -0.5f,
0.5f, -0.5f, -0.5f,
-0.5f, 0.5f, -0.5f,
0.5f, 0.5f, -0.5f,
-0.5f, -0.5f, 0.5f,
0.5f, -0.5f, 0.5f,
-0.5f, 0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
};
// 将要使用的顶点的序号保存到一个数组里面
static const GLint index_list[][2] =
{
{ 0, 1 },
{ 2, 3 },
{ 4, 5 },
{ 6, 7 },
{ 0, 2 },
{ 1, 3 },
{ 4, 6 },
{ 5, 7 },
{ 0, 4 },
{ 1, 5 },
{ 7, 3 },
{ 2, 6 }
};
//绘制立方体
void DrawCube(void)
{
int i, j;
glBegin(GL_LINES);
for (i = 0; i < 12; ++i) // 12 条线段
{
for (j = 0; j < 2; ++j) // 每条线段 2个顶点
{
glVertex3fv(vertex_list[index_list[i][j]]);
}
}
glEnd();
}
2、运用齐次坐标,采用矩阵相乘的方式自己编程实现几何变换,不能直接调用OpenGL几何变换函数;
实现方法:
(1)移动函数:
typedef GLfloat Matrix4x4[4][4];
void matrix4x4SetIdentity(Matrix4x4 matIdent4x4) {
GLint row, col;
for (row = 0; row < 4; row++)
for (col = 0; col < 4; col++) matIdent4x4[row][col] = (row == col);
}
//自定义平移函数
void translate3D(GLfloat tx, GLfloat ty, GLfloat tz) {
Matrix4x4 matTransl3D;
matrix4x4SetIdentity(matTransl3D);
matTransl3D[0][3] = tx;
matTransl3D[1][3] = ty;
matTransl3D[2][3] = tz;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 3; j++)
{
vertex_list[i][j] += matTransl3D[j][3];
}
}
}
(2)旋转函数:
typedef GLfloat Matrix4x4[4][4];
void matrix4x4SetIdentity(Matrix4x4 matIdent4x4) {
GLint row, col;
for (row = 0; row < 4; row++)
for (col = 0; col < 4; col++) matIdent4x4[row][col] = (row == col);
}
//自定义旋转函数
void rotate3D(GLfloat e, GLfloat rx, GLfloat ry, GLfloat rz)
{
Matrix4x4 matRotate3D;
m