Introduce perspective projection matrix.

Also correct a bug where the view matrix was not being used.
This commit is contained in:
2020-10-13 10:57:30 -04:00
parent 49927568e4
commit 6ff09dc375
3 changed files with 30 additions and 5 deletions

View File

@@ -27,8 +27,8 @@ using mat3 = mat<3>;
using mat4 = mat<4>; using mat4 = mat<4>;
using mat5 = mat<5>; using mat5 = mat<5>;
mat4 ortho(float left, float right, float bottom, float top, float front, float back) { mat4 orthographic(float left, float right, float bottom, float top, float front, float back) {
mat<4> res = mat4(); mat4 res = mat4();
res << res <<
2 / (right - left), 0, 0, -(right + left) / (right - left), 2 / (right - left), 0, 0, -(right + left) / (right - left),
0, 2 / (top - bottom), 0, -(top + bottom) / (top - bottom), 0, 2 / (top - bottom), 0, -(top + bottom) / (top - bottom),
@@ -36,3 +36,25 @@ mat4 ortho(float left, float right, float bottom, float top, float front, float
0, 0, 0, 1; 0, 0, 0, 1;
return res; return res;
} }
mat4 perspective(float fovy, float aspect, float zNear, float zFar) {
float tanHalfFovy(std::tan(fovy / 2));
mat4 res = mat4::Identity();
res(0, 0) = 1 / (aspect * tanHalfFovy);
res(1, 1) = 1 / (tanHalfFovy);
res(2, 2) = -(zFar + zNear) / (zFar - zNear);
res(3, 2) = -1;
res(2, 3) = -(2 + zFar * zNear) / (zFar - zNear);
return res;
}
mat4 translation(float x, float y, float z) {
mat4 res = mat4();
res <<
1, 0, 0, x,
0, 1, 0, y,
0, 0, 1, z,
0, 0, 0, 1;
return res;
}

View File

@@ -19,9 +19,12 @@ struct Matrices {
auto aspect = (float) screen.width() / (float) screen.height(); auto aspect = (float) screen.width() / (float) screen.height();
auto pheight = 1.4f; auto pheight = 1.4f;
auto pwidth = aspect * pheight; auto pwidth = aspect * pheight;
mat4 proj = ortho(-pwidth, pwidth, -pheight, pheight, -10.0f, 10.0f); // auto proj = orthographic(-pwidth, pwidth, -pheight, pheight, -10.0f, 10.0f);
// auto proj = perspective(-pwidth, pwidth, pheight, -pheight, 10.0f, 0.01f);
auto proj = perspective(0.4, aspect, 0.1, 10.0);
auto view = translation(0, 0, -4);
auto view = mat4::Identity();
return Matrices(proj, view); return Matrices(proj, view);
} }
}; };

View File

@@ -30,7 +30,7 @@ float unmix(float u, float v) {
void emit(vec4 v) { void emit(vec4 v) {
pos = v; pos = v;
col = vCol[0]; col = vCol[0];
gl_Position = proj * vec4(v.xyz, 1); gl_Position = proj * view * vec4(v.xyz, 1);
EmitVertex(); EmitVertex();
} }