Use offsetof with GLM (OpenGL maths)

a 夏天 提交于 2019-12-12 03:39:41

问题


I am writing an OpenGL program using the GLM OpenGL maths library. I would like to combine vertex positions, normals and texture coordinates into one class like so

class Vertex {
    public:
       glm::vec4 position;
       glm::vec4 normal;
       glm::vec2 texcoord;
};

and then use an array of these as my vertex buffer object (VBO). However, when calling glVertexAttribPointer to map my VBOs I need to give it an offset into this combined Vertex struct for the normal and texcoord members.

Had these just been PODs I could have used something like

offsetof(Vertex, position)

but that does not work with glm data types (or at least g++ 4.4.3 bails out).

What is the recommended way to get the offset of the members of Vertex?

(I understand the general reason why I cannot have offsetof for arbitrary C++ objects, but in this particular case things seem to be well-defined).


回答1:


(I understand the general reason why I cannot have offsetof for arbitrary C++ objects, but in this particular case things seem to be well-defined)

By C++98/03 standards, they are not well defined. C++11 improved this by relaxing the requirements for a type to be considered "standard-layout", which is a much weaker set of rules (offsetof in C++11 requires standard-layout types, not PODs). I don't know if GLM's classes follow the standard-layout rules or not.

Of course, that's all irrelevant, since you're dealing with a C++98/03 compiler. There is no mechanism that is required by the standard to work to get the offset of a member from a non-POD type. Your choices are to either stick to the standard make your vertex data POD by not using GLM types, or to just do what works for your compiler(s) of interest.

The latter case is actually not too bad, from a practical standpoint. The reason the definition of PODs was changed in C++11 was because most compilers already follow the new rules; the standards committee was simply legitimizing behavior that was widely known to work across compilers. So you could simply just do that. You know the size of a glm::vec4 will be 16 bytes, so compute the offset manually.



来源:https://stackoverflow.com/questions/12548465/use-offsetof-with-glm-opengl-maths

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!