Android/OpenglES2/examples:为什么要使用ByteBuffer进行坐标?
问题描述:
美好的一天我的朋友,Android/OpenglES2/examples:为什么要使用ByteBuffer进行坐标?
我是新来的Android和Java一般,所以对于noob问题感到抱歉。 我遇到了标准的OpenGL ES的例子,并试图理解这个代码:
static float wallCoords[] = {
// in counterclockwise order:
-0.5f, 0.6f, 0.0f, // top left
-0.5f, 0.5f, 0.0f, // bottom left
0.5f, 0.5f, 0.0f, // bottom right
0.5f, 0.6f, 0.0f, // top right
};
private final int vertexCount = wallCoords.length/COORDS_PER_VERTEX;
private final int vertexStride = COORDS_PER_VERTEX * 4; // 4 bytes per vertex
float color[] = { 0.63671875f, 0.76953125f, 0.22265625f, 0.0f };
private final FloatBuffer vertexBuffer;
private final ShortBuffer drawListBuffer;
private final short drawOrder[] = { 0, 1, 2, 0, 2, 3 }; // order to draw vertices
...
ByteBuffer bb = ByteBuffer.allocateDirect(
// (number of coordinate values * 4 bytes per float)
wallCoords.length * 4);
// use the device hardware's native byte order
bb.order(ByteOrder.nativeOrder());
// create a floating point buffer from the ByteBuffer
vertexBuffer = bb.asFloatBuffer();
// add the coordinates to the FloatBuffer
vertexBuffer.put(wallCoords);
// set the buffer to read the first coordinate
vertexBuffer.position(0);
所以我的问题是,为什么不使用例如FloatBuffer.wrap()方法:
vertexBuffer = FloatBuffer.wrap(wallCoords);
谢谢!
答
这是出于性能原因。
FloatBuffer
不具有allocateDirect
方法分配direct buffer:
直接与非直接缓冲区
字节缓冲区是直接或者非直接。给定一个直接的字节缓冲区,Java虚拟机将尽最大努力直接对它执行本地I/O操作。也就是说,它将尝试避免在每次调用某个底层操作系统的本地I/O操作之前(或之后)将缓冲区内容复制到(或从)中间缓冲区。
可以通过调用此类的allocateDirect工厂方法来创建直接字节缓冲区。这种方法返回的缓冲区通常比非直接缓冲区有更高的分配和释放成本。
实际上FloatBuffer.wrap
强烈为结阵列和
新缓冲区将由给定的float数组支持该缓冲器中;也就是说,修改缓冲区将导致数组被修改,反之亦然。
以可能复制数据为代价。
是的,正确:)只是发现了这个解释。然而,这并不能解释为什么没有舒适的API。无论如何,缓冲区和数组在这种情况下非常紧密(坦率地说,在Android中它总是如此)。 –