2.5.2 Cohen-Sutherland Line-Clipping Algorithm

Cf. [FvDFH90, 3.12.3].

First we test whether both endpoints are inside (and hence draw the line segment) or whether both are left of $ x=x_{\min}$, right of $ x=x_{\max}$, below $ y=y_{\min}$, or above $ y=y_{\max}$ (then we ignore line segment). Otherwise we split the line segment into two pieces at a clipping edge (and thus reject one part). Now we proceed iteratively.

A rather simple accept-reject test is the following:

Divide the plane into 9 regions and assign a 4 bit code to each:

...above top edge $ y>y_{\max}$
...below bottom edge $ y<y_{\min}$
...right of right edge $ x>x_{\max}$
...left of left edge $ x<x_{\min}$
mathcalculate the corresponding bit-codes for both endpoints.

Figure: Codes for the 9 regions associated to clipping rectangle

If both codes are zero then the line segment is completely inside the rectangle. If the bitwise-and of these codes is not zero then the line does not hit since both endpoints lie on the wrong side of at least one boundary line (corresponding to a bit equal to 1). Otherwise take a line which is met by the segment (for this find one non-zero bit), divide the given line at the intersection point in two parts and reject the one lying in the outside halfplane.

Figure: Example of Cohen-Sutherland line-clipping algorithm

Andreas Kriegl 2003-07-23