Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

glm translate matrix does not translate the vector

Tags:

c++

glm-math

I have crossed some very simple error while started using glm (in VS2010). I have got this short code:

glm::mat4 translate = glm::translate(glm::mat4(1.f), glm::vec3(2.f, 0.f, 0.f));
glm::vec4 vector(1.f,1.f,1.f,0.f);
glm::vec4 transformedVector = translate * vector;

The result of the transformedVector is the same as its original value (1.f, 1.f, 1.f, 0.f). I do not know what i am missing here. I have tried the rotation matrix and that is working fine, the point is transformated correctly.

glm::mat4 rotate = glm::rotate(glm::mat4(1.f), 90.f, glm::vec3(0.f, 0.f, 1.f));
glm::vec4 vector(1.f, 1.f, 1.f, 0.f);
glm::vec4 transformedVector = rotate * vector;

Ok, I have found out the problem. I would like to translate a vertex not a vector, in this case I had to set the w value to 1.

like image 283
user2661133 Avatar asked Aug 07 '13 14:08

user2661133


1 Answers

You're forgetting about projective coordinates. So the last component of

glm::vec4 vector

should be 1. So the correction is simply doing this:

glm::mat4 translate = glm::translate(glm::mat4(1.f), glm::vec3(2.f, 0.f, 0.f));
glm::vec4 vector(1.f,1.f,1.f,1.f);
glm::vec4 transformedVector = translate * vector;

This is due to the way projective coordinates work, essentially to get from projective coordinates (vec4) to normal coordinates (vec3) you divide by w component. (Which you can't do if it's zero.)

The reason it works for rotations but not translations is because in projective space rotations are "the same" as in normal space, but translations are different.

I've just noticed that you worked out your error but I thought an explanation may help.

like image 82
David Avatar answered Sep 20 '22 13:09

David