Our Feeds

Wednesday, 16 November 2016

AJITH KP

OpenGL: Bresensham's Line Drawing Algorithm

Hello GuyZ,
     Here I would like to share the OpenGL code to implement Bresensham algorithm. This algorithm can solve both |m| < 1 (|slope| < 1) condition and also |m| > 1 (|slope| > 1) condition.


Code

#include <gl/glut.h>
#include <Windows.h>
#include <iostream>
using namespace std;
/*
c0ded by (c) Ajith Kp (c) (R) _TERMINAL_CODERS_ (R)
*/
void line() {
 glColor3f(1.0, 0.0, 0.0);
 glPointSize(2.0);
 int x1, y1, x2, y2;
 cout << "Enter starting point (x, y): ";
 cin >> x1 >> y1;
 cout << "Enter end point (x, y): ";
 cin >> x2 >> y2;
 int s, o, sEnd, oEnd, dx = abs(x2 - x1), dy = abs(y2 - y1);
 int nInc, pInc, p;
 float m = (float)(y2 - y1) / (x2 - x1);
 // |slope| < 1 condition
 if (m < 1 && m>-1) {
  nInc = 2 * dy;
  pInc = 2 * (dy - dx);
  p = 2 * dy - dx;
  if (x1 < x2) {
   s = x1;
   o = y1;
   sEnd = x2;
   oEnd = y2;
  }
  else {
   s = x2;
   o = y2;
   sEnd = x1;
   oEnd = y1;
  }
 }
 // |slope| > 1 condition
 else {
  nInc = 2 * dx;
  pInc = 2 * (dx - dy);
  p = 2 * dx - dy;
  if (y1 < y2) {
   s = y1;
   o = x1;
   sEnd = y2;
   oEnd = x2;
  }
  else {
   s = y2;
   o = x2;
   sEnd = y1;
   oEnd = x1;
  }
 }
 glBegin(GL_POINTS);
 while (s < sEnd) {
  s++;
  if (p < 0) {
   p += nInc;
  }
  else {
   p += pInc;
   if (o < oEnd)
    o++;
   else
    o--;
  }
  if (m > -1 && m < 1)
   glVertex2i(s, o);
  else
   glVertex2i(o, s);
 }
 glEnd();
 glFlush();
}
int main(int argc, char ** argv) {
 glutInit(&argc, argv);
 glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
 glutInitWindowSize(500, 500);
 glutInitWindowPosition(100, 100);
 glutCreateWindow("Line Draw OpenGL");

 glClearColor(1.0, 1.0, 1.0, 1.0);
 glClear(GL_COLOR_BUFFER_BIT);
 gluOrtho2D(0, 500, 0, 500);
 glMatrixMode(GL_PROJECTION);
 glViewport(0, 0, 500, 500);

 glutDisplayFunc(line);
 glutMainLoop();
 return 0;
}