# Liang-Barsky Line Clipping Algorithm with C/C++

Theory
In Liang-Barsky algorithm, we first write the point-clipping conditions in parametric form as

Each of these for inequalities can be expressed as , k = 1, 2, 3, …..
where parameter p and q are defined as

Any line that is parallel to one of the clipping boundaries has pk = 0 for the value of k corresponding to that boundary. If, for that value of k, we also find qk < 0, then the line is completely outside the boundary and can be eliminated from further consideration. If qk >=0, the line is inside the parallel clipping boundary.
When pk <0, the infinite extension of the line proceeds from the outside to the inside of the inside of the infinite extension of this particular boundary. If pk > 0, the line proceeds from the insides to the outside. For a nonzero value of pk, we can calculate the value of u that corresponds to the point where the infinitely extended line intersects the extension of boundary k as u = qk / pk.

For each line, we calculate values of parameters u1 and u2 that define that part of the line that lies within the clip rectangle. The value of u1 is determined by looking at the rectangle edges for which the line proceeds from the outside to inside (p < 0). For these edges, we calculate rk = qk / pk. The value of u1 is taken as the largest of the set consisting of 0 and the various values of r. Conversely, the value of u2 is determined by examining the boundaries for which the line proceeds from inside to outside (p > 0). A value of rk is calculated for each of these boundaries, and the value of u2 is minimum of the set consisting of 1 and the calculated r values. If u1 > u2, the line is completely outside the clip window and it can be rejected. Otherwise, the endpoints of the clipped line are calculated from the two values of parameter u.
Source Code

Output

SHARE Liang-Barsky Line Clipping Algorithm with C/C++