问题
I am programming an OpenGL renderer in C++. I want it to be as efficient as possible and each vertex/normal/UV tex coord/tangents/etc to take up as little memory as possible. I am using indexes, line strips, and fans. I was thinking that 32bit floating points are not necessary and 16 bit Floating points should be fine, at least for some of these like normals and UVs. I can't seem to find any examples of this anywhere. I can find talk of "GL_HALF_FLOAT", but no real examples. Am I on the right track? Or is this not worth looking in to? If anyone knows of an example of this could they send a link of source code?
回答1:
In full OpenGL (unlike in OpenGL ES), shader code always operates with 32-bit floats. Starting with OpenGL 3.0, specifying vertex data as half-floats is supported, though. If the precision is sufficient for your needs, this can reduce memory usage for your vertex data, and reduce the bandwidth needed for vertex fetching.
Keep in mind that the precision of a half-float is only about 3-4 decimal digits. So the accuracy really is seriously limited.
As for how to use them, it's quite straightforward. If you have a pointer to half-float values, you store them in a VBO using glBufferData()
or glBufferSubData()
, just like you would for any other type. The glVertexAttribPointer()
call will then look like this, using an attribute with 3 components as an example:
glVertexAttribPointer(loc, 3, GL_HALF_FLOAT, GL_FALSE, 0);
The format of the data itself is defined in the ARB_texture_float extension. While it's not officially named, it looks at least very similar to the IEEE 754-2008 format. I wrote conversion code based on that Wikipedia format description before, and it worked fine for OpenGL usage.
Most languages don't have built-in types for half-floats. So you either will have to write a few lines of code to do the conversion from float to half-float, or use code that somebody else wrote.
The following resources about half-float conversion are from a quick search. I have no personal experience with any of them, and you should do your own search to find the one most suitable for your needs:
- Interesting article from Intel, explaining possible performance benefits: https://software.intel.com/en-us/articles/performance-benefits-of-half-precision-floats. This also mentions that Intel processors have instructions for the conversion (e.g. there's a
_mm256_cvtps_ph
intrinsic to convert from float to half-float). - Open source library for half-float operations and conversions: http://half.sourceforge.net/.
- gcc documentation saying that it supports a half-float type (
__fp16
) for ARM targets.
来源:https://stackoverflow.com/questions/28357977/gl-half-float-with-opengl-rendering-and-glsl