Based on Wikipedia’s article on Bresenham’s line algorithm I’ve implemented the simplified version described there, my Java implementation looks like this:
int dx = Math.abs(x2 - x1);
int dy = Math.abs(y2 - y1);
int sx = (x1 < x2) ? 1 : -1;
int sy = (y1 < y2) ? 1 : -1;
int err = dx - dy;
while (true) {
framebuffer.setPixel(x1, y1, Vec3.one);
if (x1 == x2 && y1 == y2) {
break;
}
int e2 = 2 * err;
if (e2 > -dy) {
err = err - dy;
x1 = x1 + sx;
}
if (e2 < dx) {
err = err + dx;
y1 = y1 + sy;
}
}
Now I do understand that err controls the ratio between steps on the x-axis compared to steps on the y-axis – but now that I’m supposed to document what the code is doing I fail to clearly express, what it is for, and why exactly the if-statements are, how they are, and why err is changed in the way as seen in the code.
Wikipedia doesn’t point to any more detailled explanations or sources, so I’m wondering:
What precisely does err do and why are dx and dy used in exactly the shown way to maintain the correct ratio between horizontal and vertical steps using this simplified version of Bresenham’s line algorithm?
There are various forms of equations for a line, one of the most familiar being
y=m*x+b. Now ifm=dy/dxandc = dx*b, thendx*y = dy*x + c. Writingf(x) = dy*x - dx*y + c, we havef(x,y) = 0iff(x,y)is a point on given line.If you advance
xone unit,f(x,y)changes bydy; if you advanceyone unit,f(x,y)changes bydx.In your code,
errrepresents the current value of the linear functionalf(x,y), and the statement sequencesand
represent advancing
xoryone unit (insxorsydirection), with consequent effect on the function value. As noted before,f(x,y)is zero for points on the line; it is positive for points on one side of the line, and negative for those on the other. Theiftests determine whether advancingxwill stay closer to the desired line than advancingy, or vice versa, or both.The initialization
err = dx - dy;is designed to minimize offset error; if you blow up your plotting scale, you’ll see that your computed line may not be centered on the desired line with different initializations.