title: Liang–Barsky algorithm
text: # Liang–Barsky algorithm
  
  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=x_{0}+t(x_{1}-x_{0})=x_{0}+t\Delta x,$
      $y=y_{0}+t(y_{1}-y_{0})=y_{0}+t\Delta y.$
  
  A point is in the clip window, if
  
      $x_{\text{min}}\leq x_{0}+t\Delta x\leq x_{\text{max}}$
  
  and
  
      $y_{\text{min}}\leq y_{0}+t\Delta y\leq y_{\text{max}},$
  
  which can be expressed as the 4 inequalities
  
      $tp_{i}\leq q_{i},\quad i=1,2,3,4,$
  
  where
  
      Failed to parse (SVG (MathML can be enabled via browser plugin): Invalid response ("Math extension cannot connect to Restbase.") from server "http://localhost:6011/en.wikipedia.org/v1/":): {\displaystyle \begin{align} p_1 &= -\Delta x, & q_1 &= x_0 - x_\text{min}, & &\text{(left)} \\ p_2 &= \Delta x, & q_2 &= x_\text{max} - x_0, & &\text{(right)} \\ p_3 &= -\Delta y, & q_3 &= y_0 - y_\text{min}, & &\text{(bottom)} \\ p_4 &= \Delta y, & q_4 &= y_\text{max} - y_0. & &\text{(top)} \end{align} }
  
  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$, then the line is completely outside and can be eliminated.
  * When $p_{i}<0$, the line proceeds outside to inside the clip window, and when $p_{i}>0$, the line proceeds inside to outside.
  * For nonzero $p_{i}$, $u=q_{i}/p_{i}$ gives $t$ for the intersection point of the line and the window edge (possibly projected).
  * The two actual intersections of the line with the window edges, if they exist, are described by $u_{1}$ and $u_{2}$, calculated as follows. For $u_{1}$, look at boundaries for which $p_{i}<0$ (i.e. outside to inside). Take $u_{1}$ to be the largest among $\{0,q_{i}/p_{i}\}$. For $u_{2}$, look at boundaries for which $p_{i}>0$ (i.e. inside to outside). Take $u_{2}$ to be the minimum of $\{1,q_{i}/p_{i}\}$.
  * If $u_{1}>u_{2}$, the line is entirely outside the clip window. If $u_{1}<0<1<u_{2}$ it is entirely inside it.
  