Bresenham's line algorithm

BlitzMax Forums/BlitzMax Programming/Bresenham's line algorithm

Bresenham's doesn't have anything to do with using floats and it doesn't have anything to do with having separate xsteps and ysteps detached from the loopcounter. It's meant to be really straightforward. Once you've set up the initial values, the main loop is basically stepping through one of the directions one pixel at a time, and then occasionally when there is counter overflow, stepping one pixel in the other direction. There is nothing more to it. I think that original program is cheating and is not `pure` bresenhams.

Here is some code which portrays the basic bresenhams algorithm, but it only draws when x2>x1 and y2>y1, it doesn't have the swappping and absolutes etc as seen in the one above. Easily adapted though. Also it is ENTIRELY integer math, not sneaky use of floats anywhere, which is how bresenhams is supposed to be used. If you're gunna use floats in it you might as well make an entire float routine which is really easy.

'Bresenham lines in BlitzMax
Strict
Graphics 640,480,0

Local x1,y1,x2,y2,xdiff,ydiff,xdiff2,ydiff2,counter,x,y:Int
Repeat
	Cls
	x1:Int=320
	y1:Int=240
	x2=MouseX()
	y2=MouseY()
	If (x1=x2) And (y1=y2)	'Avoid infinite loop
		SetColor Rand(0,255),Rand(0,255),Rand(0,255)
		Plot x1,y1
	Else
		xdiff=x2-x1	'Distances between start and end
		ydiff=y2-y1
		xdiff2=xdiff	'Backup
		ydiff2=ydiff
		While (xdiff & $FFFFFFFE=xdiff) And (ydiff & $FFFFFFFE=ydiff)	'If dividing by 2 still gives integers
			xdiff:/2	'Okay to make smaller
			ydiff:/2
		Wend
		If xdiff>ydiff	'If doing a line that is wider than tall
			y=y1
			counter=0
			For x=x1 To x1+(xdiff2-1) Step 1		'Move 1 pixel in X each loop
				SetColor Rand(0,255),Rand(0,255),Rand(0,255)
				Plot x,y
				counter:+ydiff
				If counter>xdiff
					counter:-xdiff
					y:+1		'Only move in Y when there is overflow
				EndIf
			Next	
		Else		'Doing a line that is taller than wide
			x=x1
			counter=0
			For y:Int=y1 To y1+(ydiff2-1) Step 1		'Move 1 pixel in Y each loop
				SetColor Rand(0,255),Rand(0,255),Rand(0,255)
				Plot x,y
				counter:+xdiff
				If counter>ydiff
					counter:-ydiff
					x:+1		'Only move in X when there is overflow
				EndIf
			Next
		EndIf		
	EndIf
	Flip
Until KeyHit(KEY_ESCAPE)
End