Bresenham's Line Drawing Algorithm Generalized Code[All slopes]
Recently I was encountered with the Bresenham's Line Drawing Algorithm. If you want to know more about it Google is your friend and here is a nice Proof that I found. It has four different condition and with little variation. So instead of writing four functions for 4 different Slopes, here I wrote one function that works for all. The trick is to pass the parameters according to the slopes and use the same function instead of using 4 different function.Here is the code in OpenGl.
#include <GL/glut.h>
#include <iostream>
using namespace std;
int a, b, c, d, flag;
void init() {
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glMatrixMode(GL_PROJECTION);
gluOrtho2D(-160.0, 160.0, -160.0, 160.0);
}
void PutPixel(int x, int y) {
glColor3f(1.0f, 0.0, 0.0);
glBegin(GL_POINTS);
if(flag)
glVertex2i(y,x);
else
glVertex2i(x, y);
glEnd();
}
//The Generalized Function, sweet ans Short.
//First three parameters only required, rest if made global need not be passed.
void bresenhamGen(int x, int y, int p, int dx, int dy, int limit, int xinc, int yinc) {
if(limit < 0) {
return;
}
PutPixel(x, y);
if(p < 0)
bresenhamGen(x + xinc, y, p + 2*dy, dx, dy, limit - 1, xinc, yinc);
else {
bresenhamGen(x + xinc, y + yinc, p + (2*dy - 2*dx), dx, dy, limit - 1, xinc, yinc);
}
}
//checking the slope ans calling the function accordingly.
void bresenham(int x1 , int y1, int x2, int y2) {
if(x1 > x2) {
swap(x1, x2);swap(y1, y2);
}
int dx, dy;
dx = x2 - x1;
dy = y2 - y1;
float m = (float)dy/dx;
if(m > 0 && m < 1) {
flag = 0;
bresenhamGen(x1, y1, 2*dy - dx, dx, dy, x2 - x1, 1, 1);
}
else if(m >= 1) {
flag = 1;
bresenhamGen(y1, x1, 2*dx - dy, dy, dx, y2-y1, 1, 1);
}
else if(m < -1.0) {
flag = 1;
bresenhamGen(y1, x1, 2*dx + dy, -1*dy, dx, y1 - y2, -1, 1);
}
else if(m >= - 1) {
flag = 0;
bresenhamGen(x1, y1, -2*dy - dx, dx, -1*dy, x2 - x1, 1, -1);
}
}
void display() {
glClear(GL_COLOR_BUFFER_BIT);
bresenham(a, b, c, d);
glFlush();
}
int main(int argc, char **argv) {
cin>>a>>b>>c>>d;
glutInit(&argc, argv);
glutCreateWindow("Bresenham");
glutInitWindowSize(320, 320);
glutInitWindowPosition(100, 100);
glutDisplayFunc(display);
init();
glutMainLoop();
return 0;
}








