Graphics Reference
In-Depth Information
By default, if glVertexAttribDivisor is not specified or is specified with
divisor equal to 0 for the vertex attributes, then the vertex attributes will
be read once per vertex. If divisor equals 1, then the vertex attributes
will be read once per primitive instance.
The second method is to use the built-in input variable gl_InstanceID as
an index to a buffer in the vertex shader to access the per-instance data.
gl_InstanceID will hold the index of the current primitive instance
when the previously mentioned geometry instancing API calls are used.
When a non-instanced draw call is used, gl_InstanceID will return 0 .
The next two code fragments illustrate how to draw many geometry (i.e.,
cubes) using a single instanced draw call where each cube instance will
be colored uniquely. Note that the complete source code is available in
Chapter_7/Instancing example.
First, we create a color buffer to store many color data to be used later for
the instanced draw call (one color per instance).
// Random color for each instance
{
GLubyte colors[NUM_INSTANCES][4];
int instance;
srandom ( 0 );
for ( instance = 0; instance < NUM_INSTANCES; instance++ )
{
colors[instance][0] = random() % 255;
colors[instance][1] = random() % 255;
colors[instance][2] = random() % 255;
colors[instance][3] = 0;
}
glGenBuffers ( 1, &userData->colorVBO );
glBindBuffer ( GL_ARRAY_BUFFER, userData->colorVBO );
glBufferData ( GL_ARRAY_BUFFER, NUM_INSTANCES * 4, colors,
GL_STATIC_DRAW );
}
After the color buffer has been created and filled, we can bind the color
buffer as one of the vertex attributes for the geometry. Then, we specify
the vertex attribute divisor as 1 so that the color will be read per primitive
instance. Finally, the cubes are drawn with a single instanced draw call.
// Load the instance color buffer
glBindBuffer ( GL_ARRAY_BUFFER, userData->colorVBO );
glVertexAttribPointer ( COLOR_LOC, 4, GL_UNSIGNED_BYTE,
GL_TRUE, 4 * sizeof ( GLubyte ),
( const void * ) NULL );
 
Search WWH ::




Custom Search