How to initialize a glm::mat4 with an array?

57,111

Solution 1

Although there isn't a constructor, GLM includes make_* functions in glm/gtc/type_ptr.hpp:

#include <glm/gtc/type_ptr.hpp>
float aaa[16];
glm::mat4 bbb = glm::make_mat4(aaa);

Solution 2

You can also directly copy the memory:

float aaa[16] = {
   1, 2, 3, 4,
   5, 6, 7, 8,
   9, 10, 11, 12,
   13, 14, 15, 16
};
glm::mat4 bbb;

memcpy( glm::value_ptr( bbb ), aaa, sizeof( aaa ) );

Solution 3

You could write an adapter function:

template<typename T>
tvec4<T> tvec4_from_t(const T *arr) {
    return tvec4<T>(arr[0], arr[1], arr[2], arr[3]);
}

template<typename T>
tmat4<T> tmat4_from_t(const T *arr) {
    return tmat4<T>(tvec4_from_t(arr), tvec4_from_t(arr + 4), tvec4_from_t(arr + 8), tvec4_from_t(arr + 12));
}


// later
float aaa[16];
glm::mat4 bbb = tmac4_from_t(aaa);
Share:
57,111

Related videos on Youtube

j00hi
Author by

j00hi

Software developer and software architect since the beginning of this century. Used to do a lot web, database and windows applications development but turned my focus to real-time graphics and game development in the past few years. In terms of programming language preferences, I like everything which is strongly typed and allows me to put more than pointers and integers on the stack. While I enjoy the beauty and light-heartedness of C#, the greatest programming language to me is (modern!) C++. It took me a while to get into it, but now I really appreciate its features and also its paradigms. My true passion is computer graphics and game development. I've done quite a lot of OpenGL development and gathered a lot of experience with Unity3D in the context of working on Augmented Reality applications and indie games. In the recent few years, I took a deep dive into Vulkan. I am working on a convenience and productivity layer atop Vulkan-Hpp and on a framework. Those two projects join two of the greatest technologies: Modern C++ and Vulkan.

Updated on August 04, 2020

Comments

  • j00hi
    j00hi almost 4 years

    I'm using the OpenGL Mathematics Library (glm.g-truc.net) and want to initialize a glm::mat4 with a float-array.

    float aaa[16];
    glm::mat4 bbb(aaa);
    

    This doesn't work.

    I guess the solution is trivial, but I don't know how to do it. I couldn't find a good documentation about glm. I would appreciate some helpful links.

  • Riaz Rizvi
    Riaz Rizvi over 9 years
    Also don't forget to ensure that the source array is stored column-wise, otherwise you will need to add glm::mat4 bbbT = glm::make_mat4(aaa); glm::mat4 bbb = glm::transpose(bbbT);
  • Nathan
    Nathan about 3 years
    Do I need to type "std::memcpy()"? Where is this memcpy() function?