From b9c013e6651134b26c969f25bd56f33aeca0ce85 Mon Sep 17 00:00:00 2001 From: Sam Hocevar Date: Wed, 16 Feb 2011 18:04:08 +0000 Subject: [PATCH] Implement float4x4::frustum() and float4x4::perspective() to build projection matrices. --- src/matrix.cpp | 27 +++++++++++++++++++++++++++ src/matrix.h | 3 +++ 2 files changed, 30 insertions(+) diff --git a/src/matrix.cpp b/src/matrix.cpp index 16b36d73..3b522c14 100644 --- a/src/matrix.cpp +++ b/src/matrix.cpp @@ -62,3 +62,30 @@ template<> float4x4 float4x4::invert() const return ret; } +template<> float4x4 float4x4::frustum(float left, float right, float bottom, + float top, float near, float far) +{ + float invrl = (right != left) ? 1.0f / right - left : 0.0f; + float invtb = (top != bottom) ? 1.0f / top - bottom : 0.0f; + float invfn = (far != near) ? 1.0f / far - near : 0.0f; + + float4x4 ret(0.0f); + ret[0][0] = 2.0f * near * invrl; + ret[1][1] = 2.0f * near * invtb; + ret[2][0] = (right + left) * invrl; + ret[2][1] = (top + bottom) * invtb; + ret[2][2] = - (far + near) * invfn; + ret[2][3] = -1.0f; + ret[3][2] = -2.0f * far * near * invfn; + return ret; +} + +template<> float4x4 float4x4::perspective(float theta, float width, + float height, float near, float far) +{ + float t1 = tanf(theta / 2.0f); + float t2 = t1 * height / width; + + return frustum(-near * t1, near * t1, -near * t2, near * t2, near, far); +} + diff --git a/src/matrix.h b/src/matrix.h index 73b9b924..afa39a9f 100644 --- a/src/matrix.h +++ b/src/matrix.h @@ -195,6 +195,9 @@ template struct Mat4 T det() const; Mat4 invert() const; + static Mat4 frustum(T left, T right, T bottom, T top, T near, T far); + static Mat4 perspective(T theta, T width, T height, T near, T far); + inline Mat4 operator +(Mat4 const val) const { Mat4 ret;