Search code examples
c++openglglfwopengl-compat

Merge color vertices at center rather than at one vertex?


I'm trying to make a color swatch tool, where you give it n colors and it makes a n-gon with those colors merging at the center.

So far it just makes an n-gon(without specifying colors, it randomly generates them for now).

However the colors don't merge at the center but rather a single vertex.

Is there any fix to this?

#include <GLFW/glfw3.h>
#include <iostream>
#include <cmath>
float randfloat(){
  float r = ((float)(rand() % 10))/10;
  return r;
}
int main() {
  int side_count;
  std::cout<<"Type the no. of sides: "<<std::endl;
  std::cin>>side_count;
  srand(time(NULL));
  std::cout<<randfloat()<<std::endl;
  std::cout<<randfloat()<<std::endl;
  float rs[side_count];
  float gs[side_count];
  float bs[side_count];
  for (int i=0;i<side_count;i++)
  {
    rs[i] = randfloat();
    gs[i] = randfloat();
    bs[i] = randfloat();
  }
  GLFWwindow* window;
  if (!glfwInit())
    return 1;
  window = glfwCreateWindow(800, 800, "Window", NULL, NULL);
  if (!window) {
    glfwTerminate();
    return 1;
  }
  glfwMakeContextCurrent(window);
  if(glewInit()!=GLEW_OK)
    std::cout<<"Error"<<std::endl;

  while(!glfwWindowShouldClose(window)) {
    glClear(GL_COLOR_BUFFER_BIT);
    glClearColor(0.11f,0.15f,0.17f,1.0f);
    glBegin(GL_POLYGON);
      //glColor3f(1.0f,0.0f,0.0f);glVertex3f(-0.5f,0.0f,0.0f);
      for(int i=0; i<side_count;i++)
      {
        float r = rs[i];
        float g = gs[i];
        float b = bs[i];
        float x = 0.5f * sin(2.0*M_PI*i/side_count);
        float y = 0.5f * cos(2.0*M_PI*i/side_count);
        glColor3f(r,g,b);glVertex2f(x,y);
      }
    glEnd();
    glfwSwapBuffers(window);
    glfwPollEvents();
  }
  glfwTerminate();
  return 0;
}

Solution

  • All you've to do is to add a new point to the GL_POLYGON primitive, in the center of the circular shape:

    glBegin(GL_TRIANGLE_FAN);
    
    glColor3f(0.5f, 0.5f, 0.5f);
    glVertex2f(0, 0);
    
    for(int i=0; i <= side_count; i++)
    {
        float r = rs[i % side_count];
        float g = gs[i % side_count];
        float b = bs[i % side_count];
        float x = 0.5f * sin(2.0*M_PI*i/side_count);
        float y = 0.5f * cos(2.0*M_PI*i/side_count);
        glColor3f(r, g, b);
        glVertex2f(x, y);
    }
    
    glEnd();
    

    Note, you've to define the color for the center point. In the code snippet, I've chosen (0.5, 0.5, 0.5).
    Instead of GL_POLYGON, GL_TRIANGLE_FAN can be used, too.