Game Development Reference
In-Depth Information
from the buffer will then know that it should read the floats from index 0 to 4 (remember that the
limit is exclusive); and that's exactly what OpenGL ES needs to know as well. Note, however,
that it will happily ignore the limit. Usually, we have to tell it the number of elements to read in
addition to passing the buffer to it. There's no error checking done, so watch out.
Sometimes, it's useful to set the position of the buffer manually after we've filled it. This can be
done via a call to the following method:
FloatBuffer.position( int position)
This will come in handy later on, when we temporarily set the position of a filled buffer to
something other than 0 for OpenGL ES to start reading at a specific position.
Sending Vertices to OpenGL ES
So how do we define the positions of the three vertices of our first triangle? Easy—assuming our
coordinate system is (0,0,1) to (320,480,-1), as we defined it in the preceding code snippet—we
can do the following:
ByteBuffer byteBuffer = ByteBuffer. allocateDirect (3 * 2 * 4);
byteBuffer.order(ByteOrder. nativeOrder ());
FloatBuffer vertices = byteBuffer.asFloatBuffer();
vertices.put( new float [] { 0.0f, 0.0f,
319.0f, 0.0f,
160.0f, 479.0f });
vertices.flip();
The first three lines should be familiar already. The only interesting part is how many bytes we
allocate. We have three vertices, each composed of a position given as x and y coordinates.
Each coordinate is a float, and thus takes up 4 bytes. That's 3 vertices 2 two coordinates times 4
bytes, for a total of 24 bytes for our triangle.
Note We can specify vertices with x and y coordinates only, and OpenGL ES will automatically set
the z coordinate to 0 for us.
Next, we put a float array holding our vertex positions into the buffer. Our triangle starts at the
bottom-left corner (0,0), goes to the right edge of the view frustum/screen (319,0), and then goes
to the middle of the top edge of the view frustum/screen. Being the good NIO buffer users we
are, we also call the flip() method on our buffer. Thus, the position will be 0 and the limit will be
6 (remember, FloatBuffer limits and positions are given in floats, not bytes).
Once we have our NIO buffer ready, we can tell OpenGL ES to draw it with its current state (that
is, viewport and projection matrix). This can be done with the following snippet:
gl.glEnableClientState(GL10. GL_VERTEX_ARRAY );
gl.glVertexPointer( 2, GL10. GL_FLOAT , 0, vertices);
gl.glDrawArrays(GL10. GL_TRIANGLES , 0, 3);
 
 
Search WWH ::




Custom Search