Search code examples
c++matrixglm-math

Is there any way to extract a transform matrix from a view matrix in glm?


I need to extract the transform matrix from my camera to assign it to a mesh.

I'm working in a computational graphics project in school, the objective is to simulate the arms of a character in first person perspective.

My camera implementation includes a vector3 for the camera position, so i can assign that to my mesh, the problem is that i can't extract the rotation of the camera from my view matrix yet.

I calculate my final pitch and yaw in the rotation function this way, x and y are the current mouse position in the screen

m_yaw += (x - m_mouseLastPosition.x) * m_rotateSpeed;

m_pitch -= (y - m_mouseLastPosition.y) * m_rotateSpeed;

This is how i update the view matrix when it changes

glm::vec3 newFront;

newFront.x = -cos(glm::radians(m_yaw)) * cos(glm::radians(m_pitch));

newFront.y = sin(glm::radians(m_yaw)) * cos(glm::radians(m_pitch));

newFront.z = sin(glm::radians(m_pitch));

m_front = glm::normalize(newFront);

m_right = glm::normalize(glm::cross(m_front, m_worldUp));

m_up = glm::normalize(glm::cross(m_right, m_front));

m_viewMatrix = glm::lookAt(m_position, (m_position + m_front), m_up);

Right now I can assign the position of the camera to my mesh, like this

m_mesh.m_transform = glm::translate(glm::mat4(1.0f), m_camera.m_position);

I can assign the camera position successfully, but not rotation.

What i expect is to assign the full camera transform to my mesh, or to extract the rotation independently and assign it to the mesh after.


Solution

  • Thank you so much for your answers, they helped a lot.

    I managed to solve my problem in a very simple way, i just had to directly assign the final transform to my mesh using the separate properties of my camera.

    glm is so new to me, i wasn't familiar with the way it handles matrix multiplications.

    The final code takes a translation matrix with the camera position, then i rotated the resulting matrix in the Y axis with my pitch and finaly the resulting one rotates in the X axis with my yaw.

    m_mesh.m_transform = glm::rotate(glm::rotate(glm::translate(glm::mat4(1.0f), camera.m_position), glm::radians(-camera.m_yaw), glm::vec3(0.0f, 1.0f, 0.0f)), glm::radians(-camera.m_pitch), glm::vec3(1.0f, 0.0f, 0.0f));