Line Clipping | Set 2 (Cyrus Beck Algorithm)
Cyrus Beck is a line clipping algorithm that is made for convex polygons. It allows line clipping for non-rectangular windows, unlike Cohen Sutherland or Nicholl Le Nicholl. It also removes the repeated clipping needed in Cohen Sutherland.
Input: 1. Convex area of interest which is defined by a set of coordinates given in a clockwise fashion. 2. vertices which are an array of coordinates: consisting of pairs (x, y) 3. n which is the number of vertices 4. A line to be clipped given by a set of coordinates. 5. line which is an array of coordinates: consisting of two pairs, (x0, y0) and (x1, y1) Output: 1. Coordinates of line clipping which is the Accepted clipping 2. Coordinates (-1, -1) which is the Rejected clipping
- Normals of every edge is calculated.
- Vector for the clipping line is calculated.
- Dot product between the difference of one vertex per edge and one selected end point of the clipping line and the normal of the edge is calculated (for all edges).
- Dot product between the vector of the clipping line and the normal of edge (for all edges) is calculated.
- The former dot product is divided by the latter dot product and multiplied by -1. This is ‘t’.
- The values of ‘t’ are classified as entering or exiting (from all edges) by observing their denominators (latter dot product).
- One value of ‘t’ is chosen from each group, and put into the parametric form of a line to calculate the coordinates.
- If the entering ‘t’ value is greater than the exiting ‘t’ value, then the clipping line is rejected.
- Case 1: The line is partially inside the clipping window:
0 < tE < tL < 1 where tE is 't' value for entering intersection point tL is 't' value for exiting intersection point
- Case 2: The line has one point inside or both sides inside the window or the intersection points are on the end points of the line:
0 ≤ tE ≤ tL ≤ 1
- Case 3: The line is completely outside the window:
tL < tE
First, calculate the parametric form of the line to be clipped and then follow the algorithm.
P0 - PEi
P1 - P0
Ni . (P0 - PEi) Ni . (P1 - P0) where i -> ith edge of the convex polygon
Ni . (P0 - PEi) t = ------------------ -(Ni . (P1 - P0))
Implementation: Here is an implementation of the above steps in SFML C++ Graphics Library. You can also press any key to unclip the line and press any key to clip the line.
(102, 50) (240, 109)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.