In computer graphics, the Liang–Barsky algorithm (named after You-Dong Liang and Brian A. Barsky) is a line clipping algorithm. The Liang–Barsky algorithm uses the parametric equation of a line and inequalities describing the range of the clipping window to determine the intersections between the line and the clip window. With these intersections it knows which portion of the line should be drawn. This algorithm is significantly more efficient than Cohen–Sutherland.The idea of the Liang-Barsky clipping algorithm is to do as much testing as possible before computing line intersections.
Consider first the usual parametric form of a straight line:
A point is in the clip window, if
and
which can be expressed as the 4 inequalities
where
To compute the final line segment:
- A line parallel to a clipping window edge has
p i = 0 for that boundary. - If for that
i ,q i < 0 , the line is completely outside and can be eliminated. - When
p i < 0 the line proceeds outside to inside the clip window and whenp i > 0 , the line proceeds inside to outside. - For nonzero
p k u = q i p i - For each line, calculate
u 1 u 2 u 1 p i < 0 (i.e. outside to inside). Takeu 1 { 0 , q i p i } . Foru 2 p i > 0 (i.e. inside to outside). Takeu 2 { 1 , q i p i } . Ifu 1 > u 2