Genius Bresenham Line Algorithm Impl. - How Does It Work?
Posted: Thu May 03, 2018 11:46 pm
I found this line drawing algorithm (among others) on GitHub: https://gist.github.com/bert/1085538#file-plot_line-c
I've modified it slightly for my own reading preferences and understanding and with some questions:
So I've been trying to wrap my brain around the basics Bresenham's line algorithm, I can understand the floating point variations I've seen (which involve the use of a slope variable), but not this. This implementation is so succinct and simple and works so perfectly, compared to the other ones I've seen, I think it's genius, but I can't fully understand how it determines moving next X, and/or next Y. I kind of get it but not fully.
Could someone with more of a mathematical brain explain it in plain English without formulas/mathematical notation, and possibly the general thinking process behind something like this?
I've modified it slightly for my own reading preferences and understanding and with some questions:
Code: Select all
int sx; int sy; // Is S sign or slope? Either way it's the increment or decrement.
if (x0 < x1) sx = 1; else sx = -1;
if (y0 < y1) sy = 1; else sy = -1;
int dx = iabs(x1 - x0);
int dy = -iabs(y1 - y0); // Negative absolute distance. It's negative for the algorithm.
int err = dx + dy;
int e2; // Error * 2
while (true) {
GFXPlot(gfx, x0, y0, colour);
if (x0 == x1 && y0 == y1) break;
e2 = (err << 1);
// This is where the selection happens. If e2 is larger than the negative value in Y delta, increment X.
// If e2 is smaller than the positive value in X delta, increment Y.
if (e2 >= dy) { err += dy; x0 += sx; } // err += dy actually subtracts EACH TIME due to Y delta being negative.
if (e2 <= dx) { err += dx; y0 += sy; }
}
Could someone with more of a mathematical brain explain it in plain English without formulas/mathematical notation, and possibly the general thinking process behind something like this?