This little post will talk about how the W component of a vector4 is transformed in the Graphic Pipeline, starting from Model Space and ending in the Screen Space Coordinates.
In Model Space (even in World Space =P) the W component does not exists, it is can be seen as a facility to represent vectors and points in a similar way. A vector (like normal) will have the W component as 0 and a point (like position) will have it as 1.
After you transform the input (points and vectors — normal, positions, tangents ….) into the view space, the W component will remains 1 or 0 and the Z will contains the distance between the actual point (vector does not have a physical position) to the 0,0,0 (the camera).
When you transform the previous values to projection space, then the W component will contains exactely what the Z component of the view space contained.
positionAfterProjection = mul(positionViewSpace, ProjectionMatrix);
now positionAfterProjection .w = positionViewSpace.z
We can say that positionAfterProjection is now in “homogenous clip space”.
Between the vertex and pixel shader the GPU will perform a what is called “homogenous divide” that is:
positionAfterProjection /= positionAfterProjection .w
And now we are in the “normalized device coordinate space” where W is 1.
which (in DirectX conventions) is:
- -1 to +1 for X and Y
- 0 to 1 for Z
(top left = (-1, 1,0) and bottom right = (1, -1, 0) in near plane =P, the far plane will be with Z instead of 0)
Finally the ViewPort information is used to transform from normalized Device Coordiantes space into Screen Space (top left = (0, 0) bottom right = (width, height) — yes, now is 2D … you cant retrive this in pixel shaders, what we do is to put the position in a texture register and recovers it in pixel shader, then we have to manually make the division by the W component)
Perspective projection matrix is “strange” until you realize that it is doing 3 separate things:
– non-linear mapping of view space Z to unit Z (the scary stuff)
– scaling into Normalized Device Coordinates space
Thats all for today =P