Question

There Is Something In Bresenham's Floating Point Algorithm which annoying me.

The Algorithm is listed below :

void line(x0, x1, y0, y1)
{
  int deltax = x1 - x0;
  int deltay = y1 - y0;
  float error = 0;
  float deltaerr = Math.abs((float)deltay / (float)deltax);
  int y = y0

  for(int x=x0;x<=x1;x++)
  {
    SetPixel(x,y)
    error = error + deltaerr
    if (error >= 0.5)
    {
             y = y + 1
             error = error - 1.0
    }
  }
}

Suppose We Want to Draw Y=0.6X. So In the first step for x=0 : error will be set as 0.6 and we will run into if statement and y will increases. and error will be set to -0.4. how can the -0.4 will help us in next step?

So My problem is with this line of code :

error = error - 1.0

Why we should decease error by 1 ? I have read we do this because of readjustment ! how it can help us ?

Was it helpful?

Solution

Error is accumulated. When it is greater than half a pixel, the line is moved one pixel over, and the error must then be corrected, again by a whole pixel.

If you simply zero'd the error out, you would only have cancelled out part of the error, and thus the line will step again prematurely and would be the wrong gradient.

In your example for y = 0.6x, if you calculate the error but zero it out, the following happens:

error = 0;
plot pixel;
increment error. error = 0.6;
error > 0.5, so move over and reset error to 0;
plot pixel;
increment error. error = 0.6;
error > 0.5, so move over and reset error to 0;
plot pixel;
increment error. error = 0.6;
error > 0.5, so move over and reset error to 0;
...

So the line actually has a gradient of 1; Indeed any line with a gradient >= 0.5 will come out the same, which is obviously not very useful.

If you do it correctly:

error = 0;
plot pixel;
increment error. error = 0.6;
error > 0.5, so move over and subtract one; error = -0.4;
plot pixel;
increment error. error = 0.2;
plot pixel;
increment error. error = 0.8;
error > 0.5, so move over and subtract one; error = -0.2;
...

The line has the correct gradient, because the error is acting as the fractional part of a fixed-point calculation.

OTHER TIPS

error is ideal_y-current_y

When we entered into a next iteration of the loop we increased x without touching y. error=error+deltaerr is update of error after this operation.

If we decided to increment y, we again must update error, that's what error=error-1 is.

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