OpenGL ES盡可能每次渲染多個精靈.以提高渲染性能.為此需要知道精靈『位置』『尺寸』『紋理區域』.『批處理』將多個渲染合拼在一起.這對GPU有利.批處理設立浮點數『緩存』保存頂點.該緩存區初此時需清空.定義『批處理』結構BATCHER.
public class BATCHER {
成員Buffer為浮點型數組用於存儲頂點.
private static float[] buffer;
成員indices為短整形索引.以三角形排列用於儲存頂點.
public static short[] indices ;
頂點列表用於批處理渲染
private static VERTICES vertices;
緩存寫入索引初此為零
private static int index = 0;
精零數量初此為零
public static int num = 0;
初次批處理.max精靈為最大量.
public static void Init(int max){
分配2D精靈頂點緩存,每個精靈有4頂點,每頂點要4個浮點數(空間坐標x,y兩個,紋理坐標u,v兩個)
buffer = new float[max44];
分配頂點緩存.『頂點』『紋理座標』『索引』
vertices = new VERTICES(max * 4, max*6, false,true);
分配索引每個精靈6個索引
indices = new short[max*6];
int len = indices.length;// 索引數組長度
index = 0;// 緩存寫入索引
num = 0;// 精零數量
生成頂點索引
for (int i=0,j=0; i < len; i += 6, j += 4) {
indices[i + 0] = (short)(j + 0);
indices[i + 1] = (short)(j + 1);
indices[i + 2] = (short)(j + 2);
indices[i + 3] = (short)(j + 2);
indices[i + 4] = (short)(j + 3);
indices[i + 5] = (short)(j + 0);
}
設置頂點索引
vertices.SetIndices(indices, 0, indices.length);
}
準備進行批處理渲染.首先綁定紋理.並將『精零數量』『緩存索引』置零
public static void Begin(TEXTURE texture){
texture.Bind();// 綁定紋理
num = 0;// 精零數量
index = 0;// 緩存寫入索引
}
結束批處理渲染.將頂點提交給OpenGL數組並觸發.綁定頂點數據後進形三角形渲染.然後取消數據綁定.每次調用繪畫時.向緩存區中添加4個頂點參數為『位置』『顏色』『索引』『紋理區域』
public void boolean End(){
vertices.SetVertices(buffer,0,index);
vertices.Draw(GL10.GL_TRIANGLES, 0, num * 6);
}
批處理繪畫計算精靈中心『位置』及『寬和高』.和『紋理區域』.生成精靈『左下角』與『右上角』『空間座標』與『紋理座標』
public static void Draw(float x,float y,float width,float height,REGION region){
float halfWidth = width/2.0f;// 寬度一半
float halfHeight = height/2.0f;//高度一半
float x1 = x – halfWidth;
float y1 = y – halfHeight;
float x2 = x + halfWidth;
float y2 = y + halfHeight;
buffer[index++] = x1;
buffer[index++] = y1;
buffer[index++] = region.u1;
buffer[index++] = region.v2;
buffer[index++] = x2;
buffer[index++] = y1;
buffer[index++] = region.u2;
buffer[index++] = region.v2;
buffer[index++] = x2;
buffer[index++] = y2;
buffer[index++] = region.u2;
buffer[index++] = region.v1;
buffer[index++] = x1;
buffer[index++] = y2;
buffer[index++] = region.u1;
buffer[index++] = region.v1;
++num;
}
}
在調用時首先清理緩存並存入紋理.但只能對使用同一紋理精靈進行批處理.最後結束渲染.如下:
BATCHER.Begin(Texture);
BATCHER.Draw(X,Y,WIDTH,HEIGHT,Region);
BATCHER.End();