Android / OpenglES2 /例子:为什么使用ByteBuffer作为coords?

时间:2016-07-13 08:53:05

标签: android opengl-es bytebuffer

美好的一天,我的朋友,

我对Android和Java一般都很陌生,所以很抱歉没有问题。 我遇到了标准的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);

谢谢!

1 个答案:

答案 0 :(得分:0)

出于性能原因。

FloatBuffer没有allocateDirect方法来分配direct buffer

  

直接与非直接缓冲

     

字节缓冲区是直接缓冲区或非直接缓冲区。给定直接字节缓冲区,Java虚拟机将尽最大努力直接执行本机I / O操作。也就是说,它将尝试避免在每次调用底层操作系统的本机I / O操作之前(或之后)将缓冲区的内容复制到(或来自)中间缓冲区。

     

可以通过调用此类的allocateDirect工厂方法来创建直接字节缓冲区。与非直接缓冲区相比,此方法返回的缓冲区通常具有更高的分配和解除分配成本。

实际上FloatBuffer.wrap强烈关联数组和缓冲区

  

新缓冲区将由给定的float数组支持;也就是说,对缓冲区的修改将导致数组被修改,反之亦然。

以可能复制数据为代价。