OpenGL ES Framework: Vertices

public class Vertices 
{
private final boolean hasColor;
private final boolean hasTexCoords;
private final int vertexSize;
private final FloatBuffer vertices;
private final ShortBuffer indices;

private final GL10 gl;

public Vertices(GL10 gl, int maxVertices, int maxIndices, boolean hasColor, boolean hasTexCoords)
{
this.gl = gl;
this.hasColor = hasColor;
this.hasTexCoords = hasTexCoords;

this.vertexSize = (2 + (hasColor ? 4 : 0) + (hasTexCoords ? 2 : 0)) * 4;
ByteBuffer buffer = ByteBuffer.allocateDirect(maxVertices * vertexSize);

buffer.order(ByteOrder.nativeOrder());
vertices = buffer.asFloatBuffer();

if(maxIndices > 0)
{
buffer = ByteBuffer.allocateDirect(maxIndices * Short.SIZE / 8);
buffer.order(ByteOrder.nativeOrder());
indices = buffer.asShortBuffer();
}
else
{
indices = null;
}
}

public void setVertices(float[] vertices, int offset, int length)
{
this.vertices.clear();
this.vertices.put(vertices, offset, length);
this.vertices.flip();
}

public void setIndices(short[] indices, int offset, int length)
{
this.indices.clear();
this.indices.put(indices, offset, length);
this.indices.flip();
}

public void draw(int primitiveType, int offset, int numVertices)
{
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
vertices.position(0);
gl.glVertexPointer(2, GL10.GL_FLOAT, vertexSize, vertices);

if(hasColor)
{
gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
vertices.position(2);
gl.glColorPointer(4, GL10.GL_FLOAT, vertexSize, vertices);
}

if(hasTexCoords)
{
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
vertices.position(hasColor ? 6 : 2);
gl.glTexCoordPointer(2, GL10.GL_FLOAT, vertexSize, vertices);
}

if (indices != null)
{
indices.position(offset);
gl.glDrawElements(primitiveType, numVertices,
GL10.GL_UNSIGNED_SHORT, indices);
}
else
{
gl.glDrawArrays(primitiveType, offset, numVertices);
}
if (hasTexCoords)
{
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
}
if (hasColor)
{
gl.glDisableClientState(GL10.GL_COLOR_ARRAY);
}

}
}

 

posted @ 2012-01-08 21:41  LiLiNiuNiu  阅读(460)  评论(0编辑  收藏  举报