2

I was reading Cohen–Sutherland algorithm on Wikipedia and I am confused in these two parts,

int ComputeOutCode(double x, double y) {
    ...
    if (x < xmin)       code |= LEFT;
    else if (x > xmax)  code |= RIGHT;
    if (y < ymin)       code |= BOTTOM;
    else if (y > ymax)  code |= TOP;
    ...
}

and

if (outcodeOut & TOP) {           // point is above the clip rectangle
    x = x0 + (x1 - x0) * (ymax - y0) / (y1 - y0);
    y = ymax;
} else if (outcodeOut & BOTTOM) { // point is below the clip rectangle
    x = x0 + (x1 - x0) * (ymin - y0) / (y1 - y0);
    y = ymin;
} else if (outcodeOut & RIGHT) {  // point is to the right of clip rectangle
    y = y0 + (y1 - y0) * (xmax - x0) / (x1 - x0);
    x = xmax;
} else if (outcodeOut & LEFT) {   // point is to the left of clip rectangle
    y = y0 + (y1 - y0) * (xmin - x0) / (x1 - x0);
    x = xmin;
}

What I am confused is, How does it handle points who are top-left, top right, etc. It just handles top, left, right and bottom.

Why use | in code |= LEFT; and outcodeOut & TOP in if-else below it? I know that these two somehow handle all 8 possible cases but I don't know how.

1
  • 1
    So, slipping into coaching mode: what do you understand |= does?
    – andy256
    Commented Dec 8, 2013 at 20:23

1 Answer 1

3

code is a bit field which uses bitwise boolean operators to store whether certain flags are set or not.

code |= LEFT; is short for code = code | LEFT; and sets the LEFT flag. outcodeOut & LEFT is an expression that is only true (!=0) when the LEFT flag is set.

The shown excerpt does indeed not handle all (16) possible cases at once, but it's part of a larger loop that may run multiple times. So it's done in several iterations.

1
  • Now I am confused how line (200,200)->(900,850) is clipped for clip rectangle (100,100) (800,800). If we use outcodeOut&RIGHT block, it'll get solved. But the algorithm will use TOP block then RIGHT block, but its still solved somehow.
    – Sourabh
    Commented Dec 10, 2013 at 12:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.