Bresenham Line drawing C program with output


Bresenham line drawing program 

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

#define sign(x) ((x>0)?1:(x<0)?-1:0);

void setPixel(GLint x, GLint y)
{
 glBegin(GL_POINTS);//The basic shapes are referred to as primitives.and glbegin is used to delimit these primitives   // GL_POINTS is an argument of glBegin which consider each vertex as a single points
 glVertex2i(x,y);    /* Plot the first point *///it is use to specify vertex
 glEnd();
}

void init()
{
 glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); //single buffer window
 glutInitWindowPosition(0,0);
 glutInitWindowSize(0,0);
 glutCreateWindow("My Window");

 glClearColor(0.0,0.0,0.0,0.0); /* Set clear color to black */
 glColor3f(1.0,1.0,1.0);     /* Set fill color to white */ //used to specify color & 3f stand for float red , green, blue

 gluOrtho2D(0,640,0,480);    //multiply the current matrix with an orthographic matrix (3 dimentional object into two dimensonal)
}

void bres(int x1,int y1,int x2, int y2)
{
 int dx,dy,x,y,p,s1,s2,length,i;
 dx=abs(x2-x1);
 dy=abs(y2-y1);

 s1=sign(x2-x1);
 s2=sign(y2-y1);

 if(dx>dy)
 length=dx;
 else
 length=dy;

 p=2*dy-dx;

 x=x1;
 y=y1;

 for(i=0;i<=length;i++)
 {
  setPixel(x,y);
  if(p>=0)
  {
   x=x+s1;
   y=y+s2;
   p=p+2*(dy-dx);
  }
  else
  {
   x=x+s1;
   p=p+2*dy;
  }
 }

 glFlush();
}
   
void draw(void)
{
    glClear(GL_COLOR_BUFFER_BIT);

    bres(20,40,620,40);
    bres(620,40,620,440);
    bres(620,440,20,440);
    bres(20,440,20,40);

    bres(320,440,20,240);
    bres(20,240,320,40);
    bres(320,40,620,240);
    bres(620,240,320,440);   

    bres(170,340,170,140);
    bres(170,140,470,140);
    bres(470,140,470,340);
    bres(470,340,170,340);   

    //bres(10,20,18,30);
       

    glFlush();
}

int main(int argc, char **argv)
{
 glutInit(&argc,argv);  /* Initialise GLUT library */
 init();

 glutDisplayFunc(draw);

 glutMainLoop(); //It enters the GLUT event processing loop. This routine should be called at most once in a GLUT program. Once called, this routine will never return

 return 0;
}
 
            

Output



Comments

Popular posts from this blog

Installation steps for openGL on ubuntu

Second Assignment DDA algorithm for line drawing using Mouse