Sunday, December 14, 2014

Smiley using Bresenham's Circle Drawing in OpenGL


#include <stdio.h>
#include <GL/glut.h>

// Center of the cicle = (320, 240)
int xc = 320, yc = 240;

// Plot two points on the lower quadrants 
// using circle's symmetrical property
void plot_point(int x, int y)
{
  glBegin(GL_POINTS);
  glVertex2i(xc+x, yc-y);
  glVertex2i(xc-x, yc-y);
  glEnd();
}

// Function to draw a circle using bresenham's
// circle drawing algorithm
void bresenham_circle(int r)
{
  int x=0,y=r;
  float pk=(5.0/4.0)-r;

  /* Plot the points */
  plot_point(x,y);
  int k;
  /* Find all vertices till x=y */
  while(x < y)
  {
    x = x + 1;
    if(pk < 0)
      pk = pk + 2*x+1;
    else
    {
      y = y - 1;
      pk = pk + 2*(x - y) + 1;
    }
    plot_point(x,y);
  }
}

// Function to draw a smiley
void smiley(void)
{
  /* Clears buffers to preset values */
  glClear(GL_COLOR_BUFFER_BIT);

  int radius = 100;
  // Draw an arc
  bresenham_circle(radius);

  // Draw a vertical line
  glBegin(GL_LINES);
  glVertex2i(xc, yc);
  glVertex2i(xc, yc-60);
  glEnd();

  // Draw 2 points on either side 
  // of the line
  glBegin(GL_POINTS);
  // A big dot made of 4 small dots
  // to the left of the line
  glVertex2i(xc-20, yc-20);
  glVertex2i(xc-19, yc-20);
  glVertex2i(xc-20, yc-19);
  glVertex2i(xc-19, yc-19);

  // A big dot made of 4 small dots
  // to the right of the line
  glVertex2i(xc+20, yc-20);
  glVertex2i(xc+21, yc-20);
  glVertex2i(xc+21, yc-19);
  glVertex2i(xc+20, yc-19);
  glEnd();
  glFlush();
}

void Init()
{
  /* Set clear color to black */
  glClearColor(0.0,0.0,0.0,0);
  /* Set fill color to white*/
  glColor3f(1.0,1.0,1.0);
  gluOrtho2D(0 , 640 , 0 , 480);
}

void main(int argc, char **argv)
{
  /* Initialise GLUT library */
  glutInit(&argc,argv);
  /* Set the initial display mode */
  glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
  /* Set the initial window position and size */
  glutInitWindowPosition(0,0);
  glutInitWindowSize(640,480);
  /* Create the window with title "DDA_Line" */
  glutCreateWindow("Smiley :-)");
  /* Initialize drawing colors */
  Init();
  /* Call the displaying function */
  glutDisplayFunc(smiley);
  /* Keep displaying untill the program is closed */
  glutMainLoop();
}

Output
=====


Written by

No comments:

Post a Comment