Defining Shapes

This lesson teaches you to

You should also read

Being able to define shapes to be drawn in the context of an OpenGL ES view is the first step in
creating your high-end graphics masterpiece. Drawing with OpenGL ES can be a little tricky without
knowing a few basic things about how OpenGL ES expects you to define graphic objects.

This lesson explains the OpenGL ES coordinate system relative to an Android device screen, the
basics of defining a shape, shape faces, as well as defining a triangle and a square.

Define a Triangle

OpenGL ES allows you to define drawn objects using coordinates in three-dimensional space. So,
before you can draw a triangle, you must define its coordinates. In OpenGL, the typical way to do
this is to define a vertex array of floating point numbers for the coordinates. For maximum
efficiency, you write these coordinates into a ByteBuffer, that is passed into the
OpenGL ES graphics pipeline for processing.

By default, OpenGL ES assumes a coordinate system where [0,0,0] (X,Y,Z) specifies the center of
the GLSurfaceView frame, [1,1,0] is the top right corner of the frame and
[-1,-1,0] is bottom left corner of the frame. For an illustration of this coordinate system, see the
OpenGL ES developer
guide.

Note that the coordinates of this shape are defined in a counterclockwise order. The drawing
order is important because it defines which side is the front face of the shape, which you typically
want to have drawn, and the back face, which you can choose to not draw using the OpenGL ES cull
face feature. For more information about faces and culling, see the OpenGL ES developer guide.

Define a Square

Defining triangles is pretty easy in OpenGL, but what if you want to get a just a little more
complex? Say, a square? There are a number of ways to do this, but a typical path to drawing such a
shape in OpenGL ES is to use two triangles drawn together:

Figure 1. Drawing a square using two triangles.

Again, you should define the vertices in a counterclockwise order for both triangles that
represent this shape, and put the values in a ByteBuffer. In order to avoid
defining the two coordinates shared by each triangle twice, use a drawing list to tell the
OpenGL ES graphics pipeline how to draw these vertices. Here’s the code for this shape:

This example gives you a peek at what it takes to create more complex shapes with OpenGL. In
general, you use collections of triangles to draw objects. In the next lesson, you learn how to draw
these shapes on screen.