Home > Blockchain >  Change color of single entity in OpenGL scene?
Change color of single entity in OpenGL scene?

Time:10-30

I'm trying to change the color of a single polygon shape (quads) in my exercises using legacy OpenGL (Freeglut Glew), but obviously when i call glColor3f the colors of the entire models (texts included) in the scene get overwritten by the new color state set by the function.

The code is fairly simple:

void drawScene(void) {

// Cleaning procedures 
glClear(GL_COLOR_BUFFER_BIT);

// Setting the color of the models as green
glColor3f(0.0, 1.0, 0.0);

// Drawing a square that will rotate based on the mouse coord on the screen
glPushMatrix();
glRotated(theta, 0.0, 0.0, 1.0);

glBegin(GL_QUADS);

// HERE: i'd like to change only the color of the square, but instead  
// everything get modified to the new color.
glColor3f(colors.r, colors.g, colors.b);
glVertex3f(-2.0, 2.0, 0.0);
glVertex3f(-2.0, -2.0, 0.0);
glVertex3f(2.0, -2.0, 0.0);
glVertex3f(2.0, 2.0, 0.0);
glEnd();
glPopMatrix();
 
// Text formatting
auto coords = std::format("Mouse coordinate is x ({}) , y ({})", xm, ym);
auto angle = std::format("Rotation angle is {}", xm/10);

glRasterPos3f(-6.0, -6.0, 0.0);
writeBitmapString(GLUT_BITMAP_9_BY_15, coords.data());

glRasterPos3f(-6.0, -8.0, 0.0);
writeBitmapString(GLUT_BITMAP_9_BY_15, angle.data());

// Swapping buffer to the back and front
glutSwapBuffers();

}

Any suggestion on how to achieve single coloring on a model?

CodePudding user response:

glColor3f sets a global state. This state is kept until it is changed again. Set the state explicitly before each object. Alternatively, you can reset the color attribute to "white" after drawing an object.

glColor3f(colors.r, colors.g, colors.b);

glBegin(GL_QUADS);
glVertex3f(-2.0, 2.0, 0.0);
glVertex3f(-2.0, -2.0, 0.0);
glVertex3f(2.0, -2.0, 0.0);
glVertex3f(2.0, 2.0, 0.0);
glEnd();

glColor3f(1.0f, 1.0f, 1.0f);
  • Related