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!