Reputation: 857
I have a C++ class Matrix4x4 which has an array of 16 floats and no virtual methods:
class Matrix4x4
{
public:
float values[16];
Matrix4x4();
Matrix4x4(float v0, float v1, float v2, float v3, float v4, float v5, float v6, float v7, float v8, float v9, float v10, float v11, float v12, float v13, float v14, float v15);
Matrix4x4(const Quaternion &quat, const Vector3 &pos);
void convertToQuatPos(Quaternion &quat, Vector3 &pos);
void loadIdentity();
void setValues(float v0, float v1, float v2, float v3, float v4, float v5, float v6, float v7, float v8, float v9, float v10, float v11, float v12, float v13, float v14, float v15);
void setPerspective(float fov, float aspect, float nearPlane, float farPlane);
void setOrthographic(float top, float left, float bottom, float right, float nearPlane, float farPlane);
...
static void multiply3x3(const Matrix4x4 &m1, const Matrix4x4 &m2, Matrix4x4 &result);
static void multiply4x4(const Matrix4x4 &m1, const Matrix4x4 &m2, Matrix4x4 &result);
...
Matrix4x4 operator*(const Matrix4x4 &a);
Vector3 operator*(const Vector3 &a);
Vector4 operator*(const Vector4 &a);
};
I'm passing vectors of these matrices to GLSL like so (where bones is a std::vector of Matrix4x4):
glUniformMatrix4fv(glGetUniformLocation(shader->getProgram(), "boneMatrices"), bones.size(), false, (GLfloat*) &bones[0].values[0]);
which obviously assumes that a Matrix4x4 object will take up only 16-floats worth of memory with no alignment or padding issues. It works fine using MSVC, is it safe to assume that it should work on other platforms (Linux, OSX, Android in the future) e.t.c? Should I be aligning the values array and ensuring there is no padding?
Upvotes: 1
Views: 1007
Reputation: 22318
Adding a static assertion to the header can at least act as a guard against the (very unlikely) possibility that elements of a Matrix4x4
array are padded:
#include <type_traits>
...
static_assert(
(sizeof(Matrix4x4) == (sizeof(GLfloat) * 16) &&
std::is_standard_layout<Matrix4x4>::value),
"Matrix4x4 does not satisfy contiguous storage requirements");
Upvotes: 2