Home > Mobile >  C# Matrix4x4 equivalent of DirectX::XMMatrixPerspectiveLH
C# Matrix4x4 equivalent of DirectX::XMMatrixPerspectiveLH

Time:06-01

I was trying to port some c code to C#, everything works except the perspective.

In c the code looks like this, which worked without distortion.

DirectX::XMMatrixTranspose(
                DirectX::XMMatrixRotationZ(100) *
                DirectX::XMMatrixRotationX(200) *
                DirectX::XMMatrixTranslation(0,0,4) *
                DirectX::XMMatrixPerspectiveLH(DirectX::XMConvertToRadians(180),pAdapter->aspectRatio,0.5f,10)

and the C# code like this

Matrix4x4.Transpose(
            Matrix4x4.CreateRotationZ(100) *
            Matrix4x4.CreateRotationX(200) *
            Matrix4x4.CreateTranslation(0, 0, 4) *
            Matrix4x4.CreatePerspective(1.39626f, 1.7777777777777777777777777777778f, 0.5f,10)
            );

I would assume both of these would do the exact same, but the C# code doesn't appear at all, when i remove the perspecitve it renders but everything is strecthed as expected.

I tried to remake the source of dxmath which resulted in this, it now renders as further away but its still stretched.

Matrix4x4 perspective = new Matrix4x4();
float ViewWidth = 1.39626f;
float ViewHeight = 1.7777777777777777777777777777778f;
float NearZ = 0.5f;
float FarZ = 10.0f;
float TwoNearZ = NearZ   NearZ;
float fRange = FarZ / (NearZ - FarZ);

perspective.M11 = TwoNearZ / ViewWidth;
perspective.M22 = TwoNearZ / ViewHeight;
perspective.M33 = fRange;
perspective.M43 = -fRange * NearZ;

data.matrix = perspective * data.matrix;

Im not really sure what the problem is, i read in another post that matrix4x4 is right handed so i tried the same with that one but it didn't render at all. Any help is appreciated.

CodePudding user response:

The perspective matrix you use appear strange. I suggest you to use the more classical implementation from OpenGL documentation. Also, notice that you don't explicitly set the M44 value of your perspective matrix to 0.0f while this value is set to 1.0f for default identity matrix. This result in a wrong perspective matrix.

float frustumDepth = farDist - nearDist;  
float oneOverDepth = 1 / frustumDepth;

perspective.M22 = (float)(1.0f / Math.Tan(0.5f * fovRadians));
perspective.M11 = 1.0f * perspective.M22 / aspectRatio; 
perspective.M33 = farDist * oneOverDepth; 
perspective.M34 = 1.0f; 
perspective.M43 = (farDist * nearDist) * oneOverDepth; 
perspective.M44 = 0.0f;              //< replace 1.0f to 0.0f
  • Related