Liang–Barsky algorithm explained

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. So 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.

The algorithm uses the parametric form of a straight line:

x=x0+t(x1-x0)=x0+t\Deltax,

y=y0+t(y1-y0)=y0+t\Deltay.

A point is in the clip window, if

xmin\lex0+t\Deltax\lexmax

and

ymin\ley0+t\Deltay\leymax,

which can be expressed as the 4 inequalities

tpi\leqi,i=1,2,3,4,

where

\begin{align} p1&=-\Deltax,&q1&=x0-xmin,&&(left)\\ p2&=\Deltax,&q2&=xmax-x0,&&(right)\\ p3&=-\Deltay,&q3&=y0-ymin,&&(bottom)\\ p4&=\Deltay,&q4&=ymax-y0.&&(top) \end{align}

To compute the final line segment:

  1. A line parallel to a clipping window edge has

pi=0

for that boundary.
  1. If for that

i

,

qi<0

, then the line is completely outside and can be eliminated.
  1. When

pi<0

, the line proceeds outside to inside the clip window, and when

pi>0

, the line proceeds inside to outside.
  1. For nonzero

pi

,

u=qi/pi

gives

t

for the intersection point of the line and the window edge (possibly projected).
  1. The two actual intersections of the line with the window edges, if they exist, are described by

u1

and

u2

, calculated as follows. For

u1

, look at boundaries for which

pi<0

(i.e. outside to inside). Take

u1

to be the largest among

\{0,qi/pi\}

. For

u2

, look at boundaries for which

pi>0

(i.e. inside to outside). Take

u2

to be the minimum of

\{1,qi/pi\}

.
  1. If

u1>u2

, the line is entirely outside the clip window. If

u1<0<1<u2

it is entirely inside it.

// Liang—Barsky line-clipping algorithm

  1. include
  2. include
  3. include

using namespace std;

// this function gives the maximumfloat maxi(float arr[],int n)

// this function gives the minimumfloat mini(float arr[], int n)

void liang_barsky_clipper(float xmin, float ymin, float xmax, float ymax, float x1, float y1, float x2, float y2)

int main

See also

Algorithms used for the same purpose:

References

External links