0
votes

I have noticed strange behaviour of uniform buffer object when I change the order of struct members (the struct in the shader is the same as struct in cpp). This is my source code (the working version):

CPP:

struct Matrices {
    // vec3, mat4 - glm library
    mat4 projectionMatrix; 
    mat4 viewMatrix;
    vec3 eyePosition;
};

GLSL:

layout (std140) uniform matrices {
    mat4 projectionMatrix;
    mat4 viewMatrix;
    vec3 eyePosition;
};

CPP ubo generation:

GLuint tmpUBO[2];
glGenBuffers(2, tmpUBO);
uniformBlocks["matrices"].bindingPoint = MATRICES_BINDING_POINT;
uniformBlocks["matrices"].ubo = tmpUBO[0];
glBindBuffer(GL_UNIFORM_BUFFER, tmpUBO[0]);
glBufferData(GL_UNIFORM_BUFFER, sizeof(Matrices), &matrices, GL_DYNAMIC_DRAW);
glBindBuffer(GL_UNIFORM_BUFFER, 0);

CPP updating ubo data:

glBindBuffer(GL_UNIFORM_BUFFER, uniformBlocks["matrices"].ubo);
GLvoid *p = 
    glMapBufferRange(GL_UNIFORM_BUFFER, 0, sizeof(Matrices), 
    GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_RANGE_BIT);
memcpy(p, &matrices, sizeof(Matrices));
glUnmapBuffer(GL_UNIFORM_BUFFER);
glBindBuffer(GL_UNIFORM_BUFFER, 0);

CPP binding ubo to linked and active shader:

GLuint bi = glGetUniformBlockIndex(handle, name);
glBindBufferBase(GL_UNIFORM_BUFFER, bindingPoint, ubo);
glUniformBlockBinding(handle, bi, bindingPoint);

This version is working totally fine, but when I change the order of struct members (in both glsl and cpp), for example:

struct Matrices {
    vec3 eyePosition;
    mat4 projectionMatrix; 
    mat4 viewMatrix;
}

one or both of the matrices is not updated when I move the camera or change the perspective.

Does anybody have any idea what is causing this?

1
what are the definitions of the vec3 and mat4 structs in cpp? - ratchet freak
I am using glm library - it is compatible with glsl. - Jimmy
Might be different padding. What is sizeof(Matrices) for the second version? - Reto Koradi
The size is the same, I don't think padding should be a problem since these are all floats. - Jimmy

1 Answers

2
votes

I have found the answer on this website http://www.opentk.com/node/2926. The problem was with alignment of struct variables in shader.