google / mathfu

C++ math library developed primarily for games focused on simplicity and efficiency.
http://google.github.io/mathfu
Apache License 2.0
1.4k stars 188 forks source link

Perspective projection matrix (what device coordinates is it mapping to?) #45

Open bransay opened 3 years ago

bransay commented 3 years ago

Hi,

So I was looking to implement a simple frustum test when I realized I wasn't sure what device coordinates the mathfu perspective matrix was mapping to (most importantly in the Z axis as it differs between different graphics APIs).

Just out of curiosity, I looked at the implementation and attempted to map "z=-near" with a right hand matrix. After simplifying the equation I ended up with it being mapped to "f/(n-f)"? This isn't a normalized device coordinate and is especially problematic the larger n is.

I verified that it was indeed doing this (simply plug near = 1 and far = 3 or something to that effect into the perspective matrix function and multiply with (0, 0, -1, 1) and you'll see that the resulting (perspective divided) z coordinate is -1.5).

Just to be sure there wasn't some trickery going on in the view matrix, I also attempted the same test but in world space (using the view projection matrix) and got the same result.

I've traced it back to this line: "zfar_per_zdist handedness, -1 handedness, 0, 0," in PerspectiveHelper which conventionally (following how perspective matrices are typically calculated for OpenGL) would have been (n + f)/(n - f) instead of just f/(n - f), which would then map -n unto -1, the min z device coordinate for OpenGL. I haven't really done the math to figure out if that made sense in a left handed system (i.e. mapping n unto -1), but I figured I'd check here first.

Is this intentional?