1 model矩阵编写

首先我是写了一个函数,作为角度值转弧度制

1
2
3
4
5
// degree to radian
float deg_to_rad(float angle)
{
return angle * MY_PI / 180.0;
}

接着直接按照定义写出即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Eigen::Matrix4f get_model_matrix(float rotation_angle)
{
Eigen::Matrix4f model = Eigen::Matrix4f::Identity();

// TODO: Implement this function
// Create the model matrix for rotating the triangle around the Z axis.
// Then return it.
Eigen::Matrix4f translate;
translate << cos(deg_to_rad(rotation_angle)), -sin(deg_to_rad(rotation_angle)), 0, 0,
sin(deg_to_rad(rotation_angle)), cos(deg_to_rad(rotation_angle)), 0, 0,
0, 0, 1, 0,
0, 0, 0, 1;

model = translate * model;

return model;
}

2 透视投影矩阵编写

传入的四个参数分别为:

  • fov角度
  • aspect宽比高
  • 近平面和远屏幕的z值

我们只需使用上面参数求出l, r, b, t即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
Eigen::Matrix4f get_projection_matrix(float eye_fov, float aspect_ratio,
float zNear, float zFar)
{
// Students will implement this function

Eigen::Matrix4f projection = Eigen::Matrix4f::Identity();

// TODO: Implement this function
// Create the projection matrix for the given parameters.
// Then return it.

// 先做透视投影变换再做正交投影变换,我们要根据fov和aspect求出l,r,t,b

Eigen::Matrix4f persp_to_ortho;
persp_to_ortho << zNear, 0, 0, 0,
0, zNear, 0, 0,
0, 0, zNear + zFar, -zNear * zFar,
0, 0, 1, 0;

float tan_half_fov = tan(deg_to_rad(eye_fov / 2));
float top = tan_half_fov * zNear;
float bottom = -top;
float right = top * aspect_ratio;
float left = -right;

Eigen::Matrix4f ortho_scale, ortho_translate;
ortho_scale << 2 / (right - left), 0, 0, 0,
0, 2 / (top - bottom), 0, 0,
0, 0, 2 / (zNear - zFar), 0,
0, 0, 0, 1;

ortho_translate << 1, 0, 0, -(right + left) / 2,
0, 1, 0, -(top + bottom) / 2,
0, 0, 1, -(zNear + zFar) / 2,
0, 0, 0, 1;

projection = ortho_scale * ortho_translate * persp_to_ortho;

return projection;
}

此时我们必要的工作已经完成了

3 [Optional]绕任意轴旋转角度的实现

直接套入罗德里格斯公式即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Eigen::Matrix4f get_rotation(Vector3f axis, float angle)
{
Eigen::Matrix4f model = Eigen::Matrix4f::Identity();
Eigen::Matrix3f identity = Eigen::Matrix3f::Identity();

auto angle_rad = deg_to_rad(angle);
Eigen::Matrix3f r, t;

t << 0, -axis[2], axis[1],
axis[2], 0, -axis[0],
-axis[1], axis[0], 0;

r = cos(angle_rad) * identity + (1 - cos(angle_rad)) * axis * axis.adjoint() + sin(angle_rad) * t;

model << r(0, 0), r(0, 1), r(0, 2), 0,
r(1, 0), r(1, 1), r(1, 2), 0,
r(2, 0), r(2, 1), r(2, 2), 0,
0, 0, 0, 1;

return model;
}

作业源码仓库: https://github.com/00nico00/GAMES101-Homework-record/tree/main/Assignment1