Wednesday, November 07, 2007

Example 2-10 : Using glArrayElement() to Define Colors and Vertices

Vertex arrays! Huzzah, now I finally know what they mean.

The code goes like this:

# Example 2-10 : Using glArrayElement() to Define Colors and Vertices
# (Using vertices & colors variables defined in Example 2-9)

from pyglet.gl import *
from pyglet import window

win = window.Window()

def display():

vertices = [25, 25,
100, 325,
175, 25,
175, 325,
250, 25,
325, 325]
colors = [1.0, 0.2, 0.2,
0.2, 0.2, 1.0,
0.8, 1.0, 0.2,
0.75, 0.75, 0.75,
0.35, 0.35, 0.35,
0.5, 0.5, 0.5]

glEnableClientState (GL_COLOR_ARRAY)
glEnableClientState (GL_VERTEX_ARRAY)

glColorPointer (3, GL_FLOAT, 0, (GLfloat * len(colors))(*colors));
glVertexPointer (2, GL_INT, 0, (GLint * len(vertices))(*vertices));

glBegin(GL_TRIANGLES)
glArrayElement (2)
glArrayElement (3)
glArrayElement (5)
glEnd()

def init():
glClearColor (0.0, 0.0, 0.0, 0.0)
glShadeModel (GL_FLAT)

while not win.has_exit:
win.dispatch_events()
win.clear()
display()
win.flip()


glArrayElement() allows you to use a vertex predefined in an array via glVertexPointer(). An easy example, but it an important one, as vertex arrays allow us to drastically optimise our code by reducing the number of function calls.

No comments: