How to build perspective projection matrix (no API)

前端 未结 2 1459
夕颜
夕颜 2020-12-24 03:43

I develop a simple 3D engine (Without any use of API), successfully transformed my scene into world and view space but have trouble projecting my scene (from view space) usi

2条回答
  •  盖世英雄少女心
    2020-12-24 04:18

    Following is a typical implemenation of perspective projection matrix. And here is a good link to explain everything OpenGL Projection Matrix

    void ComputeFOVProjection( Matrix& result, float fov, float aspect, float nearDist, float farDist, bool leftHanded /* = true */ )
    {
        //
        // General form of the Projection Matrix
        //
        // uh = Cot( fov/2 ) == 1/Tan(fov/2)
        // uw / uh = 1/aspect
        // 
        //   uw         0       0       0
        //    0        uh       0       0
        //    0         0      f/(f-n)  1
        //    0         0    -fn/(f-n)  0
        //
        // Make result to be identity first
    
        // check for bad parameters to avoid divide by zero:
        // if found, assert and return an identity matrix.
        if ( fov <= 0 || aspect == 0 )
        {
            Assert( fov > 0 && aspect != 0 );
            return;
        }
    
        float frustumDepth = farDist - nearDist;
        float oneOverDepth = 1 / frustumDepth;
    
        result[1][1] = 1 / tan(0.5f * fov);
        result[0][0] = (leftHanded ? 1 : -1 ) * result[1][1] / aspect;
        result[2][2] = farDist * oneOverDepth;
        result[3][2] = (-farDist * nearDist) * oneOverDepth;
        result[2][3] = 1;
        result[3][3] = 0;
    }
    

提交回复
热议问题