I’ve been tasked to draw eight lines, forming something like a regular eight-point star, with Bresenham’s line drawing algorithm. It was to be done in Delphi language. As I’m not really good at canvas drawing, I simply copy-pasted the algorithm from Wikipedia for Object Pascal, with minimum changes.
But the Wikipedian algorithm had the Sign(x) function, that wasn’t included in Delphi standard libraries, so I had to write it myself:
function Sign(x:integer):integer;
begin
if x=0 then Result:=0;
if x>0 then Result:=1;
else Result:=-1;
end;
Everything worked fine, but I could only operate in first two quadrants, other coordinates were mirrored.
I changed function to display errors:
function Sign(x:integer):integer;
begin
if x=0 then Result:=0;
if x>0 then Result:=1;
if x<0 then Result:=-1 else begin
Form1.Label5.Caption:='Err!';
Result:=2;
end;
end;
I used this function as following:
sx:=Sign(x1-x0);
sy:=Sign(y1-y0);
x0,x1,y0,y1 are coordinates of line begin and end points. I am confused, it seems that sometimes x1-x0 and y1-y0 are not not less, more or equal to zero, but fall under the 4th ‘else’ statement. Could you please explain the humble beginner, why does it happen?
P.S. I got that program to work, by changing the 4th ‘else’ statement to Result in 1, but still confused of this situation.
Thank you in advance.
You’re missing an else before the second if. So 0 falls both into the =0 case and the else case of >0.
And there is a Sign function in the Math unit.
And you could have tested your function with parameters -2,-1,0,+1,+2 to see what happens.