為什麼在構建投影矩陣OpenGL時否定z


0

我從scratchpixel.com上的this文章構建了正交投影矩陣:

Matrix4 ortho(float l, float r, float b, float t, float n, float f) {
   return Matrix4(
       2/(r-l), 0, 0, -(r+l)/(r-l), //row 0
       0, 2/(t-b), 0, -(t+b)/(t-b), //row 1
       0, 0, -2/(f-n), -(f+n)/(f-n), //row 2
       0, 0, 0, 1 //row 3
   );
}

,其中r, l, t, b, n, f是視圖框的右,左,上,下,近和遠角。

現在,我使用視圖框ortho(-1, 1, -1, 1, -1, 1)的默認參數測試了此矩陣,以查看是否獲得了單位矩陣。但是我得到了:

 1, 0, 0, 0,
 0, 1, 0, 0,
 0, 0, -1, 0,
 0, 0, 0, 1

基本上,這將導致每個變換點的z坐標取反。

構造投影矩陣時,否定z坐標是標準做法嗎?這樣做的目的是什麼?

1

I'm assuming your scene is constructed based on right-handed coordinates.

If you are using OpenGL, yes. If you are using Direct3D, no.

The projection matrix maps [-n, -f] into [0, 1]. This weird property comes from the fact that the eye coordinates are right-handed, but the clip space (NDC) uses left-handed coordinates. Hence the implementation of ortho().

Direct3D uses a z-axis that goes outwards the screen. Implementations for Direct3D projection matrices will not produce negated z when coupled with your application.


0

What could be the purpose behind that?

Have a look at the first lines and the first image in the Perspective Projection section of this link. For the answer to your question, it is not important that you used an orthographic projection, even though there is also a corresponding section in the link.

The issue is how OpenGL defines its coordinate systems. Quote from the link:

Note that the eye coordinates are defined in the right-handed coordinate system, but NDC uses the left-handed coordinate system. That is, the camera at the origin is looking along -Z axis in eye space, but it is looking along +Z axis in NDC.

So if you transform between them, you need to swap the z-axis. This is the whole purpose behind it, switching the handedness of the coordinate systems.

Is it standard to negate the z coordinate when constructing projection matrix?

Depends on your API and how the coordinate systems are defined. In OpenGL, you need to do this.