I wrote an implementation of the Breshenem algorithm in Python (after the Wikipedia article ), and it works correctly, except for lines at certain angles. All lines that should extend from 45 to 90 degrees, or from 135 to 270 degrees, will expand along the line y = x.
Here is my code:
def bresenham(origin, dest):
print origin
print dest
x0 = origin[0]; y0 = origin[1]
x1 = dest[0]; y1 = dest[1]
steep = abs(y1 - y0) > abs(x1 - x0)
backward = x0 > x1
if steep:
x0, y0 = y0, x0
x1, y1 = y1, x1
if backward:
x0, x1 = x1, x0
y0, y1 = y1, y0
dx = x1 - x0
dy = abs(y1 - y0)
error = dx / 2
y = y0
if y0 < y1: ystep = 1
else: ystep = -1
result = []
print "x0 = %d" % (x0)
print "x1 = %d" % (x1)
print "y0 = %d" % (y0)
print "y1 = %d" % (y1)
for x in range(x0, x1):
if steep: result.append((y,x))
else: result.append((x,y))
error -= dy
if error < 0:
y += ystep
error += dx
if backward: result.reverse()
print result
return result
Does anyone see me screwing up?
EDIT:
I added some print code to the function.
(0,0) is located in the upper left corner of the display.
My test framework is pretty simple. This is a standalone function, so I just pass two points to it:
= (416, 384)
dest = (440, 347)
bresenham (, dest)
(416, 384)
(440, 347)
x0 = 384
x1 = 347
y0 = 416
y1 = 440
[]