Search code examples
c++openglvectorpositionglm-math

Modern OpenGL: How to get the vector position of the cube?


glm::mat4 yellow_bone_obj_mat = m_bone_animation->get_yellow_mat();
glUniformMatrix4fv(glGetUniformLocation(shader.program, "model"), 1, GL_FALSE, glm::value_ptr(yellow_bone_obj_mat));
bone_obj->obj_color = m_bone_animation->colors[1];
draw_object(shader, *bone_obj);

I created a cube using this code.

glm::vec3 scale = glm::vec3(1.f, 1.f, 1.f);
m_yellow_mat = glm::mat4(1.0f);
m_yellow_mat = glm::scale(m_yellow_mat, scale);

glm::vec3 pivot = glm::vec3(0.0f, 2.f, 0.0f);

glm::vec3 pos = root_position;

m_yellow_mat = glm::translate(m_yellow_mat, pos);
m_yellow_mat = glm::rotate(m_yellow_mat, glm::radians(angleZ), glm::vec3(0, 0, 1));
m_yellow_mat = glm::rotate(m_yellow_mat, glm::radians(angleY), glm::vec3(0, 1, 0));

m_yellow_mat = glm::rotate(m_yellow_mat, glm::radians(angleX), glm::vec3(1, 0, 0));


m_yellow_mat = glm::translate(m_yellow_mat, pivot);

m_yellow_mat = glm::scale(m_yellow_mat, scale_vector[1]);

// scale_vector[1] = {0.5f,4.f,0.5f}  This is scale_vector[1]
//  root_position = { 2.0f,1.0f,2.0f };

These are the transformations I applied. This enables it to rotate around the endpoint (bottom part) of the cube. I want to find the Vector position of the start point of the cube (top part). How can I do that?


Solution

  • A 4x4 transformation matrix looks as follows:

    column 0: Xx, Xy, Xz, 0
    column 1: Yx, Xy, Yz, 0
    column 2: Zx  Zy  Zz, 0
    column 3: Tx, Ty, Tz, 1
    

    The translation is stored in the 4th column of the column major order matrix.

    That means the xyz components of the translation are m_yellow_mat[3][0], m_yellow_mat[3][1] and m_yellow_mat[3][2]:

    glm::vec3 trans = glm::vec3(m_yellow_mat[3]);
    

    If you want to know the world position of a vertex coordinate of the model, then you've to transform the model coordinate by the model matrix:

    glm::vec3 vertex_corodiante;
    
    glm::vec3 world_coordiante = glm::vec3(m_yellow_mat * glm::vec4(vertex_corodiante, 1.0f));