GAMES101 作业 01:旋转与投影
作业 01 的实现代码:Assignment01
1. get_model_matrix
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.
float radian = rotation_angle * MY_PI / 180.0;
model <<
cos(radian), -sin(radian), 0.0, 0.0,
sin(radian), cos(radian), 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0;
return model;
}
2. get_projection_matrix
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.
// 构造透视投影到正交投影矩阵
Eigen::Matrix4f persp2ortho = Eigen::Matrix4f::Identity();
persp2ortho <<
zNear, 0.0, 0.0, 0.0,
0.0, zNear, 0.0, 0.0,
0.0, 0.0, zNear+zFar, -1.0 * zNear * zFar,
0.0, 0.0, 1.0, 0.0;
// 求出 frustum 的顶、底、左、右
float top = zNear * tan(eye_fov / 2 * MY_PI / 180.0);
float botton = -1.0 * top;
float right = aspect_ratio * top;
float left = -1.0 * right;
// 构造缩放 frustum 成为 2 * 2 * 2 的 cuboid 的矩阵
Eigen::Matrix4f ortho1 = Eigen::Matrix4f::Identity();
ortho1 <<
2.0 / (right - left), 0.0, 0.0, 0.0,
0.0, 2.0 / (top - botton), 0.0, 0.0,
0.0, 0.0, 2.0 / (zNear - zFar), 0.0,
0.0, 0.0, 0.0, 1.0;
// 构造平移 cuboid 的矩阵
Eigen::Matrix4f ortho2 = Eigen::Matrix4f::Identity();
ortho2 <<
1.0, 0.0, 0.0, -1.0 * (left + right) / 2.0,
0.0, 1.0, 0.0, -1.0 * (top + right) / 2.0,
0.0, 0.0, 1.0, -1.0 * (zNear + zFar) / 2.0,
0.0, 0.0, 0.0, 1.0;
projection = ortho2 * ortho1 * persp2ortho;
return projection;
}
3. get_rotation
Eigen::Matrix4f get_rotation(Vector3f axis, float angle) {
float radian = angle * MY_PI / 180.0;
Eigen::Matrix3f model1 = Eigen::Matrix3f::Identity();
model1 = cos(radian) * model1;
Eigen::Matrix3f model2 = Eigen::Matrix3f::Identity();
model2 = (1 - cos(radian)) * axis * axis.transpose();
Eigen::Matrix3f model3 = Eigen::Matrix3f::Identity();
model3 <<
0.0, -axis[2], axis[1],
axis[2], 0.0, -axis[0],
-axis[1], axis[0], 0.0;
model3 = sin(radian) * model3;
model3 = model1 + model2 + model3;
Eigen::Matrix4f model = Eigen::Matrix4f::Identity();
model <<
model3(0, 0), model3(0, 1), model3(0, 2), 0.0,
model3(1, 0), model3(1, 1), model3(1, 2), 0.0,
model3(2, 0), model3(2, 1), model3(2, 2), 0.0,
0.0, 0.0, 0.0, 1.0;
return model;
}
4. 运行结果