gpt4 book ai didi

c++ - 如何制作可移植且与编译器无关的 glBufferData?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:15:44 25 4
gpt4 key购买 nike

This question询问是否可以依靠编译器不弄乱 struct 的值顺序和填充。

根据该问题的答案,

OpenGL defines, very clearly, what the byte layout of a std140 interface block is.

C++11 defines a concept called "standard layout types".

The only things C++ tells you about standard layout types with regard to layout is that empty base classes are ignored (so long as it remains standard layout) and that the first NSDM will be at the very beginning of the class. That is, there will never be padding at the front.

The other thing the standard says is that NSDMs of the same access class will be allocated in order, with later ones having larger offsets than earlier ones.

But that's it, as far as the C++ standard is concerned. [class.mem]/13 states that implementations can add padding between members for various reasons.

可能但并不总是存在的填充确实会把事情搞砸,最糟糕的是 - 这取决于编译器。


为了避免错误和噩梦,使用与编译器无关的方法不是更好吗?

例如:

class BufferData
{
private:
GLfloat data[12];

public:
GLfloat* getCameraPosition()
{
return (GLfloat*) &data[0];
}
GLfloat* getLightPosition()
{
return (GLfloat*) &data[4];
}
GLfloat* getLightDiffuse()
{
return (GLfloat*) &data[8];
}
GLfloat* getData()
{
return data;
}
};

相对于天真:

struct BufferData
{
GLfloat camera_position[4];
GLfloat light_position[4];
GLfloat light_diffuse[4];
};

还是天真的方法就足够好了?

(让我们假设类/结构不仅如此,而且可能会改变)

最佳答案

“与编译器无关”?没有这种动物。你写一个的尝试证明了这一点。考虑您的结构成员定义:

GLfloat data[12];

这需要存在 GLfloat 类型。但问题是,C++ 没有定义那种类型。 OpenGL 可以。

OpenGL 非常清楚地定义了该类型:它是一个 IEEE-754 floating-point type, using the BINARY32 format .

事实是,C++ 不要求 float 符合这一点。事实上,C++ 并不要求它的任何类型都符合这一点。如果编译器想让 float 使用 IEEE-754 以外的东西,那很好。

现在,您可能会说 OpenGL header 可以将 GLfloat 定义为一个类类型,大小为 32 位,它将从编译器的 float 类型转换为IEEE-754。当然,这可能会发生……除非没有办法获得 32 位值。

有 9 位字节的系统。或 18 位字节。这些系统有 C++ 编译器。这样的系统不能声明只有 32 位大小的类型。

但是能够传递 32 位值(更不用说 16 位和 8 位)是 OpenGL 的一个硬性要求。没有它,您将无法在缓冲区对象中传递任何数据。然而,C++ 不需要它。

说到顶点数据,半现代 OpenGL 中最基本的功能之一是 glVertexAttribPointer。它依赖于您将字节偏移量转换为 void*,然后它会转换回来。

C++ 不保证这有效。 C++ 标准中没有任何地方要求如果你将一个整数转换为一个指针,然后将该指针转换回一个整数,你将得到相同的整数(它确实说 ptr->int->ptr 有效,但是这并不意味着相反)。

然而 OpenGL 需要它。除非您使用单独的属性缓冲区(和 I strongly suggest you do if it's available ),否则您的代码和您调用的 OpenGL 代码都依赖于这种未定义的行为。

OpenGL 将 GLint 定义为带符号的 32 位补码。但是 C++ 不要求任何整数类型是二进制补码。

但是 OpenGL 可以。

OpenGL 无法在类型大小不正常的系统上运行。它不能在具有 9 位字节的系统上运行。它不能在使用一个补码进行有符号整数数学运算的系统上运行。我可以继续这样做,但我认为我的观点很明确。

通过选择完全使用 OpenGL(如果您想知道,也可以选择 Vulkan),您已经依赖于实现定义的行为。那么,当您已经依赖大量其他实现定义的行为时,为什么还要让您的生活更加困难来避免这种特定的实现定义行为呢?

马出了谷仓;现在关门无济于事。

关于c++ - 如何制作可移植且与编译器无关的 glBufferData?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38429628/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com