opengl 投影矩阵转换获取得到near far,视场角等方法

要从投影矩阵中获取得到near far,长宽比,视场角等参数,就需要先知道投影矩阵是如何生成的,请参考这2篇文章,是投影矩阵生成的方法:

http://www.songho.ca/opengl/gl_projectionmatrix.html

https://zhuanlan.zhihu.com/p/73034007;中文版

看了这2篇文章之后,基本就了解投影矩阵的生成方法了,那我们就可以反向获取near far,长宽比,视场角等参数。

OpenGL Perspective Frustum and NDC

r = right, l = left, b = bottom, t = top, n = near, f = far,投影矩阵:

OpenGL Perspective Projection Matrix

投影矩阵是一个4*4的矩阵,一定要注意你的矩阵是行优先矩阵还是列优先矩阵,上图为行优先矩阵,则视场角求得:

a  = w / h
ta = tan( fov_y / 2 );

2 * n / (r-l) = 1 / (ta * a)
2 * n / (t-b) = 1 / ta
(r+l)/(r-l)   = 0
(t+b)/(t-b)   = 0

具体的求解过程我就不追溯了,大家可以把公式套进去,获取得到则获取各个参数的代码如下:

        //获取角度
        public static float GetFov(this Matrix4x4 m)
        {
            float RAD2DEG = 180.0f / 3.14159265358979323846f;
            float fov = RAD2DEG * (2.0f * (float)Math.Atan(1.0f / m.m11));
            return fov;
        }

//获取near

        public static float GetNear(this Matrix4x4 m)
        {
            return m.m23 / (m.m22 - 1);
        }

//获取far
        public static float GetFar(this Matrix4x4 m)
        {
            return m.m23 / (m.m22 + 1);
        }

//获取宽高比

        public static float GetAspect(this Matrix4x4 m)
        {
            return m.m11 / m.m00;
        }

有时候,我们在opengl获取到投影矩阵,就可以获取得到这些参数,设置到unity进行重现投影。

参考文章:

http://www.songho.ca/opengl/gl_projectionmatrix.html

https://zhuanlan.zhihu.com/p/73034007

https://stackoverflow.com/questions/10830293/decompose-projection-matrix44-to-left-right-bottom-top-near-and-far-boundary/10836497#10836497

https://stackoverflow.com/questions/58615238/opengl-perspective-projection-how-to-define-left-and-right

https://developer.vuforia.com/forum/unity-3-extension-technical-discussion/vertical-fov-unity

猜你喜欢

转载自blog.csdn.net/grace_yi/article/details/109078902
今日推荐