Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenGL transform matrix order is backwards

Tags:

c++

math

opengl

If I want to rotate the object around z axis, and then translate it I must do

glm::mat4 transform;
GLfloat angle = 90f;
transform = glm::rotate(transform, angle, glm::vec3(0.0f, 0.0f, 1.0f));
transform = glm::translate(transform, glm::vec3(0.5f, -0.5f, 0.0f));

But it works backwards, it first rotates and then translates, so I need to write it as

glm::mat4 transform;
GLfloat angle = 90f;
transform = glm::translate(transform, glm::vec3(0.5f, -0.5f, 0.0f));
transform = glm::rotate(transform, angle, glm::vec3(0.0f, 0.0f, 1.0f));

How do the maths behind this work? Why I must combine matrixes in reverse to achieve the desired effect?

like image 720
lukas.pukenis Avatar asked Nov 27 '15 13:11

lukas.pukenis


People also ask

Does the order of matrix transformations matter?

In a composite transformation, the order of individual transformations is important. For example, if you first rotate, then scale, then translate, you get a different result than if you first translate, then rotate, then scale.

What is OpenGL transformation matrix?

In OpenGL we usually work with 4x4 transformation matrices for several reasons and one of them is that most of the vectors are of size 4. The most simple transformation matrix that we can think of is the identity matrix . The identity matrix is an NxN matrix with only 0s except on its diagonal.

What are the types of matrix transformations?

Learn examples of matrix transformations: reflection, dilation, rotation, shear, projection.


1 Answers

From an intuitive point of view, you are absolutely right: Transformations have to be applied the opposite way one thinks about them. The reason for this is quite easy:

In glm/OpenGL all vectors are assumed to be column vectors, thus applying a transformation (M) in matrix form to a vector t can be written as follows:

t' = M * t

Now assume that we first want to translate (T) and then rotate (R). We could now do each step separately like

t' = T * t       //Translate
t'' = R * t'     //Rotate result Translation

When we want to combine both transformations we substitute t' in the second line and get:

t'' = R * (T * t) = (R * T) * t

As you can see, the operation that is applied first is written last (or better to say closer to the vector). The same principle can be applied with as many matrices one wants.

Note, that if vectors are treated as row vectors, the whole matrix order would change.

 t' = t * M        //General case

Let's have a look at the same example as above, but this time with row vectors:

 t' = t * T
 t'' = t' * R

 t'' = (t * T) * R = t * (T * R)

Conclusion: Whenever you think about transformations and vectors, remember that the operation that is applied first has to be written closer to the vector.

like image 147
BDL Avatar answered Oct 15 '22 04:10

BDL