line_clipping::cohen_sutherland

Function clip_line

Source
pub fn clip_line(line: LineSegment, window: Window) -> Option<LineSegment>
Expand description

Implements the Cohen-Sutherland line clipping algorithm.

Returns the clipped line if the original line intersects the clipping window, or None if the original line is completely outside the clipping window.

Reference: Cohen-Sutherland algorithm

The Cohen-Sutherland algorithm is a line clipping algorithm that divides the 2D plane into 9 regions and then determines the region in which the line lies. If the line lies completely outside the clipping window, it is rejected. If the line lies completely inside the clipping window, it is accepted. If the line lies partially inside the clipping window, it is clipped.

The regions are defined as follows:

100110001010
000100000010
—–———–
010101000110

The algorithm works as follows:

  1. Determine the region in which the line’s starting point lies.
  2. Determine the region in which the line’s ending point lies.
  3. If both points lie in region 0000, the line is completely inside the clipping window and should be accepted.
  4. If both points lie in the same region that is not 0000, the line is completely outside the clipping window and should be rejected.
  5. If the points lie in different regions, the line is partially inside the clipping window and should be clipped.
  6. Clip the line using the Cohen-Sutherland algorithm.
  7. Repeat the process for the clipped line.

The Cohen-Sutherland algorithm is commonly used in computer graphics to clip lines against a rectangular window.

§Examples

use cohen_sutherland::clip_line;

let line = clip_line(
    Line { p1: Point { x: 0.0, y: 0.0 }, p2: Point { x: 10.0, y: 10.0 } },
    Window { x_min: 1.0, x_max: 9.0, y_min: 1.0, y_max: 9.0 },
);

assert_eq!(line, Some(Line { p1: Point { x: 1.0, y: 1.0 }, p2: Point { x: 9.0, y: 9.0 } }));