February 25, 2021, 02:52:13 AM

Author Topic: [bmx] Besenham's LineDraw routine (integer math only) by ImaginaryHuman [ 1+ years ago ]  (Read 1390 times)

Offline BlitzBot

  • Jr. Member
  • **
  • Posts: 1
Title : Besenham's LineDraw routine (integer math only)
Author : ImaginaryHuman
Posted : 1+ years ago

Description : This program is a conversion from a C program taken from the Wikipedia, based on the line-drawing algorithm by Mr Bresenham. It uses purely Integer math only - absolutely no floats. It plots one pixel at a time. Clipping is handled by the standard clipping of the backbuffer, by the graphics hardware for each pixel plotted (which is a Vertex in OpenGL). This isn't an OpenGL-dependent routine, you can easily use some other Plot routine. Each pixel can be a different color, or you could skip pixels, do dotted/dashed lines, marching ants, etc

Code :
Code: BlitzMax
  1. 'Bresenham linedraw in BlitzMax, adapted from C code
  3. Strict
  4. Graphics 640,480,0
  5. Repeat
  6.         Cls
  7.         Line(320,240,MouseX(),MouseY())
  8.         Flip
  9. Until KeyHit(KEY_ESCAPE)
  10. End
  12. Function Line(X1:Int,Y1:Int,X2:Int,Y2:Int)
  13.         'Draws a line of individual pixels from X1,Y1 to X2,Y2 at any angle
  14.         Local Steep:Int=Abs(Y2-Y1) > Abs(X2-X1)                 'Boolean
  15.         If Steep
  16.                 Local Temp:Int=X1; X1=Y1; Y1=Temp               'Swap X1,Y1
  17.                 Temp=X2; X2=Y2; Y2=Temp         'Swap X2,Y2
  18.         EndIf
  19.         Local DeltaX:Int=Abs(X2-X1)             'X Difference
  20.         Local DeltaY:Int=Abs(Y2-Y1)             'Y Difference
  21.         Local Error:Int=0               'Overflow counter
  22.         Local DeltaError:Int=DeltaY             'Counter adder
  23.         Local X:Int=X1          'Start at X1,Y1
  24.         Local Y:Int=Y1         
  25.         Local XStep:Int
  26.         Local YStep:Int
  27.         If X1<X2 Then XStep=1 Else XStep=-1     'Direction
  28.         If Y1<Y2 Then YStep=1 Else YStep=-1     'Direction
  29.         If Steep Then Plot(Y,X) Else Plot(X,Y)          'Draw
  30.         While X<>X2
  31.                 X:+XStep                'Move in X
  32.                 Error:+DeltaError               'Add to counter
  33.                 If (Error Shl 1)>DeltaX         'Would it overflow?
  34.                         Y:+YStep                'Move in Y
  35.                         Error=Error-DeltaX              'Overflow/wrap the counter
  36.                 EndIf
  37.                 If Steep Then Plot(Y,X) Else Plot(X,Y)          'Draw
  38.         Wend
  39. End Function

Comments : none...


SimplePortal 2.3.6 © 2008-2014, SimplePortal