Game Development Reference
In-Depth Information
Here's what we did wrong in this example in terms of OpenGL ES best practices:
ï?®
We set the same states to the same values over and over again without any
need. State changes in OpenGL ES are expensive—some a little bit more,
others a little bit less. We should always try to reduce the number of state
changes we make in a single frame.
ï?®
The viewport and projection matrix will never change once we set them.
We could move that code to the resume() method, which is only called
once each time the OpenGL ES surface gets (re-)created; this also handles
OpenGL ES context loss.
ï?®
We could also move setting the color used for clearing and setting the
default vertex color to the resume() method. These two colors won't
change either.
glEnableClientState() and glVertexPointer()
methods to the resume() method.
The only things that we need to call each frame are
ï?®
We could move the
glClear() and
glDrawArrays() . Both use the current OpenGL ES states, which will stay the
same as long as we don't change them and as long as we don't lose the
context due to the Activity being paused and resumed.
If we had put these optimizations into practice, we would have only two OpenGL ES calls in our
main loop. For the sake of clarity, we'll refrain from using these kinds of minimal state change
optimizations for now. When we start writing our first OpenGL ES game, though, we'll have to
follow those practices as best as we can to guarantee good performance.
ï?®
Let's add some more attributes to our triangle's vertices, starting with color.
Note Very, very alert readers might have noticed that the triangle in Figure 7-7 is actually
missing a pixel in the bottom-right corner. This may look like a typical off-by-one error, but it's
actually due to the way OpenGL ES rasterizes (draws the pixels of) the triangle. There's a specific
triangle rasterization rule that is responsible for that artifact. Worry not—we are mostly concerned
with rendering 2D rectangles (composed of two triangles), where this effect will vanish.
Specifying Per-Vertex Color
In the previous example, we set a global default color for all vertices we drew via glColor4f() .
Sometimes we want to have more granular control (for example, we want to set a color per
vertex). OpenGL ES offers us this functionality, and it's really easy to use. All we have to do is
add RGBA float components to each vertex and tell OpenGL ES where it can find the color for
each vertex, similar to how we told it where it can find the position for each vertex. Let's start by
adding the colors to each vertex.
 
 
Search WWH ::




Custom Search