Search code examples
matrixsqliteglm-math

GLM matrix 4X4 (mat4) to array and back


I need to put a glm math library mat4 into a sqlite3 BLOB and back. What would be the most efficient approach? Serialize mat4 to bytes?, Turn mat4 to a float array? BLOB will not take a mat4 directly

adding brute force conversion of mat4 to array of floats

             :) using namespace glm;

              mat4 fM;  
              float fma[16];

              vec4 t0 = fM[0];
              vec4 t1 = fM[1];
              vec4 t2 = fM[2];
              vec4 t3 = fM[3];



            fma[0] = t0[0];
            fma[1] = t0[1];
            fma[2] = t0[2];
            fma[3] = t0[3];

            fma[4] = t1[0];
            fma[5] = t1[1];
            fma[6] = t1[2];
            fma[7] = t1[3];

            fma[8] = t2[0];
            fma[9] = t2[1];
            fma[10] = t2[2];
            fma[11] = t2[3];

            fma[12] = t3[0];
            fma[13] = t3[1];
            fma[14] = t3[2];
            fma[15] = t3[3];

this has been tested to work correctly - but there should be a better way. the conversion from float[16] to mat4 is handled by glm library glm/gtc/type_ptr.hpp - works as it should. BLOB in sqlite3 will take a float array directly.

SOLVED:

#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>

float *fM;
glm::mat4 matrix;
fM = glm::value_ptr(matrix);
sqlite3_bind_blob(stmt, 0, fM, sizeof(fM), SQLITE_STATIC);

the above converts the values for glm::mat4 into a float array which then can be saved in sqlite3 as a single BLOB type


Solution

  • At the moment I'm doing something similar, so I hope this will help you. What I'm doing is: converting matrix to floats, then to string and storing it in xml, you could do the same thing, by storing your float array as string in SQLite database.