Orthographic matrix function?

After beating my head against the wall all morning I finally realized why my objects don't show up when using orthographic projection -- the NDC space is different between OpenGL and Metal. This means that common functions like float4x4.makeOrtho() do not work (but makePerspectiveViewAngle() does, which is part of why it was so difficult to track this down.)


I can't find a simple Swift version of makeOrtho() for Metal. Does anyone have one?


Also, should I not be using float4x4.makePerspectiveViewAngle()? Although it does work, are there some differences due to the different NDC space? In which case does anyone have both of these functions for Swift/Metal?


Thanks!

Answered by bsabiston in 269828022

OK I found one:


func makeOrthographicMatrix(left: Float, right: Float, bottom: Float, top: Float, near: Float, far: Float) -> float4x4 {
  
    return float4x4(
        [ 2 / (right - left), 0, 0, 0],
        [0, 2 / (top - bottom), 0, 0],
        [0, 0, 1 / (far - near), 0],
        [(left + right) / (left - right), (top + bottom) / (bottom - top), near / (near - far), 1]
    )
  
}


However, if anyone knows whether the standard perspective transformation I get with the following is correct, I would like to know. It works, but I don't know if it works 100% correctly:


float4x4.makePerspectiveViewAngle(float4x4.degrees(toRad: 85.0),

aspectRatio: aspect, /

nearZ: 0.01, farZ: 100.0)

Accepted Answer

OK I found one:


func makeOrthographicMatrix(left: Float, right: Float, bottom: Float, top: Float, near: Float, far: Float) -> float4x4 {
  
    return float4x4(
        [ 2 / (right - left), 0, 0, 0],
        [0, 2 / (top - bottom), 0, 0],
        [0, 0, 1 / (far - near), 0],
        [(left + right) / (left - right), (top + bottom) / (bottom - top), near / (near - far), 1]
    )
  
}


However, if anyone knows whether the standard perspective transformation I get with the following is correct, I would like to know. It works, but I don't know if it works 100% correctly:


float4x4.makePerspectiveViewAngle(float4x4.degrees(toRad: 85.0),

aspectRatio: aspect, /

nearZ: 0.01, farZ: 100.0)

Hi bsabiston,


If you look into AAPLMathUtilities.m in the Deferred Lighting sample

https://developer.apple.com/documentation/metal/deferred_lighting?language=objc

you'll find four functions of interest that return projection matrices: matrix_ortho_right_hand, matrix_ortho_left_hand, matrix_perspective_right_hand and matrix_perspective_left_hand.

Orthographic matrix function?
 
 
Q