-
Notifications
You must be signed in to change notification settings - Fork 44
Transformations and 3D
This article describes the 3D math functions bundled with OOGL and how they can be used for view transformation and perspective projection.
To rotate the triangle in the sample from the previous article, we can use a rotation matrix. Because we're going to use 3D coordinates soon enough, let's use the Mat4
class, which supports 3D transformations.
GL::Mat4 trans;
trans.RotateZ( GL::Rad( 10 ) );
The constructor of the matrix class initializes it as a 4-by-4 identity matrix. The RotateZ
member function multiplies it by a rotation matrix around the Z axis. All trigonometry functions in OOGL take radians. The Rad
utility function is used here to convert degrees to radians.
To apply this transformation to the vertices, it can be uploaded to the graphics card as a uniform. The vertex shader will now look like this:
in vec2 position;
uniform mat4 trans;
void main() {
gl_Position = trans * vec4( position, 0.0, 1.0 );
}
The uniform can be set with the overloaded SetUniform
member function:
program.SetUniform( program.GetUniform( "trans" ), trans );
If you run your program now, the triangle will be rotated by 10 degrees around the origin.
Recall that 3D requires transforming the world to the camera coordinate system, perspective projection and perspective division. The latter is performed by OpenGL based on the w
coordinate but the view transformation and projection matrix have to be supplied by you.
The Mat4
class contains implementations of gluLookAt
and glPerspective
for your convenience. Setting up the complete transformation is easy.
GL::Mat4 model;
model.RotateZ( GL::Rad( 10 ) );
GL::Mat4 view = GL::Mat4::LookAt( GL::Vec3( 1, 1, 1 ), GL::Vec3( 0, 0, 0 ), GL::Vec3( 0, 0, 1 ) );
GL::Mat4 proj = GL::Mat4::Perspective( GL::Rad( 60 ), 800.0f / 600.0f, 0.1f, 10.0f );
program.SetUniform( program.GetUniform( "trans" ), proj * view * model );
You can also do the transformations in software using the Mat4::Project
and Mat4::UnProject
functions or multiplying a Vec3
by the transformation matrix yourself and performing perspective division.