投影矩阵和z战斗

时间:2014-04-17 14:43:46

标签: opengl

这是一个简单的问题。我正在尝试学习OpenGL,并正在学习一些教程。直到最近,我一直在使用gluPerspective和gluLookAt,一切都很完美。现在作为练习,我试图用glMultMatrix取代gluPerspective,突然间我遇到了z-fighting的问题。也许有人可以帮我解决这个问题。

我的投影矩阵计算:

public static Matrix3d PerspectiveProjection(double zNear, double zFar, double fovY, double aspect)
    {
        var halfFov = MathUtils.Deg2Rad(fovY / 2);

        var f = 1.0 / (Math.Tan(halfFov));

        double[,] mat = new double[4, 4]
        {
        {f/aspect, 0, 0, 0},
        {0, f, 0, 0},
        {0, (zFar + zNear) / (zNear - zFar), (2.0*zFar*zNear)/(zNear - zFar), 0},
        {0, 0, -1, 0}
        };

        return new Matrix3d(mat);
    }

这是我的矩阵设置:

private void Perspective(OpenGL gl, ISceneView view)
    {
        gl.Viewport(0, 0, view.Width, view.Height);

        var camera = view.Camera;

        var aspect = (double)view.Width / (double)view.Height;

        gl.MatrixMode(MatrixMode.Projection);
        gl.LoadIdentity();

        var projection = Matrix3d.PerspectiveProjection(camera.ZNear, camera.ZFar, camera.VerticalLensAngle, aspect);


        //This method seems OK, but introduces z-fighting
        gl.MultMatrix(projection.GetColumnMajorOrderedData());


        //When using this method, everything is perfect
        //gl.Perspective(camera.VerticalLensAngle, aspect, camera.ZNear, camera.ZFar);

        gl.MatrixMode(MatrixMode.Modelview);
        gl.LoadIdentity();

        gl.LookAt(camera.Position.X, camera.Position.Y, camera.Position.Z,
            camera.Target.X, camera.Target.Y, camera.Target.Z,
            camera.UpVector.X, camera.UpVector.Y, camera.UpVector.Z);

    }

1 个答案:

答案 0 :(得分:0)

没关系,发现了这个问题。矩阵中的第三行不正确。应该是

{0, 0, (zFar + zNear) / (zNear - zFar), (2.0*zFar*zNear)/(zNear - zFar)}

而不是

{0, (zFar + zNear) / (zNear - zFar), (2.0*zFar*zNear)/(zNear - zFar), 0}