平台:Android 版本:2.2 及以上加速:OpenGL ES 2.0 语言:Java IDE:ADT - Eclipse
我正在尝试利用 OpenGL ES 2.0 为我正在创建的游戏快速加速 2D Sprites 的绘制,但是我没有从适用于 Android 的 OpenGL ES 2.0 中获得所需的速度。下面是我与 OpenGL 中绘图相关的代码。当使用分析器时,每帧的大部分时间都被 Draw 方法占用。
此外,由于游戏的性质,CreateModelMatrix() 在绘制之前每帧都会被调用,因为对象是不断移动和旋转的。
如何优化 Draw 方法以使其更有效?
void Create(float[] ModelData, float[] CoordData)
{
//Count Verts
Verts = ModelData.length / 3;
//Create Buffer outside Java VM
FloatBuffer ModelBuffer;
ModelBuffer = ByteBuffer.allocateDirect(ModelData.length* BYTES_PER_FLOAT)
.order(ByteOrder.nativeOrder()).asFloatBuffer();
ModelBuffer.put(ModelData).position(0);
FloatBuffer CoordBuffer;
CoordBuffer = ByteBuffer.allocateDirect(CoordData.length* BYTES_PER_FLOAT)
.order(ByteOrder.nativeOrder()).asFloatBuffer();
CoordBuffer.put(CoordData).position(0);
//Create OpenGL Buffer
final int buffers[] = new int[2];
GLES20.glGenBuffers(2,buffers,0);
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, buffers[0]);
GLES20.glBufferData(GLES20.GL_ARRAY_BUFFER, ModelBuffer.capacity() * 4, ModelBuffer, GLES20.GL_STATIC_DRAW);
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, buffers[1]);
GLES20.glBufferData(GLES20.GL_ARRAY_BUFFER, CoordBuffer.capacity() * 4, CoordBuffer, GLES20.GL_STATIC_DRAW);
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER,0);
VertHandle = buffers[0];
FrameHandle.add( buffers[1] );
//Set empty for Garbage Collection
ModelBuffer.limit(0);
ModelBuffer = null;
CoordBuffer.limit(0);
CoordBuffer = null;
ModelMatrix = new float[16];
Matrix.setIdentityM(ModelMatrix, 0);
//ModelMatrix[3] = 0.5f;
}
void CreateModelMatrix() {
Matrix.setIdentityM(ModelMatrix, 0);
Matrix.translateM(ModelMatrix,0,x,y,0.0f);
Matrix.rotateM(ModelMatrix, 0, rot, 0.0f, 0.0f, 1.0f);
Matrix.translateM(ModelMatrix,0,-this.OriginX,-this.OriginY,0.0f);
}
void Draw()
{
//final int stride = (POSITION_DATA_SIZE + NORMAL_DATA_SIZE + TEXTURE_COORDINATE_DATA_SIZE) * BYTES_PER_FLOAT;
// Pass in the position information
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, VertHandle);
GLES20.glEnableVertexAttribArray(mPositionHandle);
GLES20.glVertexAttribPointer(mPositionHandle, POSITION_DATA_SIZE, GLES20.GL_FLOAT, false, POSITION_DATA_SIZE * BYTES_PER_FLOAT, 0);
// Pass in the texture information
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, FrameHandle.get((int)Frame));
GLES20.glEnableVertexAttribArray(mTextureCoordinateHandle);
GLES20.glVertexAttribPointer(mTextureCoordinateHandle, TEXTURE_COORDINATE_DATA_SIZE, GLES20.GL_FLOAT, false,
TEXTURE_COORDINATE_DATA_SIZE * BYTES_PER_FLOAT, 0);
// Clear the currently bound buffer (so future OpenGL calls do not use this buffer).
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, 0);
//Pass the Model Matrix
GLES20.glUniformMatrix4fv(mMMatrixHandle, 1, false, ModelMatrix, 0);
//Set Texturing
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mTextureDataHandle);
GLES20.glUniform1i(mTextureUniformHandle, 0);
// Draw the cubes.
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, Verts);
}