Cohen Sutherland Line Clipping Algorithm in C and C++

Here you will learn about cohen sutherland line clipping algorithm in C and C++.

This is one of the oldest and most popular line clipping algorithm. To speed up the process this algorithm performs initial tests that reduce number of intersections that must be calculated. It does so by using a 4 bit code called as region code or outcodes. These codes identify location of the end point of line.

Each bit position indicates a direction, starting from the rightmost position of each bit indicates left, right, bottom, top respectively.

Once we establish region codes for both the endpoints of a line we determine whether the endpoint is visible, partially visible or invisible with the help of ANDing of the region codes.

There arises 3 cases which are explained in the algorithm below in step 4.

Also Read: Liang Barsky Line Clipping Algorithm in C and C++

Algorithm

1. Read 2 end points of line as p1(x1,y1) and p2(x2,y2)

2. Read 2 corner points of the clipping window (left-top and right-bottom) as (wx1,wy1) and (wx2,wy2)

3. Assign the region codes for 2 endpoints p1 and p2 using following steps:-

initialize code with 0000

Set bit 1 if x<wx1

Set bit 2 if x>wx2

Set bit 3 if y<wy2

Set bit 4 if y>wy1

4. Check for visibility of line

  1. If region codes for both endpoints are zero then line is completely visible. Draw the line go to step 9.
  2. If region codes for endpoints are not zero and logical ANDing of them is also nonzero then line is invisible. Discard the line and move to step 9.
  3. If it does not satisfy 4.a and 4.b then line is partially visible.

5. Determine the intersecting edge of clipping window as follows:-

  1. If region codes for both endpoints are nonzero find intersection points p1’ and p2’ with boundary edges.
  2. If region codes for any one end point is non zero then find intersection point p1’ or p2’.

6. Divide the line segments considering intersection points.

7. Reject line segment if any end point of line appears outside of any boundary.

8. Draw the clipped line segment.

9. Stop.

Program for Cohen Sutherland Line Clipping Algorithm in C and C++

C Program

C++ Program

Output

Cohen Sutherland Line Clipping Algorithm in C and C++

Before Clipping

Cohen Sutherland Line Clipping Algorithm in C and C++

After Clipping

Cohen Sutherland Line Clipping Algorithm in C and C++

This article is submitted by Rahul Maheshwari. You can connect with him on facebook.

Comment below if you have doubts or found any information incorrect in above cohen sutherland line clipping algorithm in C and C++.

One thought on “Cohen Sutherland Line Clipping Algorithm in C and C++

Leave a Reply

Your email address will not be published. Required fields are marked *