Search code examples
algorithmroundingclippingline-segment

Why do we need to round when computing x-intercept of horizontal line in Cohen-Sutherland clipping algorithm?


I'm studying computer graphics and came across Cohen-Sutherland line clipping algorithm. Where we have a line segment defined by the points P1 and P2 and we're trying to find out whether it's getting clipped within a clipping rectangle (usually defined by the width and height of the screen and the top left is [0, 0])

The algorithm is simple we just check each point to see if the point's x and y are out of bounds:

if (y1 < min_clip_y)
        p1_code |= CLIP_NORTH;
else if (y1 > max_clip_y)
        p1_code |= CLIP_SOUTH;

if (x1 < min_clip_x)
        p1_code |= CLIP_WEST;
else if (x1 > max_clip_x)
        p1_code |= CLIP_EAST;

// Same deal with x2, y2

if both p1_code and p2_code are not equal to zero we reject the line, if they're both zero we accept it, otherwise we continue testing to find the clip intersection point with the clipping rectangle edge of intersection:

switch(p1_code)
{
    case CLIP_NORTH:
    {
         yc1 = min_clip_y;
         xc1 = x1 + 0.5f + (min_clip_y - y1) * (x2-x1) / (y2-y1);
    } break;

    // other cases...
}

I read this from a book. I understand how we deduce the equation of the x-intercept, I Just don't get why we're adding 0.5f to round to the next integer. Why do we need to round?

Thanks!


Solution

  • Many computer graphics texts have mistakes like this. C-S was invented ~50 years ago when floating point was hugely slower than integer math, so the norm was to use integer arithmetic or integer instructions to emulate fixed point. The result is that there are weird re-implementations of old code that transplant the old fixed point with floating point. This is apparently one of them.

    As you suspect, you'd want to do the entire computation with floating point and then round to the nearest pixel if absolutely required at the end. But with modern GPUs, you might even skip that, since anti-aliased line-drawing would do the right thing with floating point coordinates.

    In fact, it's strange that graphics texts still feature line clipping so prominently, since modern graphics are so much more about polygons. There are loads of nice triangle and polygon algorithms that have more practical importance than line clipping. Too many textbook authors are slaves to the tools of their apprenticeship.