PDA

View Full Version : polygon vertices coloring



oufyal
01-21-2011, 08:05 PM
I'm new to OpenGL and have been trying to get this working for a while. Any help would be appreciated.
I am trying to color each vertex of a square using smooth shading according to key presses. For example when I push 1 on the keyboard that vertex alone changes color to red. In my code below, the coloring is flat and as a result the whole square changes color to red.
My understanding is that glut uses a loop that keeps refreshing the image, in this case my polygon and therfore included glBegin90 and glEnd() like in the last if statement in the code below to no avail. I have also tried different approaches such as removing the glShadeModel(GL_SMOOTH) in the if statements with no success.
If I just set the color of each vertex in my display() function it displays the colors as it should using smooth shading that is default in opengl.
I'm seeking an explanation of how to setup the keypress function to change the color of each vertex individually according to various key presses. Thanks in advance

void keyPress(unsigned char key, int x, int y) {


if(key == '1') {
// set to smooth color shading
glShadeModel(GL_SMOOTH);
glColor3f(1.0, 0.0, 0.0);
glVertex2f(-0.5, -0.5);


}
else if(key == '2') {
// set to smooth color shading
glShadeModel(GL_SMOOTH);
glColor3f(0.0, 1.0, 0.0);
glVertex2f(-0.5, 0.5);

}
else if(key == '3') {
glColor3f(0.0, 0.0, 1.0);
glVertex2f(0.5, 0.5);

glColor3f(1.0, 1.0, 1.0);
glVertex2f(-0.5, -0.5);
glColor3f(1.0, 1.0, 1.0);
glVertex2f(-0.5, 0.5);
glColor3f(1.0, 1.0, 1.0);
glVertex2f(0.5, -0.5);


}
else if(key == '4') {


glBegin(GL_POLYGON);

glColor3f(1.0, 1.0, 0.0);
glVertex2f(0.5, -0.5);

glColor3f(1.0, 0.0, 1.0);
glVertex2f(-0.5, -0.5);
glColor3f(0.0, 1.0, 1.0);
glVertex2f(-0.5, 0.5);
glColor3f(0.0, 0.0, 1.0);
glVertex2f(0.5, 0.5);

glEnd();


}
else if(key == 'q' || key == 'Q') {
exit(0);
}
glutPostRedisplay();
}

mobeen
01-21-2011, 08:34 PM
Hi,
You must always put the glColor* and glVertex* calls inside glBegin/glEnd block. And its better to keep the rendering code in the display function. I think if you want to change the color of individual vertices, you need to store the colors into an array of the size of your vertices. Thus the colors[i] is for vertices[i]. Then in your keyboard handler, just use something like this,


void OnKey(unsigned char key, int x, int y) {
switch(key) {
case '1':
case '8':
int index = (int)(key-'1');
colors[index]=<yournewcolor>;
break;
}
}

Your render code will simply loop through all vertices and render them based on their colors.


//in render code after glClear and matrix handling

glBegin(GL_POLYGON);
for(int i=0;i<8;i++) {
glColor3fv(colors[i]);
glVertex3fv(vertices[i]);
}
glEnd();

oufyal
01-22-2011, 05:21 AM
I will give that a try. Thanks a lot for your quick response.