Search code examples
c++openglmatrixglm-mathcoordinate-transformation

Converting 3D transformation to 2D


I am trying to figure out a way of converting a 3D transformation matrix to 2D in OpenGL. My z-coordinates are ignored (I am working with ground projections).

Here is an example of what I am trying to achieve:

// Given a transformation matrix
// | r00 r01 r01 t0 |
// | r10 r11 r11 t1 |
// | r20 r21 r21 t2 |
// | 0.  0.  0.  1. |
//
// Ignore the z-coordinate, and convert it to
// | r00 r01 t0 |
// | r10 r11 t1 |
// | 0.  0.  1. |
glm::dmat4 t_matrix_3D = GetTransformation();
glm::dmat3 t_matrix_2D = glm::dmat3(t_matrix_3D);
t_matrix_2D[2] = dvec3(dvec2(t_matrix_3D[3]), 1.);
t_matrix_2D[0][2] = 0.;
t_matrix_2D[1][2] = 0.;

The question is if there is a prettier way of doing it? Maybe using matrix slicing, or sub matrix extraction?


Solution

  • The most comprehensible and probably the best performing way is to write a inline method or function and to use directly the constructor of glm::mat3:

    glm::mat3 Mat3Dto2D( const glm::mat4 & m )
    {
        return glm::mat3(
            m[0][0], m[0][1], 0.0f,
            m[1][0], m[1][1], 0.0f,
            m[3][0], m[3][1], 1.0f
        );
    }