Learn OpenGL 7
Coordinate Systems
Introduction
OpenGL expects all the vertices to be normalized in order to be seen on the screen. Transforming coordinates to normal device coordinates
requires several different transformations. Each transformation corresponds to a certain coordinate system. There are five different coordinate systems.
- local space
- world space
- view space
- clip space
- screen space
local space
Local space is the coordinate space that is local to your object. All the transformations (translation, rotation and scale) mentioned in the previous tutorial apply to local space with model matrix
.
world space
World space is where all the objects are located. The model matrix translates, scales and/or rotates your object to place it in the world at a location/orientation they belong to. A realistic example is: Think of it as transforming a house by scaling it down (it was a bit too large in local space), translating it to a suburbia town and rotating it a bit to the left on the y-axis so that it neatly fits with the neighboring houses.
view space
The view space is the result of transforming your world-space coordinates to coordinates that are in front of the user’s view. The view space is thus the space as seen from the camera’s point of view.
clip space
In clip space, coordinates that are outside of the specific range will be clipped. There are two types of projections: orthographic projection and perspective projection.
Orthographic projection defines a cube-like frustum box. All the coordinates inside this frustum will be visible and within the range of NDC.
In GLM, it defines as:
1 | // left right bottom top near far |
The problem of orthographic projection is that it does not mimic the real world scenario. In real life, objects that are farther away appear much smaller.
Homogeneous coordinates
plays an important role in perspective projection. The projection matrix maps a given frustum range to clip space, but also manipulates the w value of each vertex coordinate in such a way that the further away a vertex coordinate is from the viewer, the higher this w component becomes.
Each component of the vertex coordinate is divided by its w component giving smaller vertex coordinates the further away a vertex is from the viewer.
In GLM, it defines as:
1 | // FOV aspect-ratio near far |
Put all together
vertex shader
1 |
|
host program
1 | // activate shader |
Z-buffer
OpenGL stores all its depth information in a z-buffer. Whenever the fragment wants to output its color, OpenGL compares its depth values with the z-buffer. If the current fragment is behind the other fragment it is discarded, otherwise overwritten. This process is called depth testing
.
To enable depth testing:
1 | glEnable(GL_DEPTH_TEST); |
Make sure to clear depth buffer at the beginning of each rendering loop.
1 | glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); |
Demo