Transforming screen space to/from camera space

Camera space to screen space

$$ clip = \text{projection matrix} \cdot \text{camera space position} $$ $$ ndc = \frac{clip_{xyz}}{clip_{w}} $$

In OGL, NDC space is left-handed. While in Vulkan, it is right-handed ($y$ pointing down, $z$ pointing front). In glm there are different projection matrices to reflect that.

$$ screen_{xy} = (ndc_{xy} + 1) \cdot 0.5 $$

With the depth range set from 0 to 1, OGL defines screen depth to be

$$ screen_{z} = (ndc_z + 1) \cdot 0.5 $$

In Vulkan, with minDepth set to 0 and maxDepth set to 1 in viewport setting,

$$ screen_{z} = ndc_z $$


Projection matrix (perspective, depth -1 to 1)

$$ P = \begin{bmatrix} \frac{1}{aspect \cdot tanHalfFovy} & 0 & 0 & 0 \\ 0 & \frac{1}{tanHalfFovy} & 0 & 0 \\ 0 & 0 & - \frac{f + n}{f - n} & - \frac{2 f \cdot n}{f - n} \\ 0 & 0 & - 1 & 0 \end{bmatrix} $$ in which $ tanHalfFovy = \tan{ \frac{fovy}{2} } $.

Calculating camera space depth $p_{z}$ from space depth $screen_{z}$ in OpenGL

$$ \left\{ \begin{align} P[22] \cdot p_{z} + P[23] &= clip_{z} \\ P[32] \cdot p_{z} &= clip_{w} \end{align} \right. $$

$$ screen_{z} = ( ndc_{z} + 1 )\cdot 0.5 = ( \frac{clip_{z}}{clip_{w}} + 1) \cdot 0.5 $$

Hence,

$$ p_{z} = \frac{2 f \cdot n}{(2 screen_{z} - 1)(f - n) - (f + n)} $$ in which $p_{z} \leq 0$, since view space is right-handed.


Projection matrix (perspective, force depth 0 to 1)

$$ \begin{align} P' &= C \cdot P \\ &= \begin{bmatrix} 1 & 0 & 0 & 0 \\ 0 & -1 & 0 & 0 \\ 0 & 0 & \frac{1}{2} & \frac{1}{2} \\ 0 & 0 & 0 & 1 \end{bmatrix} \cdot \begin{bmatrix} \frac{1}{aspect \cdot tanHalfFovy} & 0 & 0 & 0 \\ 0 & \frac{1}{tanHalfFovy} & 0 & 0 \\ 0 & 0 & \frac{f}{n - f} & - \frac{f \cdot n}{f - n} \\ 0 & 0 & - 1 & 0 \end{bmatrix} \end{align} $$

Calculating camera space depth $p_{z}$ from space depth $screen_{z}$ in Vulkan

$$ \left\{ \begin{align} P'[22] \cdot p_{z} + P'[23] &= clip_{z} \\ P'[32] \cdot p_{z} &= clip_{w} \end{align} \right. $$

$$ \left\{ \begin{align} P'[22] &= \frac{1}{2} P[22] + \frac{1}{2} P[32] &&= \frac{1}{2} (\frac{f}{n - f} - 1) \\ P'[23] &= \frac{1}{2} P[23] &&= - \frac{1}{2} \frac{f \cdot n}{f - n} \\ P'[32] &= 1 \cdot P[32] &&= -1 \end{align} \right. $$

$$ screen_{z} = ndc_{z} = \frac{clip_{z}}{clip_{w}} $$

Hence,

$$ p_{z} = \frac{f \cdot n}{2 screen_{z} (f - n) - (2 f - n)} $$

in which $p_{z} \leq 0$.