Question

I am trying to implement Bresenham's line algorithm in c, the wikipedia simplified version. My code gets stuck to an infinite loop and i cannot figure out why! (While im pretty sure it has to do with my c knowledge)

void Draw_line (unsigned int x0, unsigned int y0,unsigned int x1, unsigned int y1)
{
    unsigned int dx = abs(x1-x0);
    unsigned int dy = abs(y1-y0);
    signed short sx,sy;
    signed int err,e2;

    if (x0 < x1) {sx = 1;} else {sx = -1;}
    if (y0 < y1) {sy = 1;} else {sy = -1;}
    err = dx-dy;

    while (!(x0==x1 && y0==y1))
    {
        GLCD_PutPixel(x0, y0);
        e2 = 2*err;
        if (e2 > -dy) 
        {
            err = err - dy;
            x0 += sx;
        }
        if (e2 < dx) 
        {
            err = err + dx;
            y0 += sy;
        }
    }
}

Thanks!

EDIT: The conditional of the loop was wrong so it did not plot straight lines, changed it to the correct one.

Was it helpful?

Solution

Could it be that dy is an unsigned value so -dy is positive (and likely quite large) still (not negative). removing the unsigneds should fix it.

OTHER TIPS

After accept answer.

Changing to signed integer does not solve the problem in the general case, but may have solved it in @OP's limited case.

Changing to int works so long as the x,y points are not in the extreme range as obviously the below overflows (UB) for all sorts of large values of x0,x1 as int or unsigned.

int dx = abs(x1-x0);

I think as long as the parameters are |x| < INT_MAX/2, all is OK.


A general solution that handles all combinations of inputs needs careful handling.

[Edit]

As OP does not need a full range solution (and being a bit lazy), I'll postpone digging up and posting the general solution.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top