Putting It Together

When we put it all together, we arrive at the code in Listing 7-9.

Listing 7-9. Excerpt from IndexedTest.java; Drawing Two Indexed Triangles class IndexedScreen extends Screen { final int VERTEX_SIZE = (2 + 2) * 4; GLGraphics glGraphics; FloatBuffer vertices; ShortBuffer indices;

Texture texture;

public IndexedScreen(Game game) { super(game);

glGraphics = ((GLGame) game).getGLGraphics();

ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4 * VERTEX_SIZE); byteBuffer.order(ByteOrder.nativeOrder()); vertices = byteBuffer.asFloatBuffer(); vertices.put(new float[] { 100.0f, 100.0f, 0.0f, 1.0f,

228.0f, 100.0f, 1.0f, 1.0f, 228.0f, 228.0f, 1.0f, 0.0f, 100.0f, 228.0f, 0.0f, 0.0f });


byteBuffer = ByteBuffer.allocateDirect(6 * 2); byteBuffer.order(ByteOrder.nativeOrder()); indices = byteBuffer.asShortBuffer(); indices.put(new short[] { 0, 1, 2,


texture = new Texture((GLGame)game, "bobrgb888.png");

^Override public void present(float deltaTime) { GL10 gl = glGraphics.getGL();

gl.glViewport(0, 0, glGraphics.getWidth(), glGraphics.getHeight());

gl.glClear(GL10. GL_COLOR_BUFFER_BIT);



gl.glEnable(GL10. GL_TEXTURE_2D); texture.bind();

gl.glEnableClientState(GL10. GL_TEXTURE_COORD_ARRAY); gl.glEnableClientState(GL10. GL_VERTEX_ARRAY);


gl.glVertexPointer(2, GL10.GL_FLOAT, VERTEX_SIZE, vertices); vertices.position(2);

gl.glTexCoordPointer(2, GL10.GL_FLOAT, VERTEX_SIZE, vertices); gl.glDrawElements(GL10.GL_TRIANGLES, 6, GL10.GL_UNSIGNED_SHORT, indices);

Note the use of our awesome Texture class, which brings down the code size considerably. Figure 7-15 shows the output, and Bob in all his glory.

Figure 7-15. Bob, indexed

Now, this is pretty close already to how we worked with Canvas. We have a lot more flexibility as well, since we are not limited to axis-aligned rectangles anymore.

This example has covered all we need to know about vertices for now. We saw that every vertex must have at least a position, and can have additional attributes, such as a color given as four RGBA float values and texture coordinates. We also saw that we can reuse vertices via indexing in case we want to avoid duplication. This gives us a little performance boost, since OpenGL ES does not have to multiply more vertices by the projection and model-view matrices than absolutely necessary (which is again not entirely correct, but let's stick to this interpretation).

Was this article helpful?

0 0

Post a comment