5

由于设计薄弱,我不得不重写我的整个数学库和与数学相关的东西。相反,我发现我可以使用 GLM。如果你遇到过我之前的问题,我一直在处理骨骼动画,所以我要上传大量的mat4s、vec3、vec2s。这是我以前的顶点结构:

struct Vertex {
    Vec3 pos;
    Vec3 normal;
    Vec2 uv;
    Vec4 boneindex;
    Vec4 weightbias;
};

不幸的是,我发现我的数学库不是 POD,我试图上传整个结构,但我确实得到了奇怪的结果。我的最终骨骼矩阵定义为:

Mat4 bones[numBones];

我也尝试一次上传。

我只是想知道如果我用 glm::vec3、vec2、mat4 替换我的 Vec3s、Vec2s 和 Mat4s 并直接上传整个 Vertex 结构(顶点次数)并使用以下方法为每个数据设置偏移量:

 glBindBuffer(GL_ARRAY_BUFFER,everythingVBO);
 glVertexAttribPointer(xx,xx,xx,xx, BUFFER_OFFSET(0)) // pos
 glVertexAttribPointer(xx,xx,xx,xx, BUFFER_OFFSET(sizeof(glm::vec3)) // norm
 ..
 ..

 same for matrix
 glUniformMatrix4fv(xx, numBones, xx, glm::mat4 value)

.

它会按预期工作吗?我只是不想重写整个事情,这一次我必须确保它有效,因为我不想再次面对另一个失败。

4

1 回答 1

8

This is both a very simple and very complex question. So I'll start from the simple way first.

If you're looking to build some struct out of GLM types, upload them to a buffer, and access them via glVertexAttribPointer, you can probably get away with it on most C++98/03 compilers. Assuming you get offsets properly. It won't be "portable C++"; as far as the standard is concerned, it will be implementation-defined behavior (or undefined behavior if you try to use the offsetof macro. Granted, anything you might use in place of offsetof will be no less well defined by the standard).

But it will generally work.

In a conforming C++11 compiler, the GLM types will be considered standard layout types, and therefore offsetof has well-defined behavior. And as long as your Vertex structure is also standard layout, offsetof will work.

However, that doesn't mean that the internal structure of any of these types will not have arbitrary padding. A glm::vec3 is not required to be layout-compatible with a float[3], which is what OpenGL would expect. The C++ standard won't protect you.

That being said, it's pretty safe to assume for most compilers you will encounter that GLM's types will be equivalent to arrays. GLM even provides the type_ptr function to get a pointer to the contents of one of its types as an array, under the expectation that the compiler will make them compatible.

Similarly, the C++ standard provides no guarantees that a float[16*n] will be layout-compatible with an array of glm::mat4[n]. But again, it's fairly safe to assume that it will just work.

于 2013-06-19T17:54:16.567 回答