cooltechnomax
cooltechnomax

Reputation: 701

How to specify color per primitive for glDrawElements()

I want to render an indexed geometry. So, I have a bunch of vertices and associated sequenced indices. I am using glDrawElements() to render 2 quads as given below. Now, I know I can use glColorPointer() for specifying color per vertex. My question is: Can I specify color per primitive? If yes, then how should I do it for this indexed geometry?

static GLint vertices[] ={0,0,0,
                         1,0,0,
                         1,1,0,
                         0,1,0,
                         0,0,1,
                         0,1,1};
static GLubyte indices[]={0,1,2,3,
                          0,3,5,4}
glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_VERTEXARRAY);
//glColorPointer(3, GL_FLOAT,0,colors);
glVertexPointer(3,GL_INT,0,vertices);
glDrawElements( GL_QUADS, sizeof( indices ) / sizeof( GLubyte ), GL_UNSIGNED_BYTE, indices );

Upvotes: 7

Views: 8635

Answers (2)

Harshad Untwale
Harshad Untwale

Reputation: 89

When you are using indices, you specify a vertex value only once and assign a particular value to a vertex. So in your case you cant assign different colors for points with indices 0 and 3, if you want to have different colors for two quads.

Since the points are less in number you can use GLDrawArrays and pass the values as

GLint vertices[] = {

0,0,0,
1,0,0,
1,1,0,
0,1,0,

0,0,0,
0,1,0,
-1,1,0,
-1,0,0

};

GLubyte colors[] = {

255, 0, 0,
255, 0, 0,
255, 0, 0,
255, 0, 0,

0, 0, 255,
0, 0, 255,
0, 0, 255,
0, 0, 255,

};

. . .

glColorPointer( 3, GL_UNSIGNED_BYTE, 0, colors );

glVertexPointer( 3, GL_INT, 0, vertices );

glDrawArrays(GL_QUADS, 0, 8);

Upvotes: 0

genpfault
genpfault

Reputation: 52083

You can use glDrawElements() and per-vertex colors like this:

GLint vertices[] =
{
    0,0,0,
    1,0,0,
    1,1,0,
    0,1,0,
    -1,1,0,
    -1,0,0,
};

GLubyte colors[] =
{
    255, 0, 0,
    0, 255, 0,
    0, 0, 255,
    255, 255, 0,
    255, 0, 255,
    0, 255, 255,
};

GLubyte indices[]=
{
    0,1,2,3,
    0,3,4,5,
};

glEnableClientState( GL_COLOR_ARRAY );
glEnableClientState( GL_VERTEX_ARRAY );
glColorPointer( 3, GL_UNSIGNED_BYTE, 0, colors );
glVertexPointer( 3, GL_INT, 0, vertices );
glDrawElements( GL_QUADS, sizeof( indices ) / sizeof( GLubyte ), GL_UNSIGNED_BYTE, indices );

Upvotes: 4

Related Questions